web3-utils#toWei TypeScript Examples

The following examples show how to use web3-utils#toWei. 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: ethWallet.ts    From webapp with MIT License 6 votes vote down vote up
@action async transfer({
    floatAmount,
    recipient
  }: {
    floatAmount: string;
    recipient: string;
  }) {
    if (!floatAmount) throw new Error("Float Amount required.");
    if (!isAddress(recipient))
      throw new Error("Recipient must be valid ETH address");
    const weiAmount = toWei(floatAmount);
    const value = toHex(weiAmount);
    const params = [
      {
        from: this.currentUser,
        to: recipient,
        value
      }
    ];
    return this.tx(params);
  }
Example #2
Source File: evm-based.utils.ts    From tatum-js with MIT License 6 votes vote down vote up
evmBasedUtils = {
  generateAddressFromXPub: (xpub: string, i: number): string => {
    const w = ethHdKey.fromExtendedKey(xpub)
    const wallet = w.deriveChild(i).getWallet()
    return ADDRESS_PREFIX.EVM + wallet.getAddress().toString('hex').toLowerCase()
  },
  generatePrivateKeyFromMnemonic: async (
    blockchain: EvmBasedBlockchain,
    mnemonic: string,
    i: number,
    options?: { testnet: boolean },
  ): Promise<string> => {
    const derivationPath = getDerivationPath(blockchain, options)
    const hdwallet = ethHdKey.fromMasterSeed(await mnemonicToSeed(mnemonic))
    const derivePath = hdwallet.derivePath(derivationPath).deriveChild(i)
    return derivePath.getWallet().getPrivateKeyString()
  },
  generateAddressFromPrivateKey: (blockchain: EvmBasedBlockchain, privateKey: string): string => {
    const wallet = ethWallet.fromPrivateKey(Buffer.from(privateKey.replace(ADDRESS_PREFIX.EVM, ''), 'hex'))
    return wallet.getAddressString() as string
  },
  generateBlockchainWallet: async (
    blockchain: EvmBasedBlockchain,
    mnemonic?: string,
    options?: { testnet: boolean },
  ): Promise<TronWallet> => {
    const mnem = mnemonic ?? generateMnemonic(256)
    const derivationPath = getDerivationPath(blockchain, options)
    const hdwallet = ethHdKey.fromMasterSeed(await mnemonicToSeed(mnem))
    const derivePath = hdwallet.derivePath(derivationPath)
    return {
      xpub: derivePath.publicExtendedKey().toString(),
      mnemonic: mnem,
    }
  },
  prepareSignedTransactionAbstraction: async (
    client: Web3,
    transaction: TransactionConfig,
    web3: EvmBasedWeb3,
    signatureId?: string,
    fromPrivateKey?: string,
    gasLimit?: string,
    gasPrice?: string,
  ) => {
    const gasPriceDefined = gasPrice ? client.utils.toWei(gasPrice, 'gwei') : await web3.getGasPriceInWei()
    const tx = {
      ...transaction,
      gasPrice: gasPriceDefined,
    }

    tx.gas = gasLimit ?? (await client.eth.estimateGas(tx))

    if (signatureId) {
      return JSON.stringify(tx)
    }

    if (!fromPrivateKey) {
      throw new Error('signatureId or fromPrivateKey has to be defined')
    }

    tx.from = tx.from || client.eth.defaultAccount || 0
    const signedTransaction = await client.eth.accounts.signTransaction(tx, fromPrivateKey)

    if (!signedTransaction.rawTransaction) {
      throw new Error('Unable to get signed tx data')
    }

    return signedTransaction.rawTransaction
  },

  transformAmount: (amount: string, unit = 'ether') => {
    return toWei(amount, unit as Unit)
  },

  decimals: async (contractAddress: string, web3: EvmBasedWeb3, provider?: string) => {
    const client = web3.getClient(provider)

    return new client.eth.Contract(Erc20Token.abi as any, contractAddress).methods.decimals().call()
  },
}
Example #3
Source File: evm-based.auction.ts    From tatum-js with MIT License 6 votes vote down vote up
auctionUpdateFeeRecipientSignedTransaction = (
  body: UpdateAuctionFeeRecipient,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const client = web3.getClient(provider)

  const methodName = 'setAuctionFeeRecipient'
  const methodAbi = MarketplaceSmartContract.abi.find((a) => a.name === methodName)
  // TODO any type
  const contract = new client.eth.Contract([methodAbi as any])
  const params = [body.feeRecipient]

  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: body.amount
      ? `0x${new BigNumber(client.utils.toWei(body.amount, 'ether')).toString(16)}`
      : undefined,
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #4
Source File: evm-based.auction.ts    From tatum-js with MIT License 6 votes vote down vote up
auctionApproveNftTransferSignedTransaction = async (
  body: ApproveNftTransfer,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const client = web3.getClient(provider)

  const methodName = body.isErc721 ? 'approve' : 'setApprovalForAll'
  const abi = body.isErc721 ? Erc721Token.abi : Erc1155.abi
  const methodAbi = abi.find((a) => a.name === methodName)
  // TODO any type
  const contract = new client.eth.Contract([methodAbi as any])

  const params = body.isErc721
    ? [body.spender, `0x${new BigNumber(body.tokenId).toString(16)}`]
    : [body.spender, true]

  const data = contract.methods[methodName](...params).encodeABI()

  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: body.amount
      ? `0x${new BigNumber(client.utils.toWei(body.amount, 'ether')).toString(16)}`
      : undefined,
    data,
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #5
Source File: evm-based.auction.ts    From tatum-js with MIT License 6 votes vote down vote up
auctionCancelSignedTransaction = async (body: CancelAuction, web3: EvmBasedWeb3, provider?: string) => {
  const client = web3.getClient(provider)

  const params = [body.id]
  // TODO any type
  const contract = new client.eth.Contract(MarketplaceSmartContract.abi as any, body.contractAddress.trim())
  const data = contract.methods['cancelAuction']({ arguments: params }).encodeABI()

  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: body.amount
      ? `0x${new BigNumber(client.utils.toWei(body.amount, 'ether')).toString(16)}`
      : undefined,
    data,
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #6
Source File: evm-based.auction.ts    From tatum-js with MIT License 6 votes vote down vote up
auctionSettleSignedTransaction = async (body: SettleAuction, web3: EvmBasedWeb3, provider?: string) => {
  const client = web3.getClient(provider)

  const params = [body.id]
  const methodName = 'settleAuction'
  const methodAbi = MarketplaceSmartContract.abi.find((a) => a.name === methodName)
  // TODO any type
  const contract = new client.eth.Contract([methodAbi as any])

  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: body.amount
      ? `0x${new BigNumber(client.utils.toWei(body.amount, 'ether')).toString(16)}`
      : undefined,
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #7
Source File: prelude.ts    From solidity-utils with MIT License 5 votes vote down vote up
export function ether (n: string) {
    return toBN(toWei(n, 'ether'));
}
Example #8
Source File: web3-pure.ts    From rubic-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
     * @description convert amount from Ether to Wei units
     * @param amount amount to convert
     * @param [decimals=18] token decimals
     */
    static toWei(amount: BigNumber | string | number, decimals = 18): string {
        return new BigNumber(amount || 0).times(new BigNumber(10).pow(decimals)).toFixed(0);
    }
Example #9
Source File: web3-pure.ts    From rubic-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
     * @description converts Eth amount into Wei
     * @param value to convert in Eth
     */
    static ethToWei(value: string | BigNumber): string {
        return toWei(value.toString(), 'ether');
    }
Example #10
Source File: evm-based.auction.ts    From tatum-js with MIT License 5 votes vote down vote up
auctionApproveErc20TransferSignedTransaction = async (
  body: ApproveNftTransfer,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const client = web3.getClient(provider)
  const amount = new BigNumber(body.amount)
    .multipliedBy(
      new BigNumber(10).pow(
        // TODO any type
        await new client.eth.Contract(Erc20Token.abi as any, body.contractAddress.trim()).methods
          .decimals()
          .call(),
      ),
    )
    .toString(16)
  const params = [body.spender.trim(), `0x${amount}`]
  body.amount = '0'

  const methodName = 'approve'
  const methodAbi = MarketplaceSmartContract.abi.find((a) => a.name === methodName) as AbiItem
  const contract = new client.eth.Contract([methodAbi])
  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: amount ? `0x${new BigNumber(toWei(amount, 'ether')).toString(16)}` : undefined,
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}
Example #11
Source File: evm-based.auction.ts    From tatum-js with MIT License 5 votes vote down vote up
auctionBidSignedTransaction = async (
  body: AuctionBid,
  blockchain: EvmBasedBlockchain,
  broadcastFunction: BroadcastFunction,
  web3: EvmBasedWeb3,
  provider?: string,
) => {
  const client = web3.getClient(provider)

  const a = await new client.eth.Contract(MarketplaceSmartContract.abi as any, body.contractAddress).methods
    .getAuction(body.id)
    .call()
  let decimals = 18
  let methodName = 'bid'
  let amount: string | undefined = undefined
  if (a[6] !== '0x0000000000000000000000000000000000000000') {
    decimals = await erc20({ blockchain, web3, broadcastFunction }).decimals(a[6], provider)
    if (body.bidder) {
      methodName = 'bidForExternalBidder'
    }
  } else if (body.bidder) {
    throw new Error('Bidder could be present only for ERC20 based auctions.')
  } else {
    amount = body.bidValue
  }

  if (!body.bidValue) {
    throw new Error('No budValue set')
  }

  const params = [
    body.id,
    `0x${new BigNumber(body.bidValue).multipliedBy(new BigNumber(10).pow(decimals)).toString(16)}`,
  ]
  if (body.bidder) {
    params.push(body.bidder.trim())
  }

  // TODO any type
  const contract = new client.eth.Contract([MarketplaceSmartContract.abi as any])
  const tx: TransactionConfig = {
    from: 0,
    to: body.contractAddress.trim(),
    value: amount ? `0x${new BigNumber(client.utils.toWei(amount, 'ether')).toString(16)}` : undefined,
    data: contract.methods[methodName as string](...params).encodeABI(),
    nonce: body.nonce,
  }

  return evmBasedUtils.prepareSignedTransactionAbstraction(
    client,
    tx,
    web3,
    body.signatureId,
    body.fromPrivateKey,
    body.fee?.gasLimit,
    body.fee?.gasPrice,
  )
}