Skip to main content

Hooks

useBlockMeta

Queries block metadata.

useBlockNumber

Get the current block number. Will update automatically when the new block is mined.

useCall

Makes a call to a specific method of a specific contract and returns the value or an error if present. The hook will cause the component to refresh when a new block is mined and the return value changes. A syntax sugar for useRawCall that uses ABI, function name, and arguments instead of raw data. If typechain contract is used in call parameter then method name and arguments will be type checked. Result will be typed as well. More on type checking here.

Parameters

  • call: Falsy | Call<T, MN> - a single call to a contract, also see Call

Returns: The hook returns CallResult type.

Example

function useTotalSupply(tokenAddress: string | undefined): BigNumber | undefined {
const { value, error } = useCall(tokenAddress && {
contract: new Contract(tokenAddress, ERC20Interface),
method: 'totalSupply',
args: []
}) ?? {}
if(error) {
console.error(error.message)
return undefined
}
return value?.[0]
}

useCalls

Makes calls to specific methods of specific contracts and returns values or an error if present. The hook will cause the component to refresh when a new block is mined and the return values change. A syntax sugar for useRawCalls that uses ABI, function name, and arguments instead of raw data.

Parameters

  • calls: (Falsy | Call<Contract, string>)[] - a list of contract calls, also see Call.
  • queryParams: QueryParams - see QueryParams.

Returns: a list of results (see CallResult).

Example

function useTotalSupplies(tokenAddresses: string[] | undefined): (BigNumber | undefined)[] {
const calls = tokenAddresses?.map(address => ({
contract: new Contract(address, ERC20Interface),
method: 'totalSupply',
args: []
})) ?? []
const results = useCalls(calls) ?? []
results.forEach((result, idx) => {
if(result && result.error) {
console.error(`Error encountered calling 'totalSupply' on ${calls[idx]?.contract.address}: ${result.error.message}`)
}
})
return results.map(result => result?.value?.[0])
}

useChainCall

Deprecated: It's recommended to use useCall instead.

Makes a call to a specific contract and returns its value. The hook will cause the component to refresh whenever a new block is mined and the value is changed. Calls will be combined into a single multicall across all uses of useChainCall.

Parameters

  • call: RawCall | Falsy - a single call, also see RawCall. A call can be Falsy, as it is important to keep the same ordering of hooks even if in a given render cycle there might be not enough information to perform a call.

Returns: encoded result or Falsy value if call didn't return yet or an error occurred.

useChainCalls

Deprecated: It's recommended to use useCalls instead.

Makes multiple calls to specific contracts and returns corresponding values. The hook will cause the component to refresh when values change. Calls will be combined into a single multicall across all uses of useChainCall.

Parameters

  • calls: (RawCall | Falsy)[] - list of calls, also see RawCall. Calls need to be in the same order across component renders.

Returns: encoded result or Falsy value if call didn't return yet or an error occurred.

useChainMeta

useChainState

useConfig

Returns singleton instance of Config. Takes no parameters.

useContractCall

Deprecated: It is recommended to use useCall instead of this method as it is deprecated.

Makes a call to a specific contract and returns the value. The hook will cause the component to refresh when a new block is mined and the return value changes. A syntax sugar for useChainCall that uses ABI, function name, and arguments instead of raw data.

Parameters

  • call: ContractCall | Falsy - a single call to a contract, also see ContractCall.

Returns: the result of a call or undefined if call didn't return yet.

useContractCalls

Deprecated: It is recommended to use useCalls instead of this method as it is deprecated.

Makes calls to specific contracts and returns values. The hook will cause the component to refresh when a new block is mined and the return values change. A syntax sugar for useChainCalls that uses ABI, function name, and arguments instead of raw data.

Parameters

  • calls: (ContractCall | Falsy)[] - a list of contract calls , also see ContractCall.

Returns: array of results. Undefined if call didn't return yet.

useContractFunction

Hook returns an object with four variables: state , send, events , and resetState. The state represents the status of transaction. See TransactionStatus.

resetState can be used to reset the state to None after a transaction attempt has either succeeded or failed.

The events is a array of parsed transaction events of type LogDescription.

To send a transaction use send function returned by useContractFunction. The function forwards arguments to ethers.js contract object, so that arguments map 1 to 1 with Solidity function arguments. Additionally, there can be one extra argument - TransactionOverrides, which can be used to manipulate transaction parameters like gasPrice, nonce, etc

If typechain contract is supplied as contract parameter then function name and send arguments will be type checked. More on type checking here.

Parameters

  • contract: Falsy | T - contract which function is to be called , also see Contract
  • functionName: FN - name of function to call
  • options: TransactionOptions - additional options of type TransactionOptions

Returns: object with variables: send , state , events: { send: (...args: any[]) => void, state: TransactionStatus, events: LogDescription[] }.

Example

const { state, send } = useContractFunction(contract, 'deposit', { transactionName: 'Wrap' })

const depositEther = (etherAmount: string) => {
send({ value: utils.parseEther(etherAmount) })
}
const { state, send } = useContractFunction(contract, 'withdraw', { transactionName: 'Unwrap' })

const withdrawEther = (wethAmount: string) => {
send(utils.parseEther(wethAmount))
}

useEtherBalance

Returns ether balance of a given account.

Parameters

  • address: string | Falsy - address of an account

Returns: a balance of the account which is BigNumber or undefined if not connected to network or address is a falsy value

Example

const { account } = useEthers()
const etherBalance = useEtherBalance(account)

return (
{etherBalance && <p>Ether balance: {formatEther(etherBalance)} ETH </p>}
)

useEthers

Returns connection state and functions that allow to manipulate the state. Requires: <ConfigProvider>

Returns: Object with the following:

  • account: string - current user account (or undefined if not connected)
  • chainId: ChainId - current chainId (or undefined if not connected)
  • library: Web3Provider - an instance of ethers Web3Provider (or undefined if not connected)
  • active: boolean - returns if provider is connected (read or write mode)
  • activateBrowserWallet() - function that will initiate connection to browser web3 extension (e.g. Metamask)
  • async activate(connector: AbstractConnector, onError?: (error: Error) => void, throwErrors?: boolean) - function that allows to connect to a wallet
  • async deactivate() - function that disconnects wallet
  • error?: Error - an error that occurred during connecting (e.g. connection is broken, unsupported network)

useGasPrice

Returns gas price of current network.

Returns: gas price of current network. undefined if not initialised.

useLogs

Makes a call to get the logs for a specific contract event and returns the decoded logs or an error if present. The hook will cause the component to refresh when a new block is mined and the returned logs change. A syntax sugar for useRawLogs that uses ABI, event name, and arguments instead of raw data.

Parameters

  • filter: Falsy | TypedFilter<T, EN> - an event filter (see TypedFilter)
  • queryParams: LogQueryParams - allows for additional configuration of the query (see LogQueryParams)

Returns: an array of decoded logs (see LogsResult)

useLookupAddress

useLookupAddress is a hook that is used to retrieve the ENS (e.g. name.eth) or Rave Names (e.g. name.ftm) for a specific address.

Parameters

  • address: undefined | string - address to lookup
  • options: LookupAddressOptions - additional options

Returns: Object with the following:

  • ens: string | null | undefined - ENS or Rave name of the account or null if not found.
  • isLoading: boolean - indicates whether the lookup is in progress.
  • error: Error | null - error that occurred during the lookup or null if no error occurred.

Example

const { account } = useEthers()
const { ens } = useLookupAddress(account)

return (
<p>Account: {ens ?? account}</p>
)

useMulticallAddress

Returns an address of the multicall contract used on a given chain.

Parameters

useNotifications

useNotifications is a hook that is used to access notifications. Notifications include information about: new transactions, transaction success or failure, as well as connection to a new wallet. To use this hook call:

  const { notifications } = useNotifications()

notifications is an array of NotificationPayload.

Each notification is removed from notifications after time declared in config.notifications.expirationPeriod

Each can be one of the following:

  {
type: 'walletConnected';
address: string
}
  {
type: 'transactionStarted';
submittedAt: number
transaction: TransactionResponse;
transactionName?: string
}
  {
type: 'transactionSucceed'
transaction: TransactionResponse
originalTransaction?: TransactionResponse
receipt: TransactionReceipt
transactionName?: string
}
  {
type: 'transactionFailed'
transaction: TransactionResponse
originalTransaction?: TransactionResponse
receipt: TransactionReceipt
transactionName?: string
}

See: Transaction Response

See: Transaction Receipt

useRawCall

A low-level function that makes a call to a specific method of a specific contract and returns the value or error if present. The hook will cause the component to refresh whenever a new block is mined and the value is changed. Calls will be combined into a single multicall across all uses of useChainCall. It is recommended to use useCall where applicable instead of this method.

Parameters

  • call: RawCall | Falsy - a single call, also see RawCall. A call can be Falsy, as it is important to keep the same ordering of hooks even if in a given render cycle and there might be not enough information to perform a call.

Returns: result of multicall call. The hook returns RawCallResult type. That is: undefined when call didn't return yet or object { success: boolean, value: string } if it did, success - boolean indicating whether call was successful or not, value - encoded result when success is true or encoded error message when success is false.

useRawCalls

A low-level function that makes multiple calls to specific methods of specific contracts and returns values or error if present. The hook will cause the component to refresh when values change. Calls will be combined into a single multicall across all uses of useChainCall. It is recommended to use useCalls where applicable instead of this method.

Parameters

  • calls: (RawCall | Falsy)[] - List of calls, also see RawCall. Calls need to be in the same order across component renders.

Returns: list of multicall calls. See RawCallResult.

useRawLogs

Returns all blockchain logs given a block filter. The hook will cause the component to refresh when a new block is mined and the returned logs change.

Parameters

  • filter: Falsy | Filter | FilterByBlockHash | Promise<Filter | FilterByBlockHash> - an event filter, which blocks to query
  • queryParams: QueryParams - allows for additional configuration of the query (see QueryParams)

Returns: an array of logs

See: useLogs for a more easy-to-use version of the query.

useResolveName

useResolveName is a hook that is used to resolve an ENS name (e.g. name.eth) to a specific address.

Parameters

  • name: undefined | string - ENS name to be resolved

Returns: Object with the following:

  • address: string | null | undefined - resolved address for the given ENS name or null if not found.
  • isLoading: boolean - indicates whether the lookup is in progress.
  • error: Error | null - error that occurred during the lookup or null if no error occurred.

useSendTransaction

Hook returns an object with three variables: state, resetState, and sendTransaction. `state represents the status of transaction. See TransactionStatus.

resetState can be used to reset the state to None after a transaction attempt has either succeeded or failed.

To send a transaction use sendTransaction function returned by useSendTransaction.

Function accepts a Transaction Request object as a parameter.

Parameters

Returns: object with two variables: sendTransaction and state: { sendTransaction: (...args: any[]) => void, state: TransactionStatus }.

Example

const { sendTransaction, state } = useSendTransaction({ transactionName: 'Send Ethereum' })

const handleClick = () => {
...
sendTransaction({ to: address, value: utils.parseEther(amount) })
}

useSigner

Returns a signer if an external wallet is connected.

Returns: a JsonRpcSigner if one is available in the provider. undefined otherwise.

useToken

Returns name, symbol, decimals and token supply of a given token.

Parameters

  • tokenAddress: string | Falsy - address of a token contract.
  • queryParams: QueryParams - see QueryParams.

Returns: a token info object (see TokenInfo) or undefined if all four methods don't exist on a token.

Example

const DAI_ADDRESS = '0x6b175474e89094c44da98b954eedeac495271d0f'
const daiInfo = useToken(DAI_ADDRESS)

return daiInfo ? (
<>
<p>Dai name: {daiInfo?.name}</p>
<p>Dai symbol: {daiInfo?.symbol}</p>
<p>Dai decimals: {daiInfo?.decimals}</p>
<p>Dai totalSupply: {daiInfo?.totalSupply ? formatUnits(daiInfo?.totalSupply, daiInfo?.decimals) : ''}</p>
</>
) : null

useTokenAllowance

Returns allowance (tokens left to use by spender) for given token owner - spender relationship.

Parameters

  • tokenAddress: string | Falsy - address of a token contract
  • ownerAddress: string | Falsy - address of an account to which tokens are linked
  • spenderAddress: string | Falsy - address of an account allowed to spend tokens
  • queryParams: QueryParams - see QueryParams.

Returns: an allowance which is BigNumber, or undefined if any address or token is Falsy or not connected.

Example

const TOKEN_ADDRESS = '0x6b175474e89094c44da98b954eedeac495271d0f'
const SPENDER_ADDRESS = '0xA193E42526F1FEA8C99AF609dcEabf30C1c29fAA'
const { account, chainId } = useEthers()
const allowance = useTokenAllowance(TOKEN_ADDRESS, account, SPENDER_ADDRESS)

return (
{allowance && <p>Remaining allowance: {formatUnits(allowance, 18)} tokens</p>}
)

useTokenBalance

Returns a balance of a given token for a given address.

Parameters

  • tokenAddress: string | Falsy - address of a token contract.
  • address: string | Falsy - address of an account.
  • queryParams: QueryParams - see QueryParams.

Returns: a balance which is BigNumber, or undefined if address or token is Falsy or not connected.

Example

const DAI_ADDRESS = '0x6b175474e89094c44da98b954eedeac495271d0f'
const { account } = useEthers()
const daiBalance = useTokenBalance(DAI_ADDRESS, account)

return (
{daiBalance && <p>Dai balance: {formatUnits(daiBalance, 18)} DAI</p>}
)

useTokenList

Fetches ERC20 token list under a given address and filters them by chain id. Optionally it can filter also by token tags.

Parameters

  • tokenListURI: string - URI to fetch token list from
  • overrideChainId: number - chain id to filter tokens by (if not specified then current network is used)
  • tags: string[] - list of tags to filter tokens by (token is included if it contains any of given tags)

Returns: name: string - token list name. logoURI: string - URI to get token list logo from. tokens: TokenInfo[] - list of TokenInfo objects. If an error occurs undefined is returned.

Example

const { name, logoURI, tokens } = useTokenList(UNISWAP_DEFAULT_TOKEN_LIST_URI) || {}
const httpSource = logoURI && logoURI.startsWith('ipfs') ? logoURI.replace('ipfs://', 'https://ipfs.io/ipfs/') : logoURI
return (
<div>
<div>
{name}
{httpSource && <img src={httpSource} alt={name}/>}
</div>
<ol>
{tokens?.map(token => (
<li>
<ul>
<li>Name: {token.name}</li>
<li>Symbol: {token.symbol}</li>
<li>Decimals: {token.decimals}</li>
<li>Address: {token.address}</li>
</ul>
</li>
))}
</ol>
</div>
)

See: Token lists

See: Token list json example

See: TokenInfo object

useTransactions

useTransactions hook returns a list transactions. This list contains all transactions that were sent using useContractFunction. Transactions are stored in local storage and the status is rechecked on every new block. Each transaction has following type:

export interface StoredTransaction {
transaction: TransactionResponse
submittedAt: number
receipt?: TransactionReceipt
lastCheckedBlockNumber?: number
transactionName?: string
originalTransaction?: TransactionResponse
}

See: Transaction Response

See: Transaction Receipt

useUpdateConfig