@ethersproject/abstract-provider#BlockTag TypeScript Examples

The following examples show how to use @ethersproject/abstract-provider#BlockTag. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataProvider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the transaction receipt for a transaction.
   * @param txHash The transaction hash to get the receipt for
   * @param resolveBlockNumber The block the transaction was resolved
   * @returns A promise resolving to the transaction's receipt
   */
  abstract getTransactionReceipt(
    txHash: string,
    resolveBlockNumber: (blockTag?: BlockTag | Promise<BlockTag>) => Promise<number | undefined>
  ): Promise<TransactionReceipt>;
Example #2
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async _resolveBlockNumber(
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<number> {
    await this.resolveApi;

    if (!blockTag) {
      return logger.throwError(`Blocktag cannot be undefined`);
    }

    const resolvedBlockNumber = await blockTag;

    if (resolvedBlockNumber === 'pending') {
      throw new Error('Unsupport Block Pending');
    }

    if (resolvedBlockNumber === 'latest') {
      const header = await this.api.rpc.chain.getHeader();
      return header.number.toNumber();
    }

    if (resolvedBlockNumber === 'earliest') {
      return 0;
    }

    if (isNumber(resolvedBlockNumber)) {
      return resolvedBlockNumber;
    } else {
      throw new Error('Expect blockHash to be a number or tag');
    }
  }
Example #3
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async _resolveBlockHash(
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    await this.resolveApi;

    if (!blockTag) return undefined;

    const resolvedBlockHash = await blockTag;

    if (resolvedBlockHash === 'pending') {
      throw new Error('Unsupport Block Pending');
    }

    if (resolvedBlockHash === 'latest') {
      const hash = await this.api.query.system.blockHash();
      return hash.toString();
    }

    if (resolvedBlockHash === 'earliest') {
      const hash = this.api.query.system.blockHash(0);
      return hash.toString();
    }

    if (isHex(resolvedBlockHash)) {
      return resolvedBlockHash;
    }

    const hash = await this.api.query.system.blockHash(resolvedBlockHash);

    return hash.toString();
  }
Example #4
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Submit a transaction to be executed on chain.
   * @param transaction The transaction to call
   * @param blockTag
   * @returns The call result as a hash
   */
  async call(
    transaction: Deferrable<TransactionRequest>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    const resolved = await this._resolveTransaction(transaction);
    if (blockTag) {
      const blockHash = await this._resolveBlockHash(blockTag);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const result = await (this.api.rpc as any).evm.call(resolved, blockHash);
      return result.toHex();
    } else {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const result = await (this.api.rpc as any).evm.call({
        to: resolved.to,
        from: resolved.from,
        data: resolved.data,
        storageLimit: '0'
      });
      return result.toHex();
    }
  }
Example #5
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the storage from a block.
   * @param addressOrName The address to retrieve the storage from
   * @param position
   * @param blockTag The block to retrieve the storage from, defaults to head
   * @returns The storage data as a hash
   */
  async getStorageAt(
    addressOrName: string | Promise<string>,
    position: BigNumberish | Promise<BigNumberish>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    await this.resolveApi;

    const address = await this._resolveEvmAddress(addressOrName);
    const blockHash = await this._resolveBlockHash(blockTag);

    const code = blockHash
      ? await this.api.query.evm.accountStorages.at(blockHash, address)
      : await this.api.query.evm.accountStorages(address);

    return code.toHex();
  }
Example #6
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async queryContractInfo(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<Option<EvmContractInfo>> {
    const accountInfo = await this.queryAccountInfo(addressOrName, blockTag);

    if (accountInfo.isNone) {
      return this.api.createType<Option<EvmContractInfo>>(
        'Option<EvmContractInfo>',
        null
      );
    }

    return accountInfo.unwrap().contractInfo;
  }
Example #7
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
async queryAccountInfo(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<Option<EvmAccountInfo>> {
    // pending tag
    const resolvedBlockTag = await blockTag;
    if (resolvedBlockTag === 'pending') {
      const address = await this._resolveEvmAddress(addressOrName);
      return this.api.query.evm.accounts<Option<EvmAccountInfo>>(address);
    }

    const { address, blockHash } = await resolveProperties({
      address: this._resolveEvmAddress(addressOrName),
      blockHash: this._getBlockTag(blockTag)
    });

    const apiAt = await this.api.at(blockHash);

    const accountInfo = await apiAt.query.evm.accounts<Option<EvmAccountInfo>>(
      address
    );

    return accountInfo;
  }
Example #8
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the code hash at a given address
   * @param addressOrName The address of the code
   * @param blockTag The block to look up the address, defaults to latest
   * @returns A promise resolving in the code hash
   */
  async getCode(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> {
    await this.resolveApi;

    const { address, blockHash } = await resolveProperties({
      address: this._resolveEvmAddress(addressOrName),
      blockHash: this._getBlockTag(blockTag)
    });

    const contractInfo = await this.queryContractInfo(address, blockHash);

    if (contractInfo.isNone) {
      return '0x';
    }

    const codeHash = contractInfo.unwrap().codeHash;
    const api = await (blockHash ? this.api.at(blockHash) : this.api);
    const code = await api.query.evm.codes(codeHash);

    return code.toHex();
  }
Example #9
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the transaction count of an account at a specified block.
   * @param addressOrName The address or name of the account
   * @param blockTag The block to get the transaction count of, defaults to the head block
   * @returns A promise resolving to the account's transaction count
   */
  async getTransactionCount(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<number> {
    await this.resolveApi;

    const resolvedBlockTag = await blockTag;

    const address = await this._resolveEvmAddress(addressOrName);

    let account: Option<EvmAccountInfo>;

    if (resolvedBlockTag === 'pending') {
      account = await this.api.query.evm.accounts<Option<EvmAccountInfo>>(
        address
      );
    } else {
      const blockHash = await this._resolveBlockHash(blockTag);

      account = blockHash
        ? await this.api.query.evm.accounts.at<Option<EvmAccountInfo>>(
            blockHash,
            address
          )
        : await this.api.query.evm.accounts<Option<EvmAccountInfo>>(address);
    }

    if (!account.isNone) {
      return account.unwrap().nonce.toNumber();
    } else {
      return 0;
    }
  }
Example #10
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get an account's balance by address or name.
   * @param addressOrName The address or name of the account
   * @param blockTag The block to get the balance of, defaults to the head
   * @returns A promise resolving to the account's balance
   */
  async getBalance(
    addressOrName: string | Promise<string>,
    blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<BigNumber> {
    await this.resolveApi;

    let address = await this._resolveAddress(addressOrName);

    if (!address) {
      address = await this._toAddress(addressOrName);
    }

    const blockHash = await this._resolveBlockHash(blockTag);

    const accountInfo = blockHash
      ? await this.api.query.system.account.at(blockHash, address)
      : await this.api.query.system.account(address);

    return BigNumber.from(accountInfo.data.free.toBn().toString());
  }
Example #11
Source File: DataProvider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   * Get the transaction receipt for a transaction.
   * @param txHash The transaction hash to get the receipt for
   * @param resolveBlockNumber The block the transaction was resolved
   * @returns A promise resolving to the transaction's receipt
   */
  abstract getTransactionReceipt(
    txHash: string,
    resolveBlockNumber: (
      blockTag?: BlockTag | Promise<BlockTag>
    ) => Promise<number | undefined>
  ): Promise<TransactionReceipt>;
Example #12
Source File: DataProvider.ts    From evm-provider.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @param filter The filter to apply to the logs
   * @param resolveBlockNumber The block to retrieve the logs from, defaults
   * to the head
   * @returns A promise that resolves to an array of filtered logs
   */
  abstract getLogs(
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    filter: any,
    resolveBlockNumber: (
      blockTag?: BlockTag | Promise<BlockTag>
    ) => Promise<number | undefined>
  ): Promise<Array<Log>>;
Example #13
Source File: logs.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
_getBlockNumberFilter = (fromBlock: BlockTag | undefined, toBlock: BlockTag | undefined): string => {
  const fromBlockFilter = isDefined(fromBlock) ? `greaterThanOrEqualTo: "${fromBlock}"` : '';
  const toBlockFilter = isDefined(toBlock) ? `lessThanOrEqualTo: "${toBlock}"` : '';

  return !!fromBlockFilter || !!toBlockFilter
    ? `blockNumber: {
    ${fromBlockFilter}
    ${toBlockFilter}
  }`
    : '';
}
Example #14
Source File: DataProvider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   *
   * @param filter The filter to apply to the logs
   * @param resolveBlockNumber The block to retrieve the logs from, defaults
   * to the head
   * @returns A promise that resolves to an array of filtered logs
   */
  abstract getLogs(
    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    filter: any,
    resolveBlockNumber: (blockTag?: BlockTag | Promise<BlockTag>) => Promise<number | undefined>
  ): Promise<Array<Log>>;
Example #15
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 5 votes vote down vote up
async _getBlockTag(blockTag?: BlockTag | Promise<BlockTag>): Promise<string> {
    blockTag = await blockTag;

    if (blockTag === undefined) {
      blockTag = 'latest';
    }

    switch (blockTag) {
      case 'pending': {
        return logger.throwError(
          'pending tag not implemented',
          Logger.errors.UNSUPPORTED_OPERATION
        );
      }
      case 'latest': {
        const hash = await this.api.rpc.chain.getBlockHash();
        return hash.toHex();
      }
      case 'earliest': {
        const hash = this.api.genesisHash;
        return hash.toHex();
      }
      default: {
        if (!isHexString(blockTag)) {
          return logger.throwArgumentError(
            'blocktag should be a hex string',
            'blockTag',
            blockTag
          );
        }

        // block hash
        if (typeof blockTag === 'string' && isHexString(blockTag, 32)) {
          return blockTag;
        }

        const blockNumber = BigNumber.from(blockTag).toNumber();

        const hash = await this.api.rpc.chain.getBlockHash(blockNumber);

        return hash.toHex();
      }
    }
  }
Example #16
Source File: logs.ts    From useDApp with MIT License 5 votes vote down vote up
/**
 * @internal Intended for internal use - use it on your own risk
 */
export function encodeFilterData(
  filter: TypedFilter | Falsy,
  fromBlock?: BlockTag,
  toBlock?: BlockTag,
  blockHash?: string
): Filter | FilterByBlockHash | Falsy | Error {
  if (!filter) {
    return undefined
  }
  const { contract, event, args } = filter
  if (!contract.address || !event) {
    warnOnInvalidFilter(filter)
    return undefined
  }
  try {
    const encodedTopics = contract.interface.encodeFilterTopics((event as unknown) as utils.EventFragment, args)

    if (blockHash) {
      return {
        address: contract.address,
        topics: encodedTopics,
        blockHash: blockHash,
      } as FilterByBlockHash
    } else {
      return {
        address: contract.address,
        topics: encodedTopics,
        fromBlock: fromBlock ?? 0,
        toBlock: toBlock ?? 'latest',
      } as Filter
    }
  } catch (e) {
    if (e instanceof Error) {
      return e as Error
    } else {
      warnOnInvalidFilter(filter)
      return undefined
    }
  }
}
Example #17
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 5 votes vote down vote up
/**
   * Unimplemented, will always fail.
   */
  async getBlock(
    blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>
  ): Promise<Block> {
    return this._fail('getBlock');
  }
Example #18
Source File: Provider.ts    From evm-provider.js with Apache License 2.0 5 votes vote down vote up
/**
   * Unimplemented, will always fail.
   */
  async getBlockWithTransactions(
    blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>
  ): Promise<BlockWithTransactions> {
    return this._fail('getBlockWithTransactions');
  }