|
| 1 | +import type { Chain } from "../../../../../../../chains/types.js"; |
| 2 | +import { getCachedChain } from "../../../../../../../chains/utils.js"; |
| 3 | +import type { ThirdwebClient } from "../../../../../../../client/client.js"; |
| 4 | +import { NATIVE_TOKEN_ADDRESS } from "../../../../../../../constants/addresses.js"; |
| 5 | +import { isInsightEnabled } from "../../../../../../../insight/common.js"; |
| 6 | +import { getOwnedTokens } from "../../../../../../../insight/get-tokens.js"; |
| 7 | +import type { Wallet } from "../../../../../../../wallets/interfaces/wallet.js"; |
| 8 | +import { |
| 9 | + type GetWalletBalanceResult, |
| 10 | + getWalletBalance, |
| 11 | +} from "../../../../../../../wallets/utils/getWalletBalance.js"; |
| 12 | +import type { PayUIOptions } from "../../../../../../core/hooks/connection/ConnectButtonProps.js"; |
| 13 | +import type { |
| 14 | + SupportedTokens, |
| 15 | + TokenInfo, |
| 16 | +} from "../../../../../../core/utils/defaultTokens.js"; |
| 17 | +import { type ERC20OrNativeToken, isNativeToken } from "../../nativeToken.js"; |
| 18 | + |
| 19 | +const CHUNK_SIZE = 5; |
| 20 | + |
| 21 | +function chunkChains<T>(chains: T[]): T[][] { |
| 22 | + const chunks: T[][] = []; |
| 23 | + for (let i = 0; i < chains.length; i += CHUNK_SIZE) { |
| 24 | + chunks.push(chains.slice(i, i + CHUNK_SIZE)); |
| 25 | + } |
| 26 | + return chunks; |
| 27 | +} |
| 28 | + |
| 29 | +type FetchBalancesParams = { |
| 30 | + wallet: Wallet; |
| 31 | + accountAddress: string | undefined; |
| 32 | + sourceSupportedTokens: SupportedTokens; |
| 33 | + toChain: Chain; |
| 34 | + toToken: ERC20OrNativeToken; |
| 35 | + tokenAmount: string; |
| 36 | + mode: PayUIOptions["mode"]; |
| 37 | + client: ThirdwebClient; |
| 38 | +}; |
| 39 | + |
| 40 | +export type TokenBalance = { |
| 41 | + balance: GetWalletBalanceResult; |
| 42 | + chain: Chain; |
| 43 | + token: TokenInfo; |
| 44 | +}; |
| 45 | + |
| 46 | +export async function fetchBalancesForWallet({ |
| 47 | + wallet, |
| 48 | + accountAddress, |
| 49 | + sourceSupportedTokens, |
| 50 | + toChain, |
| 51 | + toToken, |
| 52 | + tokenAmount, |
| 53 | + mode, |
| 54 | + client, |
| 55 | +}: FetchBalancesParams): Promise<TokenBalance[]> { |
| 56 | + const account = wallet.getAccount(); |
| 57 | + if (!account) { |
| 58 | + return []; |
| 59 | + } |
| 60 | + |
| 61 | + const balances: TokenBalance[] = []; |
| 62 | + |
| 63 | + // 1. Resolve all unique chains in the supported token map |
| 64 | + const uniqueChains = Object.keys(sourceSupportedTokens).map((id) => |
| 65 | + getCachedChain(Number(id)), |
| 66 | + ); |
| 67 | + |
| 68 | + // 2. Check insight availability once per chain |
| 69 | + const insightSupport = await Promise.all( |
| 70 | + uniqueChains.map(async (c) => ({ |
| 71 | + chain: c, |
| 72 | + enabled: await isInsightEnabled(c), |
| 73 | + })), |
| 74 | + ); |
| 75 | + const insightEnabledChains = insightSupport |
| 76 | + .filter((c) => c.enabled) |
| 77 | + .map((c) => c.chain); |
| 78 | + |
| 79 | + // 3. ERC-20 balances for insight-enabled chains (batched 5 chains / call) |
| 80 | + const insightChunks = chunkChains(insightEnabledChains); |
| 81 | + await Promise.all( |
| 82 | + insightChunks.map(async (chunk) => { |
| 83 | + const owned = await getOwnedTokens({ |
| 84 | + ownerAddress: account.address, |
| 85 | + chains: chunk, |
| 86 | + client, |
| 87 | + }); |
| 88 | + |
| 89 | + for (const b of owned) { |
| 90 | + const matching = sourceSupportedTokens[b.chainId]?.find( |
| 91 | + (t) => t.address.toLowerCase() === b.tokenAddress.toLowerCase(), |
| 92 | + ); |
| 93 | + if (matching) { |
| 94 | + balances.push({ |
| 95 | + balance: b, |
| 96 | + chain: getCachedChain(b.chainId), |
| 97 | + token: matching, |
| 98 | + }); |
| 99 | + } |
| 100 | + } |
| 101 | + }), |
| 102 | + ); |
| 103 | + |
| 104 | + // 4. Build a token map that also includes the destination token so it can be used to pay |
| 105 | + const destinationToken = isNativeToken(toToken) |
| 106 | + ? { |
| 107 | + address: NATIVE_TOKEN_ADDRESS, |
| 108 | + name: toChain.nativeCurrency?.name || "", |
| 109 | + symbol: toChain.nativeCurrency?.symbol || "", |
| 110 | + icon: toChain.icon?.url, |
| 111 | + } |
| 112 | + : toToken; |
| 113 | + |
| 114 | + const tokenMap: Record<number, TokenInfo[]> = { |
| 115 | + ...sourceSupportedTokens, |
| 116 | + [toChain.id]: [ |
| 117 | + destinationToken, |
| 118 | + ...(sourceSupportedTokens[toChain.id] || []), |
| 119 | + ], |
| 120 | + }; |
| 121 | + |
| 122 | + // 5. Fallback RPC balances (native currency & ERC-20 that we couldn't fetch from insight) |
| 123 | + const rpcCalls: Promise<void>[] = []; |
| 124 | + |
| 125 | + for (const [chainIdStr, tokens] of Object.entries(tokenMap)) { |
| 126 | + const chainId = Number(chainIdStr); |
| 127 | + const chain = getCachedChain(chainId); |
| 128 | + |
| 129 | + for (const token of tokens) { |
| 130 | + const isNative = isNativeToken(token); |
| 131 | + const isAlreadyFetched = balances.some( |
| 132 | + (b) => |
| 133 | + b.chain.id === chainId && |
| 134 | + b.token.address.toLowerCase() === token.address.toLowerCase(), |
| 135 | + ); |
| 136 | + if (!isNative && !isAlreadyFetched) { |
| 137 | + // ERC20 on insight-enabled chain already handled by insight call |
| 138 | + continue; |
| 139 | + } |
| 140 | + rpcCalls.push( |
| 141 | + (async () => { |
| 142 | + try { |
| 143 | + const balance = await getWalletBalance({ |
| 144 | + address: account.address, |
| 145 | + chain, |
| 146 | + tokenAddress: isNative ? undefined : token.address, |
| 147 | + client, |
| 148 | + }); |
| 149 | + |
| 150 | + const include = |
| 151 | + token.address === destinationToken.address && |
| 152 | + chain.id === toChain.id |
| 153 | + ? mode === "fund_wallet" && account.address === accountAddress |
| 154 | + ? false |
| 155 | + : Number(balance.displayValue) > Number(tokenAmount) |
| 156 | + : balance.value > 0n; |
| 157 | + |
| 158 | + if (include) { |
| 159 | + balances.push({ balance, chain, token }); |
| 160 | + } |
| 161 | + } catch (err) { |
| 162 | + console.warn( |
| 163 | + `Failed to fetch balance for ${token.symbol} on chain ${chainId}`, |
| 164 | + err, |
| 165 | + ); |
| 166 | + } |
| 167 | + })(), |
| 168 | + ); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + await Promise.all(rpcCalls); |
| 173 | + |
| 174 | + // Remove duplicates (same chainId + token address) |
| 175 | + { |
| 176 | + const uniq: Record<string, TokenBalance> = {}; |
| 177 | + for (const b of balances) { |
| 178 | + const k = `${b.chain.id}-${b.token.address.toLowerCase()}`; |
| 179 | + if (!uniq[k]) { |
| 180 | + uniq[k] = b; |
| 181 | + } |
| 182 | + } |
| 183 | + balances.splice(0, balances.length, ...Object.values(uniq)); |
| 184 | + } |
| 185 | + // 6. Sort so that the destination token always appears first, then tokens on the destination chain, then by chain id |
| 186 | + balances.sort((a, b) => { |
| 187 | + const destAddress = destinationToken.address; |
| 188 | + if (a.chain.id === toChain.id && a.token.address === destAddress) return -1; |
| 189 | + if (b.chain.id === toChain.id && b.token.address === destAddress) return 1; |
| 190 | + if (a.chain.id === toChain.id) return -1; |
| 191 | + if (b.chain.id === toChain.id) return 1; |
| 192 | + return a.chain.id - b.chain.id; |
| 193 | + }); |
| 194 | + |
| 195 | + return balances; |
| 196 | +} |
0 commit comments