eth-hooks2
Version:
A set of hooks to turbocharge buidling
1 lines • 2.89 kB
Source Map (JSON)
{"version":3,"sources":["../src/hooks/erc/useTokenBalance.ts"],"names":["keys","address"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AAQzB,IAAM,OAAO,UAAU,KAAK,CAAC;AAC7B,IAAM,WAA0B,EAAE,WAAW,aAAa,QAAQ,KAAK,kBAAkB;AAoBlF,IAAM,kBAAkB,CAC7B,UACA,SACA,UAA0B,0BAA0B,MACzB;AAC3B,QAAM,OAAO,CAAC,EAAE,GAAG,UAAU,GAAG,YAAY,QAAQ,EAAE,GAAG,EAAE,QAAQ,CAAC;AACpE,QAAM,EAAE,MAAM,SAAS,OAAO,IAAI;AAAA,IAChC;AAAA,IACA,OAAOA,UAA6B;AAvCxC;AAwCM,YAAM,EAAE,SAAAC,SAAQ,IAAID,MAAK,SAAS;AAElC,WAAI,qCAAU,aAAYC,UAAS;AACjC,cAAM,aAAyB,QAAM,0CAAU,cAAV,kCAAsBA,cAAa;AACxE,eAAO;AAAA,MACT,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAAA,IACA;AAAA,MACE,GAAG,oBAA+B,OAAO;AAAA,MACzC,aAAa,CAAC,WAAW,eAAc,uCAAW,WAAS,uCAAW;AAAA,IACxE;AAAA,EACF;AAEA,QAAM,cAAc,sBAAsB;AAC1C,mBAAiB,SAAS,aAAa,OAAO;AAE9C,SAAO,CAAC,QAAQ,MAAM,SAAS,MAAM;AACvC","sourcesContent":["import { BigNumber } from '@ethersproject/bignumber';\nimport { BaseContract } from '@ethersproject/contracts';\nimport { useQuery } from 'react-query';\n\nimport { useBlockNumberContext } from '~~/context';\nimport { contractKey, mergeDefaultUpdateOptions, processQueryOptions, TRequiredKeys } from '~~/functions';\nimport { useEthersUpdater } from '~~/hooks/useEthersUpdater';\nimport { THookResult, TUpdateOptions } from '~~/models';\nimport { keyNamespace } from '~~/models/constants';\n\nconst zero = BigNumber.from(0);\nconst queryKey: TRequiredKeys = { namespace: keyNamespace.signer, key: 'useTokenBalance' } as const;\n\ntype ERC20 = {\n balanceOf: (address: string) => Promise<BigNumber>;\n};\n\n/**\n * #### Summary\n * Get the balance of an ERC20 token in an address\n *\n * ##### ✏️ Notes\n * - uses the ethers.Contract object's provider to access the network\n *\n * @category Hooks\n *\n * @param contract ERC20 token to get the balance of\n * @param address Address of wallet that holds the tokens\n * @param options Options for how often and when to update\n * @returns\n */\nexport const useTokenBalance = <GContract extends BaseContract & ERC20>(\n contract: GContract,\n address: string,\n options: TUpdateOptions = mergeDefaultUpdateOptions()\n): THookResult<BigNumber> => {\n const keys = [{ ...queryKey, ...contractKey(contract) }, { address }] as const;\n const { data, refetch, status } = useQuery(\n keys,\n async (keys): Promise<BigNumber> => {\n const { address } = keys.queryKey[1];\n\n if (contract?.provider && address) {\n const newBalance: BigNumber = (await contract?.balanceOf?.(address)) ?? zero;\n return newBalance;\n } else {\n return zero;\n }\n },\n {\n ...processQueryOptions<BigNumber>(options),\n isDataEqual: (oldResult, newResult) => oldResult?._hex === newResult?._hex,\n }\n );\n\n const blockNumber = useBlockNumberContext();\n useEthersUpdater(refetch, blockNumber, options);\n\n return [data ?? zero, refetch, status];\n};\n"]}