@ethersproject/bytes#hexValue TypeScript Examples

The following examples show how to use @ethersproject/bytes#hexValue. 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: decimals.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('decimals', () => {
  it('convertNativeToken', async () => {
    const value = BigNumber.from('300000000');
    const covertedToken = convertNativeToken(value, 12);
    expect(covertedToken.toString()).to.equal('300000000000000');
  });

  it('hexValue', async () => {
    expect(hexValue(1)).to.equal('0x1');
    expect(hexValue(BigInt(1))).to.equal('0x1');
    expect(hexValue(BigNumber.from(1))).to.equal('0x1');
  });
});
Example #2
Source File: utils.test.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
describe('utils', () => {
  it('connect chain', async () => {
    const a = hexValue(1616274408000);
    const b = hexValue(0);

    expect(a).to.equal('0x17851764240');
    expect(b).to.equal('0x0');
  });

  it('getLogs hexlify', () => {
    const data = [
      {
        blockNumber: 422586,
        blockHash: '0xa1a07ccf1bb31e8da1e1d62cb5aecd3012f8596826ce750f976d7f1fdfb542a5',
        transactionIndex: 0,
        removed: false,
        address: '0xe6f4a83ee9f946b86a2ef008dcd872f4a942db24',
        data: '0x426ab38338be5d42c2cafd1075db80e71965e43f87c11536d8cf0a0dae40d54300000000000000000000000029b563951ed0eb9ae5c49692266e1fbc81445cfe00000000000000000000000029b563951ed0eb9ae5c49692266e1fbc81445cfe00000000000000000000000064ff10dced55d2efeb47f132dd09d37616bfbd18000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000002532c0a3b36bf2a0bbe9a9e96ceeb0ef55ed415dfaafae68823b57bcbffab4e0cca',
        topics: ['0x79fa08de5149d912dce8e5e8da7a7c17ccdf23dd5d3bfe196802e6eb86347c7c'],
        transactionHash: '0x20220cf9d4bf9a666fc7507b47ae85339a81a899c958a83af644453243c86603',
        logIndex: 1
      }
    ];

    const result = hexlifyRpcResult(data);

    expect(result).deep.eq([
      {
        blockNumber: '0x672ba',
        blockHash: '0xa1a07ccf1bb31e8da1e1d62cb5aecd3012f8596826ce750f976d7f1fdfb542a5',
        transactionIndex: '0x0',
        removed: false,
        address: '0xe6f4a83ee9f946b86a2ef008dcd872f4a942db24',
        data: '0x426ab38338be5d42c2cafd1075db80e71965e43f87c11536d8cf0a0dae40d54300000000000000000000000029b563951ed0eb9ae5c49692266e1fbc81445cfe00000000000000000000000029b563951ed0eb9ae5c49692266e1fbc81445cfe00000000000000000000000064ff10dced55d2efeb47f132dd09d37616bfbd18000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000002532c0a3b36bf2a0bbe9a9e96ceeb0ef55ed415dfaafae68823b57bcbffab4e0cca',
        topics: ['0x79fa08de5149d912dce8e5e8da7a7c17ccdf23dd5d3bfe196802e6eb86347c7c'],
        transactionHash: '0x20220cf9d4bf9a666fc7507b47ae85339a81a899c958a83af644453243c86603',
        logIndex: '0x1'
      }
    ]);
  });
});
Example #3
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
getStorageAt = async (
    addressOrName: string | Promise<string>,
    position: BigNumberish | Promise<BigNumberish>,
    _blockTag?: BlockTag | Promise<BlockTag>
  ): Promise<string> => {
    await this.getNetwork();
    const blockTag = await this._ensureSafeModeBlockTagFinalization(_blockTag);

    // @TODO resolvedPosition
    const { address, blockHash, resolvedPosition } = await resolveProperties({
      address: this._getAddress(addressOrName),
      blockHash: this._getBlockHash(blockTag),
      resolvedPosition: Promise.resolve(position).then((p) => hexValue(p))
    });

    const code = await this.queryStorage('evm.accountStorages', [address, position], blockHash);

    return code.toHex();
  };
Example #4
Source File: hexlifyRpcResult.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
hexlifyRpcResult = (data: unknown): any => {
  if (data === null || data === undefined) return data;
  if (typeof data === 'boolean') return data;

  if (BigNumber.isBigNumber(data)) {
    return hexValue(data);
  }

  if (Array.isArray(data)) {
    return data.map((item) => {
      return hexlifyRpcResult(item);
    });
  }

  if (data && typeof data === 'object') {
    const keys = Object.keys(data);
    const result: any = {};

    for (const key of keys) {
      result[key] = hexlifyRpcResult((data as any)[key]);
    }

    return result;
  }

  if (typeof data === 'number') {
    return hexValue(data as any);
  }

  if (isHexString(data)) {
    return (data as string).toLowerCase();
  }

  return data;
}
Example #5
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the current "latest" block number.
   * @returns BLOCK NUMBER - a hex code of an integer representing the current block number the client is on.
   */
  async eth_blockNumber(params: any[]): Promise<any> {
    validate([], params);
    const number = await this.#provider.getBlockNumber();
    return hexValue(number);
  }
Example #6
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the currently configured chain id, a value used in replay-protected transaction signing as introduced by EIP-155.
   * @returns QUANTITY - big integer of the current chain id.
   */
  async eth_chainId(params: any[]): Promise<string> {
    validate([], params);
    const chainId = await this.#provider.chainId();
    return hexValue(chainId);
  }
Example #7
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the number of transactions sent from an address.
   * @param ADDRESS [required] - a string representing the address (20 bytes) to check for transaction count for
   * @param BLOCKTAG [required] - default block parameter
   * @returns TRANSACTION COUNT - a hex code of the integer representing the number of transactions sent from this address.
   */
  async eth_getTransactionCount(params: any[]): Promise<string> {
    validate([{ type: 'address' }, { type: 'block' }], params);
    const count = await this.#provider.getTransactionCount(params[0], params[1]);
    return hexValue(count);
  }
Example #8
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the current gas price in wei.
   * @returns GAS PRICE - a hex code of an integer representing the current gas price in wei.
   */
  async eth_gasPrice(params: any[]): Promise<string> {
    validate([], params);
    const gasPrice = await this.#provider.getGasPrice();
    return hexValue(gasPrice);
  }
Example #9
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the number of transactions in the block with the given block hash.
   * @param BLOCKHASH [required] - a string representing the hash (32 bytes) of a block
   * @returns BLOCK TRANSACTION COUNT - a hex code of the integer representing the number of transactions in the provided block
   */
  async eth_getBlockTransactionCountByHash(params: any[]): Promise<string> {
    validate([{ type: 'blockHash' }], params);
    const result = await this.#provider.getBlock(params[0]);
    return hexValue(result.transactions.length);
  }
Example #10
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Returns the number of transactions in the block with the given block number.
   * @param BLOCKTAG [required] - default block parameter
   * @returns BLOCK TRANSACTION COUNT - a hex code of the integer representing the number of transactions in the provided block
   */
  async eth_getBlockTransactionCountByNumber(params: any[]): Promise<string> {
    validate([{ type: 'block' }], params);
    const result = await this.#provider.getBlock(params[0]);
    return hexValue(result.transactions.length);
  }
Example #11
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
/**
   * Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. Note that the estimate may be significantly more than the amount of gas actually used by the transaction, for a variety of reasons including EVM mechanics and node performance.
   * @param TRANSACTION CALL OBJECT [required]
   * @returns GAS USED - the amount of gas used.
   */
  async eth_estimateGas(params: any[]): Promise<string> {
    validate([{ type: 'transaction' }], params);
    const val = await this.#provider.estimateGas(params[0]);
    return hexValue(val);
  }
Example #12
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
async eth_getEthGas(params: any[]): Promise<{
    gasPrice: string;
    gasLimit: string;
  }> {
    validate([{ type: 'substrateGasParams?' }], params);

    const res = await this.#provider._getEthGas(params[0]);

    return {
      gasPrice: hexValue(res.gasPrice),
      gasLimit: hexValue(res.gasLimit)
    };
  }
Example #13
Source File: eip1193-bridge.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
async eth_getEthResources(params: any[]): Promise<{
    gasPrice: string;
    gasLimit: string;
  }> {
    validate([{ type: 'transaction' }], params);

    const res = await this.#provider.getEthResources(params[0]);

    return {
      gasPrice: hexValue(res.gasPrice),
      gasLimit: hexValue(res.gasLimit)
    };
  }
Example #14
Source File: signatures.ts    From balancer-v2-monorepo with GNU General Public License v3.0 5 votes vote down vote up
static encodeCalldataAuthorization = (calldata: string, deadline: BigNumberish, signature: string): string => {
    const encodedDeadline = hexZeroPad(hexValue(deadline), 32).slice(2);
    const { v, r, s } = splitSignature(signature);
    const encodedV = hexZeroPad(hexValue(v), 32).slice(2);
    const encodedR = r.slice(2);
    const encodedS = s.slice(2);
    return `${calldata}${encodedDeadline}${encodedV}${encodedR}${encodedS}`;
  };
Example #15
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 4 votes vote down vote up
_parseExtrinsic = async (
    blockHash: string,
    extrinsic: GenericExtrinsic,
    extrinsicEvents: EventRecord[]
  ): Promise<any> => {
    // logger.info(extrinsic.method.toHuman());
    // logger.info(extrinsic.method);

    const evmEvent = findEvmEvent(extrinsicEvents);
    if (!evmEvent) {
      return logger.throwError(
        'findEvmEvent failed. extrinsic: ' + extrinsic.method.toJSON(),
        Logger.errors.UNSUPPORTED_OPERATION
      );
    }

    let gas;
    let value;
    let input;
    const from = evmEvent.event.data[0].toString();
    const to = ['Created', 'CreatedFailed'].includes(evmEvent.event.method) ? null : evmEvent.event.data[1].toString();

    // @TODO remove
    // only work on mandala and karura-testnet
    // https://github.com/AcalaNetwork/Acala/pull/1985
    let gasPrice = BIGNUMBER_ONE;

    if (
      evmEvent.event.data.length > 5 ||
      (evmEvent.event.data.length === 5 &&
        (evmEvent.event.method === 'Created' || evmEvent.event.method === 'Executed'))
    ) {
      const used_gas = BigNumber.from(evmEvent.event.data[evmEvent.event.data.length - 2].toString());
      const used_storage = BigNumber.from(evmEvent.event.data[evmEvent.event.data.length - 1].toString());

      const block = await this.api.rpc.chain.getBlock(blockHash);
      // use parentHash to get tx fee
      const payment = await this.api.rpc.payment.queryInfo(extrinsic.toHex(), block.block.header.parentHash);
      // ACA/KAR decimal is 12. Mul 10^6 to make it 18.
      let tx_fee = ethers.utils.parseUnits(payment.partialFee.toString(), 'mwei');

      // get storage fee
      // if used_storage > 0, tx_fee include the storage fee.
      if (used_storage.gt(0)) {
        const { storageDepositPerByte } = this._getGasConsts();
        tx_fee = tx_fee.add(used_storage.mul(storageDepositPerByte));
      }

      gasPrice = tx_fee.div(used_gas);
    }

    switch (extrinsic.method.section.toUpperCase()) {
      case 'EVM': {
        const evmExtrinsic: any = extrinsic.method.toJSON();
        value = evmExtrinsic?.args?.value;
        gas = evmExtrinsic?.args?.gas_limit;
        // @TODO remove
        // only work on mandala and karura-testnet
        // https://github.com/AcalaNetwork/Acala/pull/1965
        input = evmExtrinsic?.args?.input || evmExtrinsic?.args?.init;
        break;
      }
      // Not a raw evm transaction, input = 0x
      // case 'CURRENCIES':
      // case 'DEX':
      // case 'HONZONBRIDGE':
      // case 'PROXY':
      // case 'SUDO':
      // case 'TECHNICALCOMMITTEE':
      // case 'STABLEASSET':
      // @TODO support utility
      // case 'UTILITY': {
      //   return logger.throwError('Unspport utility, blockHash: ' + blockHash, Logger.errors.UNSUPPORTED_OPERATION);
      // }
      // default: {
      //   return logger.throwError(
      //     'Unspport ' + extrinsic.method.section.toUpperCase() + ' blockHash: ' + blockHash,
      //     Logger.errors.UNSUPPORTED_OPERATION
      //   );
      // }

      // Not a raw evm transaction, input = 0x
      default: {
        value = 0;
        gas = 2_100_000;
        input = '0x';
      }
    }

    // @TODO eip2930, eip1559

    // @TODO Missing data
    return {
      gasPrice,
      gas,
      input,
      v: DUMMY_V,
      r: DUMMY_R,
      s: DUMMY_S,
      hash: extrinsic.hash.toHex(),
      nonce: extrinsic.nonce.toNumber(),
      from: from,
      to: to,
      value: hexValue(value)
    };
  };