@ethersproject/bytes#hexZeroPad TypeScript Examples

The following examples show how to use @ethersproject/bytes#hexZeroPad. 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: parseTransaction.ts    From bodhi.js with Apache License 2.0 6 votes vote down vote up
function _parseEip712Signature(
  tx: AcalaEvmTX,
  fields: Array<string>,
  serialize: (tx: UnsignedAcalaEvmTX) => string
): void {
  try {
    const recid = handleNumber(fields[0]).toNumber();
    if (recid !== 0 && recid !== 1) {
      throw new Error('bad recid');
    }
    tx.v = recid;
  } catch (error) {
    logger.throwArgumentError('invalid v for transaction type: 1', 'v', fields[0]);
  }

  tx.r = hexZeroPad(fields[1], 32);
  tx.s = hexZeroPad(fields[2], 32);

  tx.from = verifyTransaction(
    {
      chainId: tx.chainId,
      salt: tx.salt,
      nonce: tx.nonce,
      gasLimit: tx.gasLimit,
      storageLimit: tx.storageLimit,
      to: tx.to,
      value: tx.value,
      data: tx.data,
      validUntil: tx.validUntil,
      tip: tx.tip,
      accessList: tx.accessList
    },
    joinSignature({ r: tx.r, s: tx.s, v: tx.v })
  );
}
Example #2
Source File: hdwallet.ts    From fuels-ts with Apache License 2.0 6 votes vote down vote up
/**
   * Get the extendKey as defined on BIP-32 from the provided seed
   *
   * @param isPublic - enable to export public extendedKey, it not required when HDWallet didn't have the privateKey.
   * @param testnet - Inform if should use testnet or mainnet prefix, default value is true (`mainnet`).
   * @returns BIP-32 extended private key
   */
  toExtendedKey(isPublic: boolean = false, testnet: boolean = false): string {
    if (this.depth >= 256) {
      throw new Error('Depth too large!');
    }
    const prefix = getExtendedKeyPrefix(this.privateKey == null || isPublic, testnet);
    const depth = hexlify(this.depth);
    const parentFingerprint = this.parentFingerprint;
    const index = hexZeroPad(hexlify(this.index), 4);
    // last 32 bites from the key
    const chainCode = this.chainCode;
    // first 32 bites from the key
    const key =
      this.privateKey != null && !isPublic ? concat(['0x00', this.privateKey]) : this.publicKey;
    const extendedKey = concat([prefix, depth, parentFingerprint, index, chainCode, key]);

    return base58check(extendedKey);
  }
Example #3
Source File: hdwallet.ts    From fuels-ts with Apache License 2.0 5 votes vote down vote up
/**
   * Derive the current HDWallet instance navigating only on the index.
   * `Ex.: m/44'/0 -> Ex.: m/44'/1 -> m/44'/2`. [Learn more](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki)
   *
   * @param index - Index of the child HDWallet.
   * @returns A new instance of HDWallet on the derived index
   */
  deriveIndex(index: number) {
    const privateKey = this.privateKey && arrayify(this.privateKey);
    const publicKey = arrayify(this.publicKey);
    const chainCode = arrayify(this.chainCode);
    const data = new Uint8Array(37);

    if (index & HARDENED_INDEX) {
      if (!privateKey) {
        throw new Error('Derive hardened requires privateKey');
      }

      // 33 bytes: 0x00 || private key
      data.set(privateKey, 1);
    } else {
      data.set(arrayify(this.publicKey));
    }

    // child number: ser32(i)
    data.set(to4Bytes(index), 33);

    const bytes = arrayify(computeHmac(SupportedAlgorithm.sha512, chainCode, data));
    const IL = bytes.slice(0, 32);
    const IR = bytes.slice(32);

    if (privateKey) {
      const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');
      // Child key ki is parse256(IL) + kpar (mod n).
      const ki = arrayify(hexZeroPad(hexlify((toBigInt(IL) + toBigInt(privateKey)) % N), 32));

      return new HDWallet({
        privateKey: ki,
        chainCode: IR,
        index,
        depth: this.depth + 1,
        parentFingerprint: this.fingerprint,
      });
    }

    const signer = new Signer(hexlify(IL));
    const Ki = signer.addPoint(publicKey);

    return new HDWallet({
      publicKey: Ki,
      chainCode: IR,
      index,
      depth: this.depth + 1,
      parentFingerprint: this.fingerprint,
    });
  }
Example #4
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 #5
Source File: index.ts    From snapshot-strategies with MIT License 4 votes vote down vote up
// options
// {
//   "crucible_factory": "0x54e0395CFB4f39beF66DBCd5bD93Cca4E9273D56",
//   "erc20_address": "0xCD6bcca48069f8588780dFA274960F15685aEe0e",
//   "erc20_decimals": 18
// }

export async function strategy(
  space,
  network,
  provider,
  addresses,
  options,
  snapshot
): Promise<Record<string, number>> {
  const blockTag = typeof snapshot === 'number' ? snapshot : 'latest';

  // get the number of crucibles owned by the wallet
  // wallet_address => crucible_count

  const callWalletToCrucibleCount = new Multicaller(network, provider, abi, {
    blockTag
  });
  for (const walletAddress of addresses) {
    callWalletToCrucibleCount.call(
      walletAddress,
      options.crucible_factory,
      'balanceOf',
      [walletAddress]
    );
  }
  const walletToCrucibleCount: Record<
    string,
    BigNumber
  > = await callWalletToCrucibleCount.execute();

  // get the address of each crucible
  // wallet_address : crucible_index => crucible_address

  const callWalletToCrucibleAddresses = new Multicaller(
    network,
    provider,
    abi,
    {
      blockTag
    }
  );
  for (const [walletAddress, crucibleCount] of Object.entries(
    walletToCrucibleCount
  )) {
    for (let index = 0; index < crucibleCount.toNumber(); index++) {
      callWalletToCrucibleAddresses.call(
        walletAddress.toString() + '-' + index.toString(),
        options.crucible_factory,
        'tokenOfOwnerByIndex',
        [walletAddress, index]
      );
    }
  }
  const walletIDToCrucibleAddresses: Record<
    string,
    BigNumber
  > = await callWalletToCrucibleAddresses.execute();

  // get the balance of each crucible
  // crucible_address => lp_balance

  const callCrucibleToLpBalance = new Multicaller(network, provider, abi, {
    blockTag
  });
  for (const [walletID, crucibleAddress] of Object.entries(
    walletIDToCrucibleAddresses
  )) {
    callCrucibleToLpBalance.call(walletID, options.erc20_address, 'balanceOf', [
      hexZeroPad(crucibleAddress.toHexString(), 20)
    ]);
  }
  const walletIDToLpBalance: Record<
    string,
    BigNumber
  > = await callCrucibleToLpBalance.execute();

  // sum the amount of LP tokens held across all crucibles
  // wallet_address => lp_balance

  const walletToLpBalance = {} as Record<string, BigNumber>;
  for (const [walletID, lpBalance] of Object.entries(walletIDToLpBalance)) {
    const address = walletID.split('-')[0];
    walletToLpBalance[address] = walletToLpBalance[address]
      ? walletToLpBalance[address].add(lpBalance)
      : lpBalance;
  }

  return Object.fromEntries(
    Object.entries(walletToLpBalance).map(([address, balance]) => [
      address,
      parseFloat(formatUnits(balance, options.erc20_decimals))
    ])
  );
}