Skip to content

Handle token balance retrieval failures #7600

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/fallback-native-balance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"thirdweb": patch
---

Add fallback mechanism to usePaymentMethods hook for getOwnedTokens failures

When getOwnedTokens batches fail in the usePaymentMethods hook, the system now falls back to getting native token balances for each chain using getWalletBalance. This ensures users can still access their native tokens as payment methods even when the insight API is experiencing issues, providing a more resilient user experience.

The fallback mechanism:
- Catches getOwnedTokens failures and logs warnings
- Falls back to native balance fetching using getWalletBalance for each chain
- Transforms results to match the expected format
- Continues normal processing flow seamlessly
62 changes: 49 additions & 13 deletions packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
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";

Expand Down Expand Up @@ -80,16 +84,42 @@
const limit = 500;

while (true) {
const batch = await getOwnedTokens({
chains: insightEnabledChains.map((c) => getCachedChain(c.chainId)),
client,
ownerAddress: wallet.getAccount()?.address || "",
queryOptions: {
limit,
metadata: "false",
page,
},
});
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) {

Check warning on line 99 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L87-L99

Added lines #L87 - L99 were not covered by tests
// If the batch fails, fall back to getting native balance for each chain
console.warn(`Failed to get owned tokens for batch ${page}:`, error);

Check warning on line 101 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L101

Added line #L101 was not covered by tests

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;
}),
);

Check warning on line 115 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L103-L115

Added lines #L103 - L115 were not covered by tests

// 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);
}

Check warning on line 122 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L118-L122

Added lines #L118 - L122 were not covered by tests

if (batch.length === 0) {
break;
Expand Down Expand Up @@ -126,7 +156,9 @@

// Add destination token if included
if (includeDestinationToken) {
const tokenKey = `${destinationToken.chainId}-${destinationToken.address.toLowerCase()}`;
const tokenKey = `${
destinationToken.chainId
}-${destinationToken.address.toLowerCase()}`;

Check warning on line 161 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L159-L161

Added lines #L159 - L161 were not covered by tests
allValidOriginTokens.set(tokenKey, destinationToken);
}

Expand Down Expand Up @@ -155,7 +187,9 @@
) {
continue;
}
const tokenKey = `${route.originToken.chainId}-${route.originToken.address.toLowerCase()}`;
const tokenKey = `${
route.originToken.chainId
}-${route.originToken.address.toLowerCase()}`;

Check warning on line 192 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L190-L192

Added lines #L190 - L192 were not covered by tests
allValidOriginTokens.set(tokenKey, route.originToken);
}
} catch (error) {
Expand All @@ -169,7 +203,9 @@
const validOwnedTokens: OwnedTokenWithQuote[] = [];

for (const ownedToken of allOwnedTokens) {
const tokenKey = `${ownedToken.originToken.chainId}-${ownedToken.originToken.address.toLowerCase()}`;
const tokenKey = `${
ownedToken.originToken.chainId
}-${ownedToken.originToken.address.toLowerCase()}`;

Check warning on line 208 in packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts

View check run for this annotation

Codecov / codecov/patch

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts#L206-L208

Added lines #L206 - L208 were not covered by tests
const validOriginToken = allValidOriginTokens.get(tokenKey);

if (validOriginToken) {
Expand Down
Loading