2021-08-19 07:57:32 +00:00
|
|
|
//
|
|
|
|
// Copyright 2021 Vulcanize, Inc.
|
|
|
|
//
|
|
|
|
|
|
|
|
import assert from 'assert';
|
2021-12-13 10:08:34 +00:00
|
|
|
import { DeepPartial, FindConditions, FindManyOptions } from 'typeorm';
|
2021-08-20 13:32:57 +00:00
|
|
|
import debug from 'debug';
|
2021-09-21 11:13:55 +00:00
|
|
|
import { ethers } from 'ethers';
|
2022-10-11 08:11:26 +00:00
|
|
|
import _ from 'lodash';
|
|
|
|
import { sha256 } from 'multiformats/hashes/sha2';
|
|
|
|
import { CID } from 'multiformats/cid';
|
2021-08-19 07:57:32 +00:00
|
|
|
|
2022-10-11 08:11:26 +00:00
|
|
|
import * as codec from '@ipld/dag-cbor';
|
2022-09-09 11:43:01 +00:00
|
|
|
import { EthClient } from '@cerc-io/ipld-eth-client';
|
|
|
|
import { GetStorageAt, getStorageValue, StorageLayout } from '@cerc-io/solidity-mapper';
|
2021-08-20 13:32:57 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
import {
|
|
|
|
BlockProgressInterface,
|
|
|
|
DatabaseInterface,
|
|
|
|
IndexerInterface,
|
|
|
|
EventInterface,
|
|
|
|
ContractInterface,
|
|
|
|
SyncStatusInterface,
|
|
|
|
StateInterface,
|
|
|
|
StateKind
|
|
|
|
} from './types';
|
|
|
|
import { UNKNOWN_EVENT_NAME, JOB_KIND_CONTRACT, QUEUE_EVENT_PROCESSING, DIFF_MERGE_BATCH_SIZE } from './constants';
|
2021-12-08 05:41:29 +00:00
|
|
|
import { JobQueue } from './job-queue';
|
2021-12-13 10:08:34 +00:00
|
|
|
import { Where, QueryOptions } from './database';
|
2022-10-11 08:11:26 +00:00
|
|
|
import { ServerConfig } from './config';
|
2021-08-20 13:32:57 +00:00
|
|
|
|
2022-07-13 09:10:42 +00:00
|
|
|
const DEFAULT_MAX_EVENTS_BLOCK_RANGE = 1000;
|
2021-08-24 06:25:29 +00:00
|
|
|
|
2021-08-20 13:32:57 +00:00
|
|
|
const log = debug('vulcanize:indexer');
|
2021-08-19 07:57:32 +00:00
|
|
|
|
2021-09-21 11:13:55 +00:00
|
|
|
export interface ValueResult {
|
|
|
|
value: any;
|
|
|
|
proof?: {
|
|
|
|
data: string;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
export interface StateStatus {
|
2022-10-11 08:11:26 +00:00
|
|
|
init?: number;
|
|
|
|
diff?: number;
|
|
|
|
checkpoint?: number;
|
|
|
|
// eslint-disable-next-line camelcase
|
|
|
|
diff_staged?: number;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
export type ResultState = {
|
2022-10-11 08:11:26 +00:00
|
|
|
block: {
|
|
|
|
cid: string;
|
|
|
|
hash: string;
|
|
|
|
number: number;
|
|
|
|
timestamp: number;
|
|
|
|
parentHash: string;
|
|
|
|
};
|
|
|
|
contractAddress: string;
|
|
|
|
cid: string;
|
|
|
|
kind: string;
|
|
|
|
data: string;
|
|
|
|
};
|
|
|
|
|
2021-08-19 07:57:32 +00:00
|
|
|
export class Indexer {
|
2022-10-11 08:11:26 +00:00
|
|
|
_serverConfig: ServerConfig;
|
2021-08-19 07:57:32 +00:00
|
|
|
_db: DatabaseInterface;
|
2021-12-06 11:52:09 +00:00
|
|
|
_ethClient: EthClient;
|
2021-10-22 09:50:11 +00:00
|
|
|
_getStorageAt: GetStorageAt;
|
|
|
|
_ethProvider: ethers.providers.BaseProvider;
|
2021-12-08 05:41:29 +00:00
|
|
|
_jobQueue: JobQueue;
|
2021-08-19 07:57:32 +00:00
|
|
|
|
2021-12-08 05:41:29 +00:00
|
|
|
_watchedContracts: { [key: string]: ContractInterface } = {};
|
2022-10-19 09:54:14 +00:00
|
|
|
_stateStatusMap: { [key: string]: StateStatus } = {};
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
constructor (
|
|
|
|
serverConfig: ServerConfig,
|
|
|
|
db: DatabaseInterface,
|
|
|
|
ethClient: EthClient,
|
|
|
|
ethProvider: ethers.providers.BaseProvider,
|
2022-10-19 09:54:14 +00:00
|
|
|
jobQueue: JobQueue
|
2022-10-11 08:11:26 +00:00
|
|
|
) {
|
|
|
|
this._serverConfig = serverConfig;
|
2021-08-19 07:57:32 +00:00
|
|
|
this._db = db;
|
2021-12-06 11:52:09 +00:00
|
|
|
this._ethClient = ethClient;
|
2021-10-22 09:50:11 +00:00
|
|
|
this._ethProvider = ethProvider;
|
2021-12-08 05:41:29 +00:00
|
|
|
this._jobQueue = jobQueue;
|
2021-12-06 11:52:09 +00:00
|
|
|
this._getStorageAt = this._ethClient.getStorageAt.bind(this._ethClient);
|
2021-08-20 13:32:57 +00:00
|
|
|
}
|
|
|
|
|
2021-12-08 05:41:29 +00:00
|
|
|
async fetchContracts (): Promise<void> {
|
|
|
|
assert(this._db.getContracts);
|
|
|
|
|
|
|
|
const contracts = await this._db.getContracts();
|
|
|
|
|
|
|
|
this._watchedContracts = contracts.reduce((acc: { [key: string]: ContractInterface }, contract) => {
|
|
|
|
acc[contract.address] = contract;
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
2021-08-20 13:32:57 +00:00
|
|
|
async getSyncStatus (): Promise<SyncStatusInterface | undefined> {
|
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
|
|
|
res = await this._db.getSyncStatus(dbTx);
|
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
2021-08-19 07:57:32 +00:00
|
|
|
}
|
|
|
|
|
2021-10-20 10:36:03 +00:00
|
|
|
async updateSyncStatusIndexedBlock (blockHash: string, blockNumber: number, force = false): Promise<SyncStatusInterface> {
|
2021-08-19 07:57:32 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
2021-10-20 10:36:03 +00:00
|
|
|
res = await this._db.updateSyncStatusIndexedBlock(dbTx, blockHash, blockNumber, force);
|
2021-08-19 07:57:32 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2021-12-17 06:27:09 +00:00
|
|
|
async updateSyncStatusChainHead (blockHash: string, blockNumber: number, force = false): Promise<SyncStatusInterface> {
|
2021-08-19 07:57:32 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
2021-12-17 06:27:09 +00:00
|
|
|
res = await this._db.updateSyncStatusChainHead(dbTx, blockHash, blockNumber, force);
|
2021-08-19 07:57:32 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2021-10-20 10:36:03 +00:00
|
|
|
async updateSyncStatusCanonicalBlock (blockHash: string, blockNumber: number, force = false): Promise<SyncStatusInterface> {
|
2021-08-19 07:57:32 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
2021-10-20 10:36:03 +00:00
|
|
|
res = await this._db.updateSyncStatusCanonicalBlock(dbTx, blockHash, blockNumber, force);
|
2021-08-19 07:57:32 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2021-12-03 10:53:11 +00:00
|
|
|
async getBlocks (blockFilter: { blockNumber?: number, blockHash?: string }): Promise<any> {
|
|
|
|
assert(blockFilter.blockHash || blockFilter.blockNumber);
|
2022-06-08 06:43:52 +00:00
|
|
|
const result = await this._ethClient.getBlocks(blockFilter);
|
2021-12-03 10:53:11 +00:00
|
|
|
const { allEthHeaderCids: { nodes: blocks } } = result;
|
|
|
|
|
|
|
|
if (!blocks.length) {
|
|
|
|
try {
|
|
|
|
const blockHashOrNumber = blockFilter.blockHash || blockFilter.blockNumber as string | number;
|
|
|
|
await this._ethProvider.getBlock(blockHashOrNumber);
|
|
|
|
} catch (error: any) {
|
|
|
|
// eth_getBlockByHash will update statediff but takes some time.
|
|
|
|
// The block is not returned immediately and an error is thrown so that it is fetched in the next job retry.
|
|
|
|
if (error.code !== ethers.utils.Logger.errors.SERVER_ERROR) {
|
2021-10-22 09:50:11 +00:00
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
2021-12-16 11:46:48 +00:00
|
|
|
log('Block not found. Fetching block after RPC call.');
|
2021-12-03 10:53:11 +00:00
|
|
|
}
|
2021-10-22 09:50:11 +00:00
|
|
|
}
|
2021-12-03 10:53:11 +00:00
|
|
|
|
|
|
|
return blocks;
|
2021-08-20 13:32:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async getBlockProgress (blockHash: string): Promise<BlockProgressInterface | undefined> {
|
|
|
|
return this._db.getBlockProgress(blockHash);
|
|
|
|
}
|
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
async getBlockProgressEntities (where: FindConditions<BlockProgressInterface>, options: FindManyOptions<BlockProgressInterface>): Promise<BlockProgressInterface[]> {
|
|
|
|
return this._db.getBlockProgressEntities(where, options);
|
|
|
|
}
|
|
|
|
|
2021-08-19 07:57:32 +00:00
|
|
|
async getBlocksAtHeight (height: number, isPruned: boolean): Promise<BlockProgressInterface[]> {
|
|
|
|
return this._db.getBlocksAtHeight(height, isPruned);
|
|
|
|
}
|
|
|
|
|
2021-08-23 11:36:35 +00:00
|
|
|
async markBlocksAsPruned (blocks: BlockProgressInterface[]): Promise<void> {
|
2021-08-19 07:57:32 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
|
|
|
try {
|
2021-08-23 11:36:35 +00:00
|
|
|
await this._db.markBlocksAsPruned(dbTx, blocks);
|
2021-08-19 07:57:32 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
2021-08-20 13:32:57 +00:00
|
|
|
|
2021-12-10 05:14:10 +00:00
|
|
|
async updateBlockProgress (block: BlockProgressInterface, lastProcessedEventIndex: number): Promise<BlockProgressInterface> {
|
2021-08-20 13:32:57 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
|
|
|
try {
|
2021-12-10 05:14:10 +00:00
|
|
|
const updatedBlock = await this._db.updateBlockProgress(dbTx, block, lastProcessedEventIndex);
|
2021-08-20 13:32:57 +00:00
|
|
|
await dbTx.commitTransaction();
|
2021-12-10 05:14:10 +00:00
|
|
|
|
|
|
|
return updatedBlock;
|
2021-08-20 13:32:57 +00:00
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async getEvent (id: string): Promise<EventInterface | undefined> {
|
|
|
|
return this._db.getEvent(id);
|
|
|
|
}
|
|
|
|
|
2022-10-11 08:11:26 +00:00
|
|
|
async fetchBlockWithEvents (block: DeepPartial<BlockProgressInterface>, fetchAndSaveEvents: (block: DeepPartial<BlockProgressInterface>) => Promise<BlockProgressInterface>): Promise<BlockProgressInterface> {
|
2021-08-20 13:32:57 +00:00
|
|
|
assert(block.blockHash);
|
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
log(`getBlockEvents: fetching from upstream server ${block.blockHash}`);
|
|
|
|
const blockProgress = await fetchAndSaveEvents(block);
|
|
|
|
log(`getBlockEvents: fetched for block: ${blockProgress.blockHash} num events: ${blockProgress.numEvents}`);
|
2021-08-20 13:32:57 +00:00
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
return blockProgress;
|
2021-08-20 13:32:57 +00:00
|
|
|
}
|
|
|
|
|
2022-10-11 08:11:26 +00:00
|
|
|
async fetchBlockEvents (block: DeepPartial<BlockProgressInterface>, fetchEvents: (block: DeepPartial<BlockProgressInterface>) => Promise<DeepPartial<EventInterface>[]>): Promise<DeepPartial<EventInterface>[]> {
|
|
|
|
assert(block.blockHash);
|
|
|
|
|
|
|
|
log(`getBlockEvents: fetching from upstream server ${block.blockHash}`);
|
2022-10-13 11:37:46 +00:00
|
|
|
console.time(`time:indexer#fetchBlockEvents-fetchAndSaveEvents-${block.blockHash}`);
|
2022-10-11 08:11:26 +00:00
|
|
|
const events = await fetchEvents(block);
|
2022-10-13 11:37:46 +00:00
|
|
|
console.timeEnd(`time:indexer#fetchBlockEvents-fetchAndSaveEvents-${block.blockHash}`);
|
2022-10-11 08:11:26 +00:00
|
|
|
log(`getBlockEvents: fetched for block: ${block.blockHash} num events: ${events.length}`);
|
|
|
|
|
|
|
|
return events;
|
|
|
|
}
|
|
|
|
|
|
|
|
async saveBlockProgress (block: DeepPartial<BlockProgressInterface>): Promise<BlockProgressInterface> {
|
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
|
|
|
res = await this._db.saveBlockProgress(dbTx, block);
|
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
async getBlockEvents (blockHash: string, where: Where, queryOptions: QueryOptions): Promise<Array<EventInterface>> {
|
|
|
|
return this._db.getBlockEvents(blockHash, where, queryOptions);
|
2021-08-20 13:32:57 +00:00
|
|
|
}
|
2021-08-23 11:36:35 +00:00
|
|
|
|
2021-10-12 10:32:56 +00:00
|
|
|
async getEventsByFilter (blockHash: string, contract?: string, name?: string): Promise<Array<EventInterface>> {
|
2022-05-23 13:24:14 +00:00
|
|
|
// TODO: Uncomment after implementing hot reload of watched contracts in server process.
|
|
|
|
// This doesn't affect functionality as we already have a filter condition on the contract in the query.
|
|
|
|
// if (contract) {
|
|
|
|
// const watchedContract = await this.isWatchedContract(contract);
|
|
|
|
// if (!watchedContract) {
|
|
|
|
// throw new Error('Not a watched contract');
|
|
|
|
// }
|
|
|
|
// }
|
2021-09-21 11:13:55 +00:00
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
const where: Where = {
|
|
|
|
eventName: [{
|
|
|
|
value: UNKNOWN_EVENT_NAME,
|
|
|
|
not: true,
|
|
|
|
operator: 'equals'
|
|
|
|
}]
|
2021-09-21 11:13:55 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if (contract) {
|
2021-12-13 10:08:34 +00:00
|
|
|
where.contract = [
|
|
|
|
{ value: contract, operator: 'equals', not: false }
|
|
|
|
];
|
2021-09-21 11:13:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (name) {
|
2021-12-13 10:08:34 +00:00
|
|
|
where.eventName = [
|
|
|
|
{ value: name, operator: 'equals', not: false }
|
|
|
|
];
|
2021-09-21 11:13:55 +00:00
|
|
|
}
|
|
|
|
|
2021-12-13 10:08:34 +00:00
|
|
|
const events = await this._db.getBlockEvents(blockHash, where);
|
2021-09-21 11:13:55 +00:00
|
|
|
log(`getEvents: db hit, num events: ${events.length}`);
|
|
|
|
|
|
|
|
return events;
|
|
|
|
}
|
|
|
|
|
2021-10-20 12:19:44 +00:00
|
|
|
async removeUnknownEvents (eventEntityClass: new () => EventInterface, block: BlockProgressInterface): Promise<void> {
|
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this._db.removeEntities(
|
|
|
|
dbTx,
|
|
|
|
eventEntityClass,
|
|
|
|
{
|
|
|
|
where: {
|
|
|
|
block: { id: block.id },
|
|
|
|
eventName: UNKNOWN_EVENT_NAME
|
|
|
|
},
|
|
|
|
relations: ['block']
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-23 11:36:35 +00:00
|
|
|
async getAncestorAtDepth (blockHash: string, depth: number): Promise<string> {
|
|
|
|
return this._db.getAncestorAtDepth(blockHash, depth);
|
|
|
|
}
|
2021-08-24 06:25:29 +00:00
|
|
|
|
|
|
|
async saveEventEntity (dbEvent: EventInterface): Promise<EventInterface> {
|
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
2021-12-02 09:58:03 +00:00
|
|
|
res = await this._db.saveEventEntity(dbTx, dbEvent);
|
2021-08-24 06:25:29 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2022-10-11 08:11:26 +00:00
|
|
|
async saveEvents (dbEvents: EventInterface[]): Promise<void> {
|
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
|
|
|
try {
|
|
|
|
await this._db.saveEvents(dbTx, dbEvents);
|
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-08-24 06:25:29 +00:00
|
|
|
async getProcessedBlockCountForRange (fromBlockNumber: number, toBlockNumber: number): Promise<{ expected: number, actual: number }> {
|
|
|
|
return this._db.getProcessedBlockCountForRange(fromBlockNumber, toBlockNumber);
|
|
|
|
}
|
|
|
|
|
2022-07-13 09:10:42 +00:00
|
|
|
async getEventsInRange (fromBlockNumber: number, toBlockNumber: number, maxBlockRange: number = DEFAULT_MAX_EVENTS_BLOCK_RANGE): Promise<Array<EventInterface>> {
|
2021-08-24 06:25:29 +00:00
|
|
|
if (toBlockNumber <= fromBlockNumber) {
|
|
|
|
throw new Error('toBlockNumber should be greater than fromBlockNumber');
|
|
|
|
}
|
|
|
|
|
2022-07-13 09:10:42 +00:00
|
|
|
if (maxBlockRange > -1 && (toBlockNumber - fromBlockNumber) > maxBlockRange) {
|
|
|
|
throw new Error(`Max range (${maxBlockRange}) exceeded`);
|
2021-08-24 06:25:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return this._db.getEventsInRange(fromBlockNumber, toBlockNumber);
|
|
|
|
}
|
2021-09-21 11:13:55 +00:00
|
|
|
|
2022-10-11 08:11:26 +00:00
|
|
|
isWatchedContract (address : string): ContractInterface | undefined {
|
2021-12-08 05:41:29 +00:00
|
|
|
return this._watchedContracts[address];
|
|
|
|
}
|
|
|
|
|
2022-01-06 13:02:08 +00:00
|
|
|
getContractsByKind (kind: string): ContractInterface[] {
|
|
|
|
const watchedContracts = Object.values(this._watchedContracts)
|
|
|
|
.filter(contract => contract.kind === kind);
|
|
|
|
|
|
|
|
return watchedContracts;
|
|
|
|
}
|
|
|
|
|
2022-07-18 08:34:59 +00:00
|
|
|
getWatchedContracts (): ContractInterface[] {
|
|
|
|
return Object.values(this._watchedContracts);
|
|
|
|
}
|
|
|
|
|
2021-10-20 12:25:54 +00:00
|
|
|
async watchContract (address: string, kind: string, checkpoint: boolean, startingBlock: number): Promise<void> {
|
2021-12-08 05:41:29 +00:00
|
|
|
assert(this._db.saveContract);
|
2022-10-19 09:54:14 +00:00
|
|
|
this.updateStateStatusMap(address, {});
|
2021-12-08 05:41:29 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
2021-11-18 12:33:36 +00:00
|
|
|
// Use the checksum address (https://docs.ethers.io/v5/api/utils/address/#utils-getAddress) if input to address is a contract address.
|
|
|
|
// If a contract identifier is passed as address instead, no need to convert to checksum address.
|
|
|
|
// Customize: use the kind input to filter out non-contract-address input to address.
|
|
|
|
const contractAddress = (kind === '__protocol__') ? address : ethers.utils.getAddress(address);
|
2021-12-08 05:41:29 +00:00
|
|
|
|
|
|
|
try {
|
2021-10-20 12:25:54 +00:00
|
|
|
const contract = await this._db.saveContract(dbTx, contractAddress, kind, checkpoint, startingBlock);
|
2021-12-08 05:41:29 +00:00
|
|
|
this.cacheContract(contract);
|
|
|
|
await dbTx.commitTransaction();
|
|
|
|
|
|
|
|
await this._jobQueue.pushJob(
|
|
|
|
QUEUE_EVENT_PROCESSING,
|
|
|
|
{
|
|
|
|
kind: JOB_KIND_CONTRACT,
|
|
|
|
contract
|
|
|
|
},
|
|
|
|
{ priority: 1 }
|
|
|
|
);
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
2021-09-21 11:13:55 +00:00
|
|
|
|
2021-12-08 05:41:29 +00:00
|
|
|
cacheContract (contract: ContractInterface): void {
|
|
|
|
this._watchedContracts[contract.address] = contract;
|
2021-09-21 11:13:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async getStorageValue (storageLayout: StorageLayout, blockHash: string, token: string, variable: string, ...mappingKeys: any[]): Promise<ValueResult> {
|
|
|
|
return getStorageValue(
|
|
|
|
storageLayout,
|
|
|
|
this._getStorageAt,
|
|
|
|
blockHash,
|
|
|
|
token,
|
|
|
|
variable,
|
|
|
|
...mappingKeys
|
|
|
|
);
|
|
|
|
}
|
2022-08-04 11:39:30 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
getStateData (state: StateInterface): any {
|
|
|
|
return codec.decode(Buffer.from(state.data));
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async getLatestStateIndexedBlock (): Promise<BlockProgressInterface> {
|
|
|
|
// Get current stateSyncStatus.
|
|
|
|
const stateSyncStatus = await this._db.getStateSyncStatus();
|
|
|
|
assert(stateSyncStatus, 'stateSyncStatus not found');
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get all the blocks at height stateSyncStatus.latestIndexedBlockNumber.
|
|
|
|
const blocksAtHeight = await this.getBlocksAtHeight(stateSyncStatus.latestIndexedBlockNumber, false);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// There can exactly one block at stateSyncStatus.latestIndexedBlockNumber height.
|
2022-10-11 08:11:26 +00:00
|
|
|
assert(blocksAtHeight.length === 1);
|
|
|
|
|
|
|
|
return blocksAtHeight[0];
|
|
|
|
}
|
|
|
|
|
|
|
|
async processCheckpoint (indexer: IndexerInterface, blockHash: string, checkpointInterval: number): Promise<void> {
|
|
|
|
// Get all the contracts.
|
|
|
|
const contracts = Object.values(this._watchedContracts);
|
|
|
|
|
|
|
|
// Getting the block for checkpoint.
|
|
|
|
const block = await this.getBlockProgress(blockHash);
|
|
|
|
assert(block);
|
|
|
|
|
|
|
|
// For each contract, merge the diff till now to create a checkpoint.
|
|
|
|
for (const contract of contracts) {
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get State status for the contract.
|
|
|
|
const stateStatus = this._stateStatusMap[contract.address];
|
|
|
|
assert(stateStatus, `State status for contract ${contract.address} not found`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
const initBlockNumber = stateStatus.init;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// Check if contract has checkpointing on.
|
|
|
|
// Check if it's time for a checkpoint or the init is in current block.
|
|
|
|
if (
|
|
|
|
contract.checkpoint &&
|
|
|
|
(block.blockNumber % checkpointInterval === 0 || initBlockNumber === block.blockNumber)
|
|
|
|
) {
|
|
|
|
await this.createCheckpoint(indexer, contract.address, block);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async processCLICheckpoint (indexer: IndexerInterface, contractAddress: string, blockHash?: string): Promise<string | undefined> {
|
|
|
|
// Getting the block for checkpoint.
|
|
|
|
let block;
|
|
|
|
|
|
|
|
if (blockHash) {
|
|
|
|
block = await this.getBlockProgress(blockHash);
|
|
|
|
} else {
|
2022-10-19 09:54:14 +00:00
|
|
|
// In case of empty blockHash from checkpoint CLI, get the latest indexed block from stateSyncStatus for the checkpoint.
|
|
|
|
block = await this.getLatestStateIndexedBlock();
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
assert(block);
|
|
|
|
|
|
|
|
const checkpointBlockHash = await this.createCheckpoint(indexer, contractAddress, block);
|
|
|
|
assert(checkpointBlockHash, 'Checkpoint not created');
|
|
|
|
|
|
|
|
return checkpointBlockHash;
|
|
|
|
}
|
|
|
|
|
|
|
|
async createStateCheckpoint (contractAddress: string, block: BlockProgressInterface, data: any): Promise<void> {
|
|
|
|
// Get the contract.
|
|
|
|
const contract = this._watchedContracts[contractAddress];
|
|
|
|
assert(contract, `Contract ${contractAddress} not watched`);
|
|
|
|
|
|
|
|
if (block.blockNumber < contract.startingBlock) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create a checkpoint from the hook data without being concerned about diffs.
|
2022-10-19 09:54:14 +00:00
|
|
|
const state = await this.prepareStateEntry(block, contractAddress, data, StateKind.Checkpoint);
|
|
|
|
await this.saveOrUpdateState(state);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async createInit (
|
|
|
|
indexer: IndexerInterface,
|
|
|
|
blockHash: string,
|
|
|
|
blockNumber: number
|
|
|
|
): Promise<void> {
|
|
|
|
// Get all the contracts.
|
|
|
|
const contracts = Object.values(this._watchedContracts);
|
|
|
|
|
|
|
|
// Create an initial state for each contract.
|
|
|
|
for (const contract of contracts) {
|
|
|
|
// Check if contract has checkpointing on.
|
|
|
|
if (contract.checkpoint) {
|
|
|
|
// Check if starting block not reached yet.
|
|
|
|
if (blockNumber < contract.startingBlock) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get State status for the contract.
|
|
|
|
const stateStatus = this._stateStatusMap[contract.address];
|
|
|
|
assert(stateStatus, `State status for contract ${contract.address} not found`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Check if a 'init' State already exists.
|
|
|
|
// Or if a 'diff' State already exists.
|
|
|
|
// Or if a 'checkpoint' State already exists.
|
|
|
|
// (A watcher with imported state won't have an init State, but it will have the imported checkpoint)
|
2022-10-11 08:11:26 +00:00
|
|
|
if (
|
2022-10-19 09:54:14 +00:00
|
|
|
stateStatus.init ||
|
|
|
|
stateStatus.diff ||
|
|
|
|
stateStatus.checkpoint
|
2022-10-11 08:11:26 +00:00
|
|
|
) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Call initial state hook.
|
|
|
|
assert(indexer.processInitialState);
|
|
|
|
const stateData = await indexer.processInitialState(contract.address, blockHash);
|
|
|
|
|
|
|
|
const block = await this.getBlockProgress(blockHash);
|
|
|
|
assert(block);
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
const state = await this.prepareStateEntry(block, contract.address, stateData, StateKind.Init);
|
|
|
|
await this.saveOrUpdateState(state);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async createDiffStaged (contractAddress: string, blockHash: string, data: any): Promise<void> {
|
|
|
|
const block = await this.getBlockProgress(blockHash);
|
|
|
|
assert(block);
|
|
|
|
|
|
|
|
// Get the contract.
|
|
|
|
const contract = this._watchedContracts[contractAddress];
|
|
|
|
assert(contract, `Contract ${contractAddress} not watched`);
|
|
|
|
|
|
|
|
if (block.blockNumber < contract.startingBlock) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Create a staged diff state.
|
|
|
|
const state = await this.prepareStateEntry(block, contractAddress, data, StateKind.DiffStaged);
|
|
|
|
await this.saveOrUpdateState(state);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async finalizeDiffStaged (blockHash: string): Promise<void> {
|
|
|
|
const block = await this.getBlockProgress(blockHash);
|
|
|
|
assert(block);
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get all the staged diff states for the given blockHash.
|
|
|
|
const stagedStates = await this._db.getStates({ block, kind: StateKind.DiffStaged });
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// For each staged block, create a diff block.
|
2022-10-19 09:54:14 +00:00
|
|
|
for (const stagedState of stagedStates) {
|
|
|
|
const data = codec.decode(Buffer.from(stagedState.data));
|
|
|
|
await this.createDiff(stagedState.contractAddress, block, data);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Remove all the staged diff states for current blockNumber.
|
2022-10-11 08:11:26 +00:00
|
|
|
// (Including staged diff blocks associated with pruned blocks)
|
2022-10-19 09:54:14 +00:00
|
|
|
await this.removeStates(block.blockNumber, StateKind.DiffStaged);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async createDiff (contractAddress: string, block: BlockProgressInterface, data: any): Promise<void> {
|
|
|
|
// Get the contract.
|
|
|
|
const contract = this._watchedContracts[contractAddress];
|
|
|
|
assert(contract, `Contract ${contractAddress} not watched`);
|
|
|
|
|
|
|
|
if (block.blockNumber < contract.startingBlock) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get State status for the contract.
|
|
|
|
const stateStatus = this._stateStatusMap[contractAddress];
|
|
|
|
assert(stateStatus, `State status for contract ${contractAddress} not found`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// Get the latest checkpoint block number.
|
2022-10-19 09:54:14 +00:00
|
|
|
const checkpointBlockNumber = stateStatus.checkpoint;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
if (!checkpointBlockNumber) {
|
|
|
|
// Get the initial state block number.
|
2022-10-19 09:54:14 +00:00
|
|
|
const initBlockNumber = stateStatus.init;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// There should be an initial state at least.
|
2022-10-19 09:54:14 +00:00
|
|
|
assert(initBlockNumber, `No initial state found for contract ${contractAddress}`);
|
2022-10-11 08:11:26 +00:00
|
|
|
} else if (checkpointBlockNumber === block.blockNumber) {
|
|
|
|
// Check if the latest checkpoint is in the same block if block number is same.
|
2022-10-19 09:54:14 +00:00
|
|
|
const checkpoint = await this._db.getLatestState(contractAddress, StateKind.Checkpoint);
|
2022-10-11 08:11:26 +00:00
|
|
|
assert(checkpoint);
|
|
|
|
|
|
|
|
assert(checkpoint.block.blockHash !== block.blockHash, 'Checkpoint already created for the block hash');
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
const state = await this.prepareStateEntry(block, contractAddress, data, StateKind.Diff);
|
|
|
|
await this.saveOrUpdateState(state);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async createCheckpoint (indexer: IndexerInterface, contractAddress: string, currentBlock: BlockProgressInterface): Promise<string | undefined> {
|
|
|
|
// Get the contract.
|
|
|
|
const contract = this._watchedContracts[contractAddress];
|
|
|
|
assert(contract, `Contract ${contractAddress} not watched`);
|
|
|
|
|
|
|
|
if (currentBlock.blockNumber < contract.startingBlock) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure the block is marked complete.
|
|
|
|
assert(currentBlock.isComplete, 'Block for a checkpoint should be marked as complete');
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get current stateSyncStatus.
|
|
|
|
const stateSyncStatus = await this._db.getStateSyncStatus();
|
|
|
|
assert(stateSyncStatus);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Make sure state for the block has been indexed.
|
|
|
|
assert(currentBlock.blockNumber <= stateSyncStatus.latestIndexedBlockNumber, 'State should be indexed for checkpoint at a block');
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// Call state checkpoint hook and check if default checkpoint is disabled.
|
|
|
|
assert(indexer.processStateCheckpoint);
|
|
|
|
const disableDefaultCheckpoint = await indexer.processStateCheckpoint(contractAddress, currentBlock.blockHash);
|
|
|
|
|
|
|
|
if (disableDefaultCheckpoint) {
|
|
|
|
// Return if default checkpoint is disabled.
|
|
|
|
// Return block hash for checkpoint CLI.
|
|
|
|
return currentBlock.blockHash;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fetch the latest 'checkpoint' | 'init' for the contract to fetch diffs after it.
|
2022-10-19 09:54:14 +00:00
|
|
|
let prevNonDiffState: StateInterface;
|
2022-10-11 08:11:26 +00:00
|
|
|
let diffStartBlockNumber: number;
|
2022-10-19 09:54:14 +00:00
|
|
|
const checkpointState = await this._db.getLatestState(contractAddress, StateKind.Checkpoint, currentBlock.blockNumber - 1);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
if (checkpointState) {
|
|
|
|
const checkpointBlockNumber = checkpointState.block.blockNumber;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
prevNonDiffState = checkpointState;
|
2022-10-11 08:11:26 +00:00
|
|
|
diffStartBlockNumber = checkpointBlockNumber;
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Update State status map with the latest checkpoint info.
|
2022-10-11 08:11:26 +00:00
|
|
|
// Essential while importing state as checkpoint at the snapshot block is added by import-state CLI.
|
2022-10-19 09:54:14 +00:00
|
|
|
// (job-runner won't have the updated State status)
|
|
|
|
this.updateStateStatusMap(contractAddress, { checkpoint: checkpointBlockNumber });
|
2022-10-11 08:11:26 +00:00
|
|
|
} else {
|
|
|
|
// There should be an initial state at least.
|
2022-10-19 09:54:14 +00:00
|
|
|
const initBlock = await this._db.getLatestState(contractAddress, StateKind.Init);
|
|
|
|
assert(initBlock, `No initial state found for contract ${contractAddress}`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
prevNonDiffState = initBlock;
|
2022-10-11 08:11:26 +00:00
|
|
|
// Take block number previous to initial state block as the checkpoint is to be created in the same block.
|
|
|
|
diffStartBlockNumber = initBlock.block.blockNumber - 1;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
const prevNonDiffStateData = codec.decode(Buffer.from(prevNonDiffState.data)) as any;
|
|
|
|
let data = {
|
|
|
|
state: prevNonDiffStateData.state
|
2022-10-11 08:11:26 +00:00
|
|
|
};
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
console.time(`time:indexer#createCheckpoint-${contractAddress}`);
|
|
|
|
|
|
|
|
// Fetching and merging all diff blocks after the latest 'checkpoint' | 'init'.
|
|
|
|
data = await this._mergeDiffsInRange(data, contractAddress, diffStartBlockNumber, currentBlock.blockNumber);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
const state = await this.prepareStateEntry(currentBlock, contractAddress, data, StateKind.Checkpoint);
|
|
|
|
await this.saveOrUpdateState(state);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
console.timeEnd(`time:indexer#createCheckpoint-${contractAddress}`);
|
2022-10-11 08:11:26 +00:00
|
|
|
return currentBlock.blockHash;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async prepareStateEntry (block: BlockProgressInterface, contractAddress: string, data: any, kind: StateKind):Promise<any> {
|
|
|
|
console.time('time:indexer#prepareStateEntry');
|
|
|
|
let stateEntry: StateInterface;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get State status for the contract.
|
|
|
|
const stateStatus = this._stateStatusMap[contractAddress];
|
|
|
|
assert(stateStatus, `State status for contract ${contractAddress} not found`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get an existing 'init' | 'diff' | 'diff_staged' | 'checkpoint' State for current block, contractAddress to update.
|
|
|
|
let currentState: StateInterface | undefined;
|
|
|
|
const prevStateBlockNumber = stateStatus[kind];
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Fetch previous State from DB if:
|
|
|
|
// present at the same height (to update)
|
|
|
|
// or for checkpoint kind (to build upon previous checkpoint)
|
|
|
|
if (kind === 'checkpoint' || (prevStateBlockNumber && prevStateBlockNumber === block.blockNumber)) {
|
|
|
|
const currentStates = await this._db.getStates({ block, contractAddress, kind });
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// There can be at most one State for a (block, contractAddress, kind) combination.
|
|
|
|
assert(currentStates.length <= 1);
|
|
|
|
currentState = currentStates[0];
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
if (currentState) {
|
|
|
|
// Update current State of same kind if it exists.
|
|
|
|
stateEntry = currentState;
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// Update the data field.
|
2022-10-19 09:54:14 +00:00
|
|
|
const oldData = codec.decode(Buffer.from(stateEntry.data));
|
2022-10-11 08:11:26 +00:00
|
|
|
data = _.merge(oldData, data);
|
|
|
|
} else {
|
2022-10-19 09:54:14 +00:00
|
|
|
// Create a new State instance.
|
|
|
|
stateEntry = this._db.getNewState();
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Fetch the parent State entry.
|
|
|
|
const parentState = await this._db.getLatestState(contractAddress, null, block.blockNumber);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Setting the meta-data for a State entry (done only once per State entry).
|
2022-10-11 08:11:26 +00:00
|
|
|
data.meta = {
|
|
|
|
id: contractAddress,
|
|
|
|
kind,
|
|
|
|
parent: {
|
2022-10-19 09:54:14 +00:00
|
|
|
'/': parentState ? parentState.cid : null
|
2022-10-11 08:11:26 +00:00
|
|
|
},
|
|
|
|
ethBlock: {
|
|
|
|
cid: {
|
|
|
|
'/': block.cid
|
|
|
|
},
|
|
|
|
num: block.blockNumber
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
// Encoding the data using dag-cbor codec.
|
|
|
|
const bytes = codec.encode(data);
|
|
|
|
|
|
|
|
// Calculating sha256 (multi)hash of the encoded data.
|
|
|
|
const hash = await sha256.digest(bytes);
|
|
|
|
|
|
|
|
// Calculating the CID: v1, code: dag-cbor, hash.
|
|
|
|
const cid = CID.create(1, codec.code, hash);
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Update stateEntry with new data.
|
|
|
|
stateEntry = Object.assign(stateEntry, {
|
2022-10-11 08:11:26 +00:00
|
|
|
block,
|
|
|
|
contractAddress,
|
|
|
|
cid: cid.toString(),
|
|
|
|
kind: data.meta.kind,
|
|
|
|
data: Buffer.from(bytes)
|
|
|
|
});
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
console.timeEnd('time:indexer#prepareStateEntry');
|
|
|
|
return stateEntry;
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async getStatesByHash (blockHash: string): Promise<StateInterface[]> {
|
2022-10-11 08:11:26 +00:00
|
|
|
const block = await this.getBlockProgress(blockHash);
|
|
|
|
assert(block);
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
return this._db.getStates({ block });
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async getStateByCID (cid: string): Promise<StateInterface | undefined> {
|
|
|
|
const ipldBlocks = await this._db.getStates({ cid });
|
2022-10-11 08:11:26 +00:00
|
|
|
|
|
|
|
// There can be only one IPLDBlock with a particular cid.
|
|
|
|
assert(ipldBlocks.length <= 1);
|
|
|
|
|
|
|
|
return ipldBlocks[0];
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async saveOrUpdateState (state: StateInterface): Promise<StateInterface> {
|
2022-10-11 08:11:26 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
let res;
|
|
|
|
|
|
|
|
try {
|
2022-10-19 09:54:14 +00:00
|
|
|
res = await this._db.saveOrUpdateState(dbTx, state);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Get State status for the contract.
|
|
|
|
const stateStatus = this._stateStatusMap[res.contractAddress];
|
|
|
|
assert(stateStatus, `State status for contract ${res.contractAddress} not found`);
|
2022-10-11 08:11:26 +00:00
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// Update the State status for the kind.
|
|
|
|
stateStatus[res.kind] = res.block.blockNumber;
|
2022-10-19 08:56:10 +00:00
|
|
|
|
|
|
|
await dbTx.commitTransaction();
|
2022-10-11 08:11:26 +00:00
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async removeStates (blockNumber: number, kind: StateKind): Promise<void> {
|
2022-10-11 08:11:26 +00:00
|
|
|
const dbTx = await this._db.createTransactionRunner();
|
|
|
|
|
|
|
|
try {
|
2022-10-19 09:54:14 +00:00
|
|
|
await this._db.removeStates(dbTx, blockNumber, kind);
|
2022-10-11 08:11:26 +00:00
|
|
|
await dbTx.commitTransaction();
|
|
|
|
} catch (error) {
|
|
|
|
await dbTx.rollbackTransaction();
|
|
|
|
throw error;
|
|
|
|
} finally {
|
|
|
|
await dbTx.release();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
async fetchStateStatus (): Promise<void> {
|
2022-10-11 08:11:26 +00:00
|
|
|
const contracts = Object.values(this._watchedContracts);
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
// TODO: Fire a single query for all contracts.
|
2022-10-11 08:11:26 +00:00
|
|
|
for (const contract of contracts) {
|
2022-10-19 09:54:14 +00:00
|
|
|
const initState = await this._db.getLatestState(contract.address, StateKind.Init);
|
|
|
|
const diffState = await this._db.getLatestState(contract.address, StateKind.Diff);
|
|
|
|
const diffStagedState = await this._db.getLatestState(contract.address, StateKind.DiffStaged);
|
|
|
|
const checkpointState = await this._db.getLatestState(contract.address, StateKind.Checkpoint);
|
|
|
|
|
|
|
|
this._stateStatusMap[contract.address] = {
|
|
|
|
init: initState?.block.blockNumber,
|
|
|
|
diff: diffState?.block.blockNumber,
|
|
|
|
diff_staged: diffStagedState?.block.blockNumber,
|
|
|
|
checkpoint: checkpointState?.block.blockNumber
|
2022-10-11 08:11:26 +00:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-19 09:54:14 +00:00
|
|
|
updateStateStatusMap (address: string, stateStatus: StateStatus): void {
|
|
|
|
// Get and update State status for the contract.
|
|
|
|
const oldStateStatus = this._stateStatusMap[address];
|
|
|
|
this._stateStatusMap[address] = _.merge(oldStateStatus, stateStatus);
|
2022-10-11 08:11:26 +00:00
|
|
|
}
|
|
|
|
|
2022-08-04 11:39:30 +00:00
|
|
|
parseEvent (logDescription: ethers.utils.LogDescription): { eventName: string, eventInfo: any } {
|
|
|
|
const eventName = logDescription.name;
|
|
|
|
|
|
|
|
const eventInfo = logDescription.eventFragment.inputs.reduce((acc: any, input, index) => {
|
|
|
|
acc[input.name] = this._parseLogArg(input, logDescription.args[index]);
|
|
|
|
|
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
|
|
|
|
return {
|
|
|
|
eventName,
|
|
|
|
eventInfo
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
_parseLogArg (param: ethers.utils.ParamType, arg: ethers.utils.Result): any {
|
|
|
|
if (ethers.utils.Indexed.isIndexed(arg)) {
|
|
|
|
// Get hash if indexed reference type.
|
|
|
|
return arg.hash;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ethers.BigNumber.isBigNumber(arg)) {
|
|
|
|
return arg.toBigInt();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (param.baseType === 'array') {
|
|
|
|
return arg.map(el => this._parseLogArg(param.arrayChildren, el));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (param.baseType === 'tuple') {
|
|
|
|
return param.components.reduce((acc: any, component) => {
|
|
|
|
acc[component.name] = this._parseLogArg(component, arg[component.name]);
|
|
|
|
return acc;
|
|
|
|
}, {});
|
|
|
|
}
|
|
|
|
|
|
|
|
return arg;
|
|
|
|
}
|
2022-10-19 09:54:14 +00:00
|
|
|
|
|
|
|
async _mergeDiffsInRange (data: { state: any }, contractAddress: string, startBlock: number, endBlock: number): Promise<{ state: any }> {
|
|
|
|
// Merge all diff blocks in the given range in batches.
|
|
|
|
for (let i = startBlock; i < endBlock;) {
|
|
|
|
const endBlockHeight = Math.min(i + DIFF_MERGE_BATCH_SIZE, endBlock);
|
|
|
|
|
|
|
|
console.time(`time:indexer#_mergeDiffsInRange-${i}-${endBlockHeight}-${contractAddress}`);
|
|
|
|
const diffBlocks = await this._db.getDiffStatesInRange(contractAddress, i, endBlockHeight);
|
|
|
|
|
|
|
|
// Merge all diff blocks in the current batch.
|
|
|
|
for (const diffBlock of diffBlocks) {
|
|
|
|
const diff = codec.decode(Buffer.from(diffBlock.data)) as any;
|
|
|
|
data.state = _.merge(data.state, diff.state);
|
|
|
|
}
|
|
|
|
|
|
|
|
i = endBlockHeight;
|
|
|
|
console.timeEnd(`time:indexer#_mergeDiffsInRange-${i}-${endBlockHeight}-${contractAddress}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return data;
|
|
|
|
}
|
2021-08-19 07:57:32 +00:00
|
|
|
}
|