@0x/web3-wrapper

  • Version 7.6.5
  • Published
  • 152 kB
  • 9 dependencies
  • Apache-2.0 license

Install

npm i @0x/web3-wrapper
yarn add @0x/web3-wrapper
pnpm add @0x/web3-wrapper

Overview

Wraps around web3 and gives a nicer interface

Index

Variables

Classes

Interfaces

Enums

Type Aliases

Variables

variable marshaller

const marshaller: {
unmarshalIntoBlockWithoutTransactionData(
blockWithHexValues: BlockWithoutTransactionDataRPC
): BlockWithoutTransactionData;
unmarshalIntoBlockWithTransactionData(
blockWithHexValues: BlockWithTransactionDataRPC
): BlockWithTransactionData;
unmarshalTransaction(txRpc: TransactionRPC): Transaction;
unmarshalTransactionReceipt(
txReceiptRpc: TransactionReceiptRPC
): TransactionReceipt;
unmarshalTxData(txDataRpc: TxDataRPC): TxData;
marshalTxData(txData: TxData): Partial<TxDataRPC>;
marshalCallData(callData: CallData): Partial<CallDataRPC>;
marshalCallOverrides(overrides: GethCallOverrides): GethCallOverridesRPC;
marshalAddress(address: string): string;
marshalBlockParam(
blockParam: BlockParam | string | number | undefined
): string | undefined;
unmarshalLog(rawLog: RawLogEntry): LogEntry;
_marshalCallTxDataBase(
callTxDataBase: CallTxDataBase
): Partial<CallTxDataBaseRPC>;
};
  • Utils to convert ethereum structures from user-space format to RPC format. (marshall/unmarshall)

Classes

class Web3Wrapper

class Web3Wrapper {}
  • An alternative to the Web3.js library that provides a consistent, clean, promise-based interface.

constructor

constructor(supportedProvider: SupportedProvider, callAndTxnDefaults?: CallData);
  • Instantiates a new Web3Wrapper.

    Parameter provider

    The Web3 provider instance you would like the Web3Wrapper to use for interacting with the backing Ethereum node.

    Parameter callAndTxnDefaults

    Override Call and Txn Data defaults sent with RPC requests to the backing Ethereum node. An instance of the Web3Wrapper class.

property abiDecoder

abiDecoder: AbiDecoder;

    property isZeroExWeb3Wrapper

    isZeroExWeb3Wrapper: boolean;
    • Flag to check if this instance is of type Web3Wrapper

    method awaitTransactionMinedAsync

    awaitTransactionMinedAsync: (
    txHash: string,
    pollingIntervalMs?: number,
    timeoutMs?: number
    ) => Promise<TransactionReceiptWithDecodedLogs>;
    • Waits for a transaction to be mined and returns the transaction receipt. Note that just because a transaction was mined does not mean it was successful. You need to check the status code of the transaction receipt to find out if it was successful, or use the helper method awaitTransactionSuccessAsync.

      Parameter txHash

      Transaction hash

      Parameter pollingIntervalMs

      How often (in ms) should we check if the transaction is mined.

      Parameter timeoutMs

      How long (in ms) to poll for transaction mined until aborting. Transaction receipt with decoded log args.

    method awaitTransactionSuccessAsync

    awaitTransactionSuccessAsync: (
    txHash: string,
    pollingIntervalMs?: number,
    timeoutMs?: number
    ) => Promise<TransactionReceiptWithDecodedLogs>;
    • Waits for a transaction to be mined and returns the transaction receipt. Unlike awaitTransactionMinedAsync, it will throw if the receipt has a status that is not equal to 1. A status of 0 or null indicates that the transaction was mined, but failed. See: https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt

      Parameter txHash

      Transaction hash

      Parameter pollingIntervalMs

      How often (in ms) should we check if the transaction is mined.

      Parameter timeoutMs

      How long (in ms) to poll for transaction mined until aborting. Transaction receipt with decoded log args.

    method callAsync

    callAsync: (callData: CallData, defaultBlock?: BlockParam) => Promise<string>;
    • Call a smart contract method at a given block height

      Parameter callData

      Call data

      Parameter defaultBlock

      Block height at which to make the call. Defaults to latest

      Returns

      The raw call result

    method createAccessListAsync

    createAccessListAsync: (
    callData: CallData,
    defaultBlock?: BlockParam
    ) => Promise<TxAccessListWithGas>;
    • Generate an access list for an ethereum call and also compute the gas used.

      Parameter callData

      Call data

      Parameter defaultBlock

      Block height at which to make the call. Defaults to 'latest'.

      Returns

      The access list and gas used.

    method doesContractExistAtAddressAsync

    doesContractExistAtAddressAsync: (address: string) => Promise<boolean>;
    • Check if a contract exists at a given address

      Parameter address

      Address to which to check

      Returns

      Whether or not contract code was found at the supplied address

    method estimateGasAsync

    estimateGasAsync: (txData: TxData) => Promise<number>;
    • Calculate the estimated gas cost for a given transaction

      Parameter txData

      Transaction data

      Returns

      Estimated gas cost

    method getAccountNonceAsync

    getAccountNonceAsync: (
    address: string,
    defaultBlock?: BlockParam
    ) => Promise<number>;
    • Fetches the nonce for an account (transaction count for EOAs).

      Parameter address

      Address of account.

      Parameter defaultBlock

      Block height at which to make the call. Defaults to latest

      Returns

      Account nonce.

    method getAvailableAddressesAsync

    getAvailableAddressesAsync: () => Promise<string[]>;
    • Retrieve the user addresses available through the backing provider

      Returns

      Available user addresses

    method getBalanceInWeiAsync

    getBalanceInWeiAsync: (
    owner: string,
    defaultBlock?: BlockParam
    ) => Promise<BigNumber>;
    • Retrieves an accounts Ether balance in wei

      Parameter owner

      Account whose balance you wish to check

      Parameter defaultBlock

      The block depth at which to fetch the balance (default=latest)

      Returns

      Balance in wei

    method getBaseFeePerGasAsync

    getBaseFeePerGasAsync: () => Promise<BigNumber>;
    • Fetch the base fee per gas for the pending block.

    method getBlockIfExistsAsync

    getBlockIfExistsAsync: (
    blockParam: string | BlockParam
    ) => Promise<BlockWithoutTransactionData | undefined>;
    • Fetch a specific Ethereum block without transaction data

      Parameter blockParam

      The block you wish to fetch (blockHash, blockNumber or blockLiteral)

      Returns

      The requested block without transaction data, or undefined if block was not found (e.g the node isn't fully synced, there was a block re-org and the requested block was uncles, etc...)

    method getBlockNumberAsync

    getBlockNumberAsync: () => Promise<number>;
    • Fetches the latest block number

      Returns

      Block number

    method getBlockTimestampAsync

    getBlockTimestampAsync: (blockParam: string | BlockParam) => Promise<number>;
    • Fetch a block's timestamp

      Parameter blockParam

      The block you wish to fetch (blockHash, blockNumber or blockLiteral)

      Returns

      The block's timestamp

    method getBlockWithTransactionDataAsync

    getBlockWithTransactionDataAsync: (
    blockParam: string | BlockParam
    ) => Promise<BlockWithTransactionData>;
    • Fetch a specific Ethereum block with transaction data

      Parameter blockParam

      The block you wish to fetch (blockHash, blockNumber or blockLiteral)

      Returns

      The requested block with transaction data

    method getChainIdAsync

    getChainIdAsync: () => Promise<number>;
    • Fetches the chainId of the backing Ethereum node

      Returns

      The chain id

    method getContractCodeAsync

    getContractCodeAsync: (
    address: string,
    defaultBlock?: BlockParam
    ) => Promise<string>;
    • Gets the contract code by address

      Parameter address

      Address of the contract

      Parameter defaultBlock

      Block height at which to make the call. Defaults to latest Code of the contract

    method getContractDefaults

    getContractDefaults: () => Partial<CallData> | undefined;
    • Get the contract defaults set to the Web3Wrapper instance CallAndTxnData defaults (e.g gas, gasPrice, nonce, etc...)

    method getGasPriceAsync

    getGasPriceAsync: () => Promise<BigNumber>;
    • Fetch the current gas price. For post-London hardfork chains, this will be baseFeePerGas + maxPriorityFeePerGas

    method getLogsAsync

    getLogsAsync: (filter: FilterObject) => Promise<LogEntry[]>;
    • Retrieve smart contract logs for a given filter

      Parameter filter

      Parameters by which to filter which logs to retrieve

      Returns

      The corresponding log entries

    method getMaxPriorityFeePerGasAsync

    getMaxPriorityFeePerGasAsync: () => Promise<BigNumber>;
    • Fetch the current max piority fee per gas. This is the suggested miner tip to get mined in the current block.

    method getNetworkIdAsync

    getNetworkIdAsync: () => Promise<number>;
    • Fetches the networkId of the backing Ethereum node

      Returns

      The network id

    method getNodeTypeAsync

    getNodeTypeAsync: () => Promise<NodeType>;
    • Returns either NodeType.Geth or NodeType.Ganache depending on the type of the backing Ethereum node. Throws for any other type of node.

    method getNodeVersionAsync

    getNodeVersionAsync: () => Promise<string>;
    • Fetch the backing Ethereum node's version string (e.g MetaMask/v4.2.0)

      Returns

      Ethereum node's version string

    method getProvider

    getProvider: () => SupportedProvider;
    • Retrieve the Web3 provider Web3 provider instance

    method getTransactionByHashAsync

    getTransactionByHashAsync: (txHash: string) => Promise<Transaction>;
    • Retrieves the transaction data for a given transaction

      Parameter txHash

      Transaction hash

      Returns

      The raw transaction data

    method getTransactionReceiptIfExistsAsync

    getTransactionReceiptIfExistsAsync: (
    txHash: string
    ) => Promise<TransactionReceipt | undefined>;
    • Retrieves the transaction receipt for a given transaction hash if found

      Parameter txHash

      Transaction hash

      Returns

      The transaction receipt, including it's status (0: failed, 1: succeeded). Returns undefined if transaction not found.

    method getTransactionTraceAsync

    getTransactionTraceAsync: (
    txHash: string,
    traceParams: TraceParams
    ) => Promise<TransactionTrace>;
    • Gets the debug trace of a transaction

      Parameter txHash

      Hash of the transactuon to get a trace for

      Parameter traceParams

      Config object allowing you to specify if you need memory/storage/stack traces. Transaction trace

    method increaseTimeAsync

    increaseTimeAsync: (timeDelta: number) => Promise<number>;
    • Increase the next blocks timestamp on TestRPC/Ganache or Geth local node. Will throw if provider is neither TestRPC/Ganache or Geth.

      Parameter timeDelta

      Amount of time to add in seconds

    method isAddress

    static isAddress: (address: string) => boolean;
    • Check if an address is a valid Ethereum address

      Parameter address

      Address to check

      Returns

      Whether the address is a valid Ethereum address

    method isSenderAddressAvailableAsync

    isSenderAddressAvailableAsync: (senderAddress: string) => Promise<boolean>;
    • Check whether an address is available through the backing provider. This can be useful if you want to know whether a user can sign messages or transactions from a given Ethereum address.

      Parameter senderAddress

      Address to check availability for

      Returns

      Whether the address is available through the provider.

    method mineBlockAsync

    mineBlockAsync: () => Promise<void>;
    • Mine a block on a TestRPC/Ganache local node

    method revertSnapshotAsync

    revertSnapshotAsync: (snapshotId: number) => Promise<boolean>;
    • Revert the blockchain state to a previous snapshot state on TestRPC/Ganache local node

      Parameter snapshotId

      snapshot id to revert to

      Returns

      Whether the revert was successful

    method sendRawPayloadAsync

    sendRawPayloadAsync: <A>(payload: JSONRPCRequestPayload) => Promise<A>;
    • Sends a raw Ethereum JSON RPC payload and returns the response's result key

      Parameter payload

      A partial JSON RPC payload. No need to include version, id, params (if none needed) The contents nested under the result key of the response body

    method sendTransactionAsync

    sendTransactionAsync: (txData: TxData) => Promise<string>;
    • Send a transaction

      Parameter txData

      Transaction data

      Returns

      Transaction hash

    method setHeadAsync

    setHeadAsync: (blockNumber: number) => Promise<void>;
    • Calls the 'debug_setHead' JSON RPC method, which sets the current head of the local chain by block number. Note, this is a destructive action and may severely damage your chain. Use with extreme caution. As of now, this is only supported by Geth. It sill throw if the 'debug_setHead' method is not supported.

      Parameter blockNumber

      The block number to reset to.

    method setProvider

    setProvider: (supportedProvider: SupportedProvider) => void;
    • Update the used Web3 provider

      Parameter provider

      The new Web3 provider to be set

    method signMessageAsync

    signMessageAsync: (address: string, message: string) => Promise<string>;
    • Sign a message with a specific address's private key (eth_sign)

      Parameter address

      Address of signer

      Parameter message

      Message to sign

      Returns

      Signature string (might be VRS or RSV depending on the Signer)

    method signTypedDataAsync

    signTypedDataAsync: (address: string, typedData: any) => Promise<string>;
    • Sign an EIP712 typed data message with a specific address's private key (eth_signTypedData)

      Parameter address

      Address of signer

      Parameter typedData

      Typed data message to sign

      Returns

      Signature string (as RSV)

    method takeSnapshotAsync

    takeSnapshotAsync: () => Promise<number>;
    • Take a snapshot of the blockchain state on a TestRPC/Ganache local node

      Returns

      The snapshot id. This can be used to revert to this snapshot

    method toBaseUnitAmount

    static toBaseUnitAmount: (
    amount: BigNumber | number,
    decimals: number
    ) => BigNumber;
    • A baseUnit is defined as the smallest denomination of a token. An amount expressed in baseUnits is the amount expressed in the smallest denomination. E.g: 1 unit of a token with 18 decimal places is expressed in baseUnits as 1000000000000000000

      Parameter amount

      The amount of units that you would like converted to baseUnits.

      Parameter decimals

      The number of decimal places the unit amount has. The amount in baseUnits.

    method toUnitAmount

    static toUnitAmount: (amount: BigNumber, decimals: number) => BigNumber;
    • A unit amount is defined as the amount of a token above the specified decimal places (integer part). E.g: If a currency has 18 decimal places, 1e18 or one quintillion of the currency is equivalent to 1 unit.

      Parameter amount

      The amount in baseUnits that you would like converted to units.

      Parameter decimals

      The number of decimal places the unit amount has. The amount in units.

    method toWei

    static toWei: (ethAmount: BigNumber) => BigNumber;
    • Convert an Ether amount from ETH to Wei

      Parameter ethAmount

      Amount of Ether to convert to wei

      Returns

      Amount in wei

    Interfaces

    interface BlockWithoutTransactionDataRPC

    interface BlockWithoutTransactionDataRPC extends AbstractBlockRPC {}

      property transactions

      transactions: string[];

        interface BlockWithTransactionDataRPC

        interface BlockWithTransactionDataRPC extends AbstractBlockRPC {}

          property transactions

          transactions: TransactionRPC[];

            interface CallDataRPC

            interface CallDataRPC extends CallTxDataBaseRPC {}

              property from

              from?: string;

                interface GethCallOverridesRPC

                interface GethCallOverridesRPC {}

                  index signature

                  [address: string]: {
                  code?: string;
                  nonce?: string;
                  balance?: string;
                  };

                    interface LogEntryRPC

                    interface LogEntryRPC {}

                      property address

                      address: string;

                        property blockHash

                        blockHash: string | null;

                          property blockNumber

                          blockNumber: string | null;

                            property data

                            data: string;

                              property logIndex

                              logIndex: string | null;

                                property topics

                                topics: string[];

                                  property transactionHash

                                  transactionHash: string;

                                    property transactionIndex

                                    transactionIndex: string | null;

                                      interface TransactionReceiptRPC

                                      interface TransactionReceiptRPC {}

                                        property blockHash

                                        blockHash: string;

                                          property blockNumber

                                          blockNumber: string;

                                            property contractAddress

                                            contractAddress: string | null;

                                              property cumulativeGasUsed

                                              cumulativeGasUsed: string;

                                                property from

                                                from: string;

                                                  property gasUsed

                                                  gasUsed: string;

                                                    property logs

                                                    logs: LogEntryRPC[];

                                                      property status

                                                      status: TransactionReceiptStatusRPC;

                                                        property to

                                                        to: string;

                                                          property transactionHash

                                                          transactionHash: string;

                                                            property transactionIndex

                                                            transactionIndex: string;

                                                              interface TransactionRPC

                                                              interface TransactionRPC {}

                                                                property blockHash

                                                                blockHash: string | null;

                                                                  property blockNumber

                                                                  blockNumber: string | null;

                                                                    property from

                                                                    from: string;

                                                                      property gas

                                                                      gas: string;

                                                                        property gasPrice

                                                                        gasPrice?: string;

                                                                          property hash

                                                                          hash: string;

                                                                            property input

                                                                            input: string;

                                                                              property maxFeePerGas

                                                                              maxFeePerGas?: string;

                                                                                property maxPriorityFeePerGas

                                                                                maxPriorityFeePerGas?: string;

                                                                                  property nonce

                                                                                  nonce: string;

                                                                                    property to

                                                                                    to: string | null;

                                                                                      property transactionIndex

                                                                                      transactionIndex: string | null;

                                                                                        property value

                                                                                        value: string;

                                                                                          interface TxDataRPC

                                                                                          interface TxDataRPC extends CallDataRPC {}

                                                                                            Enums

                                                                                            enum NodeType

                                                                                            enum NodeType {
                                                                                            Geth = 'GETH',
                                                                                            Ganache = 'GANACHE',
                                                                                            }

                                                                                              member Ganache

                                                                                              Ganache = 'GANACHE'

                                                                                                member Geth

                                                                                                Geth = 'GETH'

                                                                                                  enum Web3WrapperErrors

                                                                                                  enum Web3WrapperErrors {
                                                                                                  TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT',
                                                                                                  }

                                                                                                    member TransactionMiningTimeout

                                                                                                    TransactionMiningTimeout = 'TRANSACTION_MINING_TIMEOUT'

                                                                                                      Type Aliases

                                                                                                      type TransactionReceiptStatusRPC

                                                                                                      type TransactionReceiptStatusRPC = null | string | 0 | 1;

                                                                                                        Package Files (4)

                                                                                                        Dependencies (9)

                                                                                                        Dev Dependencies (17)

                                                                                                        Peer Dependencies (0)

                                                                                                        No peer dependencies.

                                                                                                        Badge

                                                                                                        To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                        You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@0x/web3-wrapper.

                                                                                                        • Markdown
                                                                                                          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@0x/web3-wrapper)
                                                                                                        • HTML
                                                                                                          <a href="https://www.jsdocs.io/package/@0x/web3-wrapper"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>