-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathusePaymentMethods.ts
More file actions
297 lines (269 loc) · 9.48 KB
/
Copy pathusePaymentMethods.ts
File metadata and controls
297 lines (269 loc) · 9.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { useQuery } from "@tanstack/react-query";
import { chains } from "../../../bridge/Chains.js";
import { routes } from "../../../bridge/Routes.js";
import type { Token } from "../../../bridge/types/Token.js";
import {
getCachedChain,
getInsightEnabledChainIds,
} from "../../../chains/utils.js";
import type { ThirdwebClient } from "../../../client/client.js";
import { getOwnedTokens } from "../../../insight/get-tokens.js";
import { toTokens } from "../../../utils/units.js";
import type { Wallet } from "../../../wallets/interfaces/wallet.js";
import {
type GetWalletBalanceResult,
getWalletBalance,
} from "../../../wallets/utils/getWalletBalance.js";
import type { PaymentMethod } from "../machines/paymentMachine.js";
import { useActiveWallet } from "./wallets/useActiveWallet.js";
type OwnedTokenWithQuote = {
originToken: Token;
balance: bigint;
originAmount: bigint;
};
/**
* Hook that returns available payment methods for BridgeEmbed
* Fetches real routes data based on the destination token
*
* @param options - Configuration options
* @param options.destinationToken - The destination token to find routes for
* @param options.client - ThirdwebClient for API calls
* @returns Available payment methods with route data
*
* @example
* ```tsx
* const { data: paymentMethods, isLoading, error } = usePaymentMethods({
* destinationToken,
* client
* });
* ```
*/
export function usePaymentMethods(options: {
destinationToken: Token;
destinationAmount: string;
client: ThirdwebClient;
payerWallet?: Wallet;
includeDestinationToken?: boolean;
}) {
const {
destinationToken,
destinationAmount,
client,
payerWallet,
includeDestinationToken,
} = options;
const localWallet = useActiveWallet(); // TODO (bridge): get all connected wallets
const wallet = payerWallet || localWallet;
const routesQuery = useQuery({
enabled: !!wallet,
queryFn: async (): Promise<PaymentMethod[]> => {
if (!wallet) {
throw new Error("No wallet connected");
}
// 1. Get all supported chains
const [allChains, insightEnabledChainIds] = await Promise.all([
chains({ client }),
getInsightEnabledChainIds(),
]);
// 2. Check insight availability for all chains
const insightEnabledChains = allChains.filter((c) =>
insightEnabledChainIds.includes(c.chainId),
);
// 3. Get all owned tokens for insight-enabled chains
let allOwnedTokens: Array<{
balance: bigint;
originToken: Token;
}> = [];
let page = 0;
const limit = 500;
while (true) {
let batch: GetWalletBalanceResult[];
try {
batch = await getOwnedTokens({
chains: insightEnabledChains.map((c) => getCachedChain(c.chainId)),
client,
ownerAddress: wallet.getAccount()?.address || "",
queryOptions: {
limit,
metadata: "false",
page,
},
});
} catch (error) {
// If the batch fails, fall back to getting native balance for each chain
console.warn(`Failed to get owned tokens for batch ${page}:`, error);
const chainsInBatch = insightEnabledChains.map((c) =>
getCachedChain(c.chainId),
);
const nativeBalances = await Promise.allSettled(
chainsInBatch.map(async (chain) => {
const balance = await getWalletBalance({
address: wallet.getAccount()?.address || "",
chain,
client,
});
return balance;
}),
);
// Transform successful native balances into the same format as getOwnedTokens results
batch = nativeBalances
.filter((result) => result.status === "fulfilled")
.map((result) => result.value)
.filter((balance) => balance.value > 0n);
// Convert to our format
const tokensWithBalance = batch.map((b) => ({
balance: b.value,
originToken: {
address: b.tokenAddress,
chainId: b.chainId,
decimals: b.decimals,
iconUri: "",
name: b.name,
prices: {
USD: 0,
},
symbol: b.symbol,
} as Token,
}));
allOwnedTokens = [...allOwnedTokens, ...tokensWithBalance];
break;
}
if (batch.length === 0) {
break;
}
// Convert to our format and filter out zero balances
const tokensWithBalance = batch
.filter((b) => b.value > 0n)
.map((b) => ({
balance: b.value,
originToken: {
address: b.tokenAddress,
chainId: b.chainId,
decimals: b.decimals,
iconUri: "",
name: b.name,
prices: {
USD: 0,
},
symbol: b.symbol,
} as Token,
}));
allOwnedTokens = [...allOwnedTokens, ...tokensWithBalance];
page += 1;
}
// 4. For each chain where we have owned tokens, fetch possible routes
const chainsWithOwnedTokens = Array.from(
new Set(allOwnedTokens.map((t) => t.originToken.chainId)),
);
const allValidOriginTokens = new Map<string, Token>();
// Add destination token if included
if (includeDestinationToken) {
const tokenKey = `${
destinationToken.chainId
}-${destinationToken.address.toLowerCase()}`;
allValidOriginTokens.set(tokenKey, destinationToken);
}
// Fetch routes for each chain with owned tokens
await Promise.all(
chainsWithOwnedTokens.map(async (chainId) => {
try {
// TODO (bridge): this is quite inefficient, need to fix the popularity sorting to really capture all users tokens
const routesForChain = await routes({
client,
destinationChainId: destinationToken.chainId,
destinationTokenAddress: destinationToken.address,
includePrices: true,
limit: 100,
maxSteps: 3,
originChainId: chainId,
});
// Add all origin tokens from this chain's routes
for (const route of routesForChain) {
// Skip if the origin token is the same as the destination token, will be added later only if includeDestinationToken is true
if (
route.originToken.chainId === destinationToken.chainId &&
route.originToken.address.toLowerCase() ===
destinationToken.address.toLowerCase()
) {
continue;
}
const tokenKey = `${
route.originToken.chainId
}-${route.originToken.address.toLowerCase()}`;
allValidOriginTokens.set(tokenKey, route.originToken);
}
} catch (error) {
// Log error but don't fail the entire operation
console.warn(`Failed to fetch routes for chain ${chainId}:`, error);
}
}),
);
// 5. Filter owned tokens to only include valid origin tokens
const validOwnedTokens: OwnedTokenWithQuote[] = [];
for (const ownedToken of allOwnedTokens) {
const tokenKey = `${
ownedToken.originToken.chainId
}-${ownedToken.originToken.address.toLowerCase()}`;
const validOriginToken = allValidOriginTokens.get(tokenKey);
if (validOriginToken) {
validOwnedTokens.push({
balance: ownedToken.balance,
originAmount: 0n,
originToken: validOriginToken, // Use the token with pricing info from routes
});
}
}
// Sort by dollar balance descending
validOwnedTokens.sort((a, b) => {
const aDollarBalance =
Number.parseFloat(toTokens(a.balance, a.originToken.decimals)) *
(a.originToken.prices["USD"] || 0);
const bDollarBalance =
Number.parseFloat(toTokens(b.balance, b.originToken.decimals)) *
(b.originToken.prices["USD"] || 0);
return bDollarBalance - aDollarBalance;
});
const suitableOriginTokens: OwnedTokenWithQuote[] = [];
for (const token of validOwnedTokens) {
if (
includeDestinationToken &&
token.originToken.address.toLowerCase() ===
destinationToken.address.toLowerCase() &&
token.originToken.chainId === destinationToken.chainId
) {
// Add same token to the front of the list
suitableOriginTokens.unshift(token);
continue;
}
suitableOriginTokens.push(token);
}
const transformedRoutes = [
...suitableOriginTokens.map((s) => ({
balance: s.balance,
originToken: s.originToken,
payerWallet: wallet,
type: "wallet" as const,
})),
];
return transformedRoutes;
},
queryKey: [
"bridge-routes",
destinationToken.chainId,
destinationToken.address,
destinationAmount,
payerWallet?.getAccount()?.address,
includeDestinationToken,
], // 5 minutes
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000,
});
return {
data: routesQuery.data || [],
error: routesQuery.error,
isError: routesQuery.isError,
isLoading: routesQuery.isLoading,
isSuccess: routesQuery.isSuccess,
refetch: routesQuery.refetch,
};
}