-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathusePaymentMethods.ts
More file actions
168 lines (160 loc) · 5.54 KB
/
Copy pathusePaymentMethods.ts
File metadata and controls
168 lines (160 loc) · 5.54 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
import { useQuery } from "@tanstack/react-query";
import type { Quote } from "../../../bridge/index.js";
import { ApiError } from "../../../bridge/types/Errors.js";
import type { Token } from "../../../bridge/types/Token.js";
import type { ThirdwebClient } from "../../../client/client.js";
import { getThirdwebBaseUrl } from "../../../utils/domains.js";
import { getClientFetch } from "../../../utils/fetch.js";
import { toTokens, toUnits } from "../../../utils/units.js";
import type { Wallet } from "../../../wallets/interfaces/wallet.js";
import type { PaymentMethod } from "../machines/paymentMachine.js";
import type { SupportedTokens } from "../utils/defaultTokens.js";
import { useActiveWallet } from "./wallets/useActiveWallet.js";
/**
* 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;
supportedTokens?: SupportedTokens;
}) {
const {
destinationToken,
destinationAmount,
client,
payerWallet,
includeDestinationToken,
supportedTokens,
} = options;
const localWallet = useActiveWallet(); // TODO (bridge): get all connected wallets
const wallet = payerWallet || localWallet;
const query = useQuery({
enabled: !!wallet,
queryFn: async (): Promise<PaymentMethod[]> => {
const account = wallet?.getAccount();
if (!wallet || !account) {
throw new Error("No wallet connected");
}
const url = new URL(
`${getThirdwebBaseUrl("bridge")}/v1/buy/quote/${account.address}`,
);
url.searchParams.set(
"destinationChainId",
destinationToken.chainId.toString(),
);
url.searchParams.set("destinationTokenAddress", destinationToken.address);
url.searchParams.set(
"amount",
toUnits(destinationAmount, destinationToken.decimals).toString(),
);
const clientFetch = getClientFetch(client);
const response = await clientFetch(url.toString());
if (!response.ok) {
const errorJson = await response.json();
throw new ApiError({
code: errorJson.code || "UNKNOWN_ERROR",
correlationId: errorJson.correlationId || undefined,
message: errorJson.message || response.statusText,
statusCode: response.status,
});
}
const {
data: allValidOriginTokens,
}: { data: { quote: Quote; balance: string; token: Token }[] } =
await response.json();
// Sort by enough balance to pay THEN gross balance
const validTokenQuotes = allValidOriginTokens.map((s) => ({
balance: BigInt(s.balance),
originToken: s.token,
payerWallet: wallet,
type: "wallet" as const,
quote: s.quote,
}));
const insufficientBalanceQuotes = validTokenQuotes
.filter((s) => s.balance < s.quote.originAmount)
.sort((a, b) => {
return (
Number.parseFloat(
toTokens(a.quote.originAmount, a.originToken.decimals),
) *
(a.originToken.prices.USD || 1) -
Number.parseFloat(
toTokens(b.quote.originAmount, b.originToken.decimals),
) *
(b.originToken.prices.USD || 1)
);
});
const sufficientBalanceQuotes = validTokenQuotes
.filter((s) => s.balance >= s.quote.originAmount)
.sort((a, b) => {
return (
Number.parseFloat(
toTokens(a.quote.originAmount, a.originToken.decimals),
) *
(a.originToken.prices.USD || 1) -
Number.parseFloat(
toTokens(b.quote.originAmount, b.originToken.decimals),
) *
(b.originToken.prices.USD || 1)
);
});
// Filter out quotes that are not included in the supportedTokens (if provided)
const tokensToInclude = supportedTokens
? Object.keys(supportedTokens).flatMap(
(c: string) =>
supportedTokens[Number(c)]?.map((t) => ({
chainId: Number(c),
address: t.address,
})) ?? [],
)
: [];
const finalQuotes = supportedTokens
? [...sufficientBalanceQuotes, ...insufficientBalanceQuotes].filter(
(q) =>
tokensToInclude.find(
(t) =>
t.chainId === q.originToken.chainId &&
t.address === q.originToken.address,
),
)
: [...sufficientBalanceQuotes, ...insufficientBalanceQuotes];
return finalQuotes;
},
queryKey: [
"payment-methods",
destinationToken.chainId,
destinationToken.address,
destinationAmount,
payerWallet?.getAccount()?.address,
includeDestinationToken,
supportedTokens,
], // 5 minutes
refetchOnWindowFocus: false,
staleTime: 5 * 60 * 1000,
});
return {
data: query.data || [],
error: query.error,
isError: query.isError,
isLoading: query.isLoading,
isSuccess: query.isSuccess,
refetch: query.refetch,
};
}