@ethersproject/bytes#hexlify TypeScript Examples

The following examples show how to use @ethersproject/bytes#hexlify. 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: util.ts    From fuels-ts with Apache License 2.0 7 votes vote down vote up
getContractRoot = (bytecode: Uint8Array): string => {
  const chunkSize = 8;
  const chunks: Uint8Array[] = [];
  for (let offset = 0; offset < bytecode.length; offset += chunkSize) {
    const chunk = new Uint8Array(chunkSize);
    chunk.set(bytecode.slice(offset, offset + chunkSize));
    chunks.push(chunk);
  }
  return calcRoot(chunks.map((c) => hexlify(c)));
}
Example #2
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
_getTransactionRequest = async (transaction: Deferrable<TransactionRequest>): Promise<Partial<Transaction>> => {
    const values: any = await transaction;

    const tx: any = {};

    ['from', 'to'].forEach((key) => {
      if (values[key] === null || values[key] === undefined) {
        return;
      }
      tx[key] = Promise.resolve(values[key]).then((v) => (v ? this._getAddress(v) : null));
    });

    ['gasLimit', 'gasPrice', 'maxFeePerGas', 'maxPriorityFeePerGas', 'value'].forEach((key) => {
      if (values[key] === null || values[key] === undefined) {
        return;
      }
      tx[key] = Promise.resolve(values[key]).then((v) => (v ? BigNumber.from(v) : null));
    });

    ['type'].forEach((key) => {
      if (values[key] === null || values[key] === undefined) {
        return;
      }
      tx[key] = Promise.resolve(values[key]).then((v) => (v !== null || v !== undefined ? v : null));
    });

    if (values.accessList) {
      tx.accessList = accessListify(values.accessList);
    }

    ['data'].forEach((key) => {
      if (values[key] === null || values[key] === undefined) {
        return;
      }
      tx[key] = Promise.resolve(values[key]).then((v) => (v ? hexlify(v) : null));
    });

    return await resolveProperties(tx);
  };
Example #3
Source File: coin-quantity.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
coinQuantityfy = (coinQuantityLike: CoinQuantityLike): CoinQuantity => {
  let assetId;
  let amount;
  if (Array.isArray(coinQuantityLike)) {
    amount = coinQuantityLike[0];
    assetId = coinQuantityLike[1] ?? NativeAssetId;
  } else {
    amount = coinQuantityLike.amount;
    assetId = coinQuantityLike.assetId ?? NativeAssetId;
  }

  return {
    assetId: hexlify(assetId),
    amount: BigInt(amount),
  };
}
Example #4
Source File: index.ts    From ccip-read with MIT License 6 votes vote down vote up
async function sendRPC(fetcher: Fetch, urls: string[], to: BytesLike, callData: BytesLike): Promise<BytesLike> {
  const processFunc = (value: any, response: FetchJsonResponse) => {
    return { body: value, status: response.statusCode };
  };

  const args = { sender: hexlify(to), data: hexlify(callData) };
  for (let template of urls) {
    const url = template.replace(/\{([^}]*)\}/g, (_match, p1: keyof typeof args) => args[p1]);
    const data = await fetcher(url, template.includes('{data}') ? undefined : JSON.stringify(args), processFunc);
    if (data.status >= 400 && data.status <= 499) {
      return logger.throwError('bad response', Logger.errors.SERVER_ERROR, {
        status: data.status,
        name: data.body.message,
      });
    }
    if (data.status >= 200 && data.status <= 299) {
      return data.body.data;
    }
    logger.warn('Server returned an error', url, to, callData, data.status, data.body.message);
  }
  return logger.throwError('All gateways returned an error', Logger.errors.SERVER_ERROR, { urls, to, callData });
}
Example #5
Source File: b256.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
decode(data: Uint8Array, offset: number): [string, number] {
    let bytes = data.slice(offset, offset + 32);

    if (toBigInt(bytes) === 0n) {
      bytes = new Uint8Array(32);
    }

    if (bytes.length !== 32) {
      this.throwError('Invalid size for b256', bytes);
    }
    return [hexlify(bytes), offset + 32];
  }
Example #6
Source File: web3.ts    From snapshot.js with MIT License 5 votes vote down vote up
export async function signMessage(web3, msg, address) {
  msg = hexlify(new Buffer(msg, 'utf8'));
  return await web3.send('personal_sign', [msg, address]);
}
Example #7
Source File: base-provider.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
sendTransaction = async (signedTransaction: string | Promise<string>): Promise<TransactionResponse> => {
    await this.getNetwork();
    const hexTx = await Promise.resolve(signedTransaction).then((t) => hexlify(t));
    const tx = parseTransaction(await signedTransaction);

    if ((tx as any).confirmations === null || (tx as any).confirmations === undefined) {
      (tx as any).confirmations = 0;
    }

    try {
      const { extrinsic, transaction } = await this.prepareTransaction(hexTx);
      //@TODO
      // wait for tx in block
      const result = await sendTx(this.api, extrinsic);
      const blockHash = result.status.isInBlock ? result.status.asInBlock : result.status.asFinalized;
      const header = await this._getBlockHeader(blockHash.toHex());
      const blockNumber = header.number.toNumber();
      const hash = extrinsic.hash.toHex();

      return this._wrapTransaction(transaction, hash, blockNumber, blockHash.toHex());
    } catch (err) {
      const error = err as any;
      for (let pattern of ERROR_PATTERN) {
        const match = ((error.toString?.() || '') as string).match(pattern);
        if (match) {
          const errDetails = this.api.registry.findMetaError(new Uint8Array([parseInt(match[1]), parseInt(match[2])]));

          // error.message is readonly, so construct a new error object
          throw new Error(
            JSON.stringify({
              message: `${errDetails.section}.${errDetails.name}: ${errDetails.docs}`,
              transaction: tx,
              transactionHash: tx.hash
            })
          );
        }
      }

      error.transaction = tx;
      error.transactionHash = tx.hash;
      throw error;
    }
  };
Example #8
Source File: index.ts    From ccip-read with MIT License 5 votes vote down vote up
async function handleCall(
  provider: CCIPReadProvider,
  params: { transaction: TransactionRequest; blockTag?: BlockTag },
  maxCalls = 4
): Promise<{ transaction: TransactionRequest; result: BytesLike }> {
  for (let i = 0; i < maxCalls; i++) {
    let result;
    let bytes: Uint8Array;
    try {
      result = await provider.parent.perform('call', params);
      bytes = arrayify(result);
    } catch (e) {
      if (isRevertError(e)) {
        bytes = arrayify(e.error.data.originalError.data);
      } else {
        return logger.throwError('The error message does not contain originalError', Logger.errors.UNKNOWN_ERROR);
      }
    }
    if (bytes.length % 32 !== 4 || hexlify(bytes.slice(0, 4)) !== CCIP_READ_INTERFACE.getSighash('OffchainLookup')) {
      return { transaction: params.transaction, result: bytes };
    }
    const { sender, urls, callData, callbackFunction, extraData } = CCIP_READ_INTERFACE.decodeErrorResult(
      'OffchainLookup',
      bytes
    );
    if (params.transaction.to === undefined || sender.toLowerCase() !== params.transaction.to.toLowerCase()) {
      return logger.throwError('OffchainLookup thrown in nested scope', Logger.errors.UNSUPPORTED_OPERATION, {
        to: params.transaction.to,
        sender,
        urls,
        callData,
        callbackFunction,
        extraData,
      });
    }
    const response = await sendRPC(provider.fetcher, urls, params.transaction.to, callData);
    const data = hexConcat([
      callbackFunction,
      defaultAbiCoder.encode(CCIP_READ_INTERFACE.getFunction('callback').inputs, [response, extraData]),
    ]);
    params = Object.assign({}, params, {
      transaction: Object.assign({}, params.transaction, { data }),
    });
  }
  return logger.throwError('Too many redirects', Logger.errors.TIMEOUT, { to: params.transaction.to });
}
Example #9
Source File: createTransactionPayload.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
createTransactionPayload = (tx: AcalaEvmTXPayload) => {
  if (!tx.salt) {
    return logger.throwError('eip712tx missing salt');
  }

  if (!tx.chainId) {
    return logger.throwError('eip712tx missing chainId');
  }

  return {
    types: {
      EIP712Domain: [
        {
          name: 'name',
          type: 'string'
        },
        {
          name: 'version',
          type: 'string'
        },
        {
          name: 'chainId',
          type: 'uint256'
        },
        {
          name: 'salt',
          type: 'bytes32'
        }
      ],
      AccessList: [
        { name: 'address', type: 'address' },
        { name: 'storageKeys', type: 'uint256[]' }
      ],
      Transaction: [
        { name: 'action', type: 'string' },
        { name: 'to', type: 'address' },
        { name: 'nonce', type: 'uint256' },
        { name: 'tip', type: 'uint256' },
        { name: 'data', type: 'bytes' },
        { name: 'value', type: 'uint256' },
        { name: 'gasLimit', type: 'uint256' },
        { name: 'storageLimit', type: 'uint256' },
        { name: 'accessList', type: 'AccessList[]' },
        { name: 'validUntil', type: 'uint256' }
      ]
    },
    primaryType: 'Transaction' as const,
    domain: {
      name: 'Acala EVM',
      version: '1',
      chainId: tx.chainId,
      salt: hexlify(tx.salt || '0x')
    },
    message: {
      action: tx.action || (tx.to ? 'Call' : 'Create'),
      to: tx.to || '0x0000000000000000000000000000000000000000',
      nonce: BigNumber.from(tx.nonce).toString(),
      tip: BigNumber.from(tx.tip || 0).toString(),
      data: hexlify(tx.data || '0x'),
      value: BigNumber.from(tx.value || 0).toString(),
      gasLimit: BigNumber.from(tx.gasLimit || 0).toString(),
      storageLimit: BigNumber.from(tx.storageLimit || 0).toString(),
      accessList: tx.accessList ? accessListify(tx.accessList) : [],
      validUntil: BigNumber.from(tx.validUntil || MAX_UINT256).toString()
    }
  };
}
Example #10
Source File: transaction.test.ts    From fuels-ts with Apache License 2.0 5 votes vote down vote up
describe('TransactionCoder', () => {
  it('Can encode TransactionScript', () => {
    const transaction: Transaction = {
      type: TransactionType.Script,
      gasPrice: 0n,
      gasLimit: 0n,
      bytePrice: 0n,
      maturity: 0n,
      scriptLength: 0,
      scriptDataLength: 0,
      inputsCount: 0,
      outputsCount: 0,
      witnessesCount: 0,
      receiptsRoot: B256,
      script: '0x',
      scriptData: '0x',
      inputs: [],
      outputs: [],
      witnesses: [],
    };

    const encoded = hexlify(new TransactionCoder().encode(transaction));

    expect(encoded).toEqual(
      '0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d5579c46dfcc7f18207013e65b44e4cb4e2c2298f4ac457ba8f82743f31e930b'
    );

    const [decoded, offset] = new TransactionCoder().decode(arrayify(encoded), 0);

    expect(offset).toEqual((encoded.length - 2) / 2);
    expect(decoded).toEqual(transaction);
  });

  it('Can encode TransactionCreate', () => {
    const transaction: Transaction = {
      type: TransactionType.Create,
      gasPrice: 0n,
      gasLimit: 0n,
      bytePrice: 0n,
      maturity: 0n,
      bytecodeLength: 0,
      bytecodeWitnessIndex: 0,
      staticContractsCount: 0,
      storageSlotsCount: 0,
      inputsCount: 0,
      outputsCount: 0,
      witnessesCount: 0,
      salt: B256,
      staticContracts: [],
      storageSlots: [],
      inputs: [],
      outputs: [],
      witnesses: [],
    };

    const encoded = hexlify(new TransactionCoder().encode(transaction));

    expect(encoded).toEqual(
      '0x000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000d5579c46dfcc7f18207013e65b44e4cb4e2c2298f4ac457ba8f82743f31e930b'
    );

    const [decoded, offset] = new TransactionCoder().decode(arrayify(encoded), 0);

    expect(offset).toEqual((encoded.length - 2) / 2);
    expect(decoded).toEqual(transaction);
  });
});