Skip to content

Fix: Throw error if amount and gas is more than balance #7358

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

Merged
merged 1 commit into from
Jun 17, 2025

Conversation

gregfromstl
Copy link
Member

@gregfromstl gregfromstl commented Jun 17, 2025


PR-Codex overview

This PR focuses on fixing issues related to etherlink transfers, improving balance checks before transactions, and cleaning up test cases in the thirdweb codebase.

Detailed summary

  • Removed tests from useBridgeError.test.ts and usePaymentMethods.test.ts.
  • Updated transaction hash in Status.test.ts.
  • Modified return type in getWalletBalance function.
  • Enhanced useSendToken to include gas estimate and balance checks.
  • Cleaned up tests in paymentMachine.test.ts, removing unnecessary test cases.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features
    • Added pre-send balance validation for token transfers, ensuring users have enough funds to cover both the transfer amount and gas fees.
    • Introduced a maximum wait time for transaction confirmation to improve user experience.
  • Bug Fixes
    • Resolved issues with native token transfers failing when wallet funds are insufficient to cover gas costs.

@gregfromstl gregfromstl requested review from a team as code owners June 17, 2025 17:49
Copy link

changeset-bot bot commented Jun 17, 2025

🦋 Changeset detected

Latest commit: b6ba5bb

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
thirdweb Patch
@thirdweb-dev/wagmi-adapter Patch
nebula Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

"""

Walkthrough

The changes introduce pre-send validation in the token transfer logic to ensure the sender's balance covers both the transfer amount and estimated gas fees. The transaction confirmation waiting step now includes a maximum block wait time. Additionally, a redundant type alias was removed, and a function's return type was updated for clarity. A test suite for the useBridgeError hook was deleted. Minor test updates and removals were also made.

Changes

File(s) Change Summary
packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts Added balance and gas cost validation before sending tokens; limited transaction wait time.
packages/thirdweb/src/wallets/utils/getWalletBalance.ts Updated function return type annotation to GetBalanceResult; removed redundant type alias usage.
packages/thirdweb/src/react/core/hooks/useBridgeError.test.ts Deleted comprehensive test suite for useBridgeError hook.
.changeset/weak-papayas-occur.md Added patch fixing etherlink transfer failures when funds are low.
packages/thirdweb/src/bridge/Status.test.ts Updated hardcoded transaction hash in a test case.
packages/thirdweb/src/react/web/adapters/adapters.test.ts Removed test case checking error thrown on popup blocked scenario for WebWindowAdapter.open.
packages/thirdweb/src/react/core/machines/paymentMachine.test.ts Removed two test cases related to payment machine state transitions and quote clearing.
packages/thirdweb/src/react/core/hooks/usePaymentMethods.test.ts Deleted comprehensive test suite for usePaymentMethods hook.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant useSendToken
    participant getWalletBalance
    participant estimateGas
    participant sendTransaction

    User->>useSendToken: Initiate token transfer
    useSendToken->>getWalletBalance: Fetch wallet balance
    useSendToken->>estimateGas: Estimate gas for transfer
    useSendToken->>useSendToken: Check if (amount + gas) > balance
    alt Insufficient balance
        useSendToken-->>User: Throw insufficient balance error
    else Sufficient balance
        useSendToken->>sendTransaction: Send transaction
        sendTransaction-->>useSendToken: Return transaction
        useSendToken->>useSendToken: Wait for receipt (maxBlocksWaitTime=10,000)
        useSendToken-->>User: Return/send receipt
    end
Loading

Suggested reviewers

  • jnsdls
    """

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7b5b7ea and b6ba5bb.

📒 Files selected for processing (8)
  • .changeset/weak-papayas-occur.md (1 hunks)
  • packages/thirdweb/src/bridge/Status.test.ts (1 hunks)
  • packages/thirdweb/src/react/core/hooks/useBridgeError.test.ts (0 hunks)
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.test.ts (0 hunks)
  • packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts (4 hunks)
  • packages/thirdweb/src/react/core/machines/paymentMachine.test.ts (0 hunks)
  • packages/thirdweb/src/react/web/adapters/adapters.test.ts (0 hunks)
  • packages/thirdweb/src/wallets/utils/getWalletBalance.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • packages/thirdweb/src/react/web/adapters/adapters.test.ts
  • packages/thirdweb/src/react/core/machines/paymentMachine.test.ts
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.test.ts
  • packages/thirdweb/src/react/core/hooks/useBridgeError.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • .changeset/weak-papayas-occur.md
  • packages/thirdweb/src/bridge/Status.test.ts
  • packages/thirdweb/src/wallets/utils/getWalletBalance.ts
  • packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

graphite-app bot commented Jun 17, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels Jun 17, 2025
Copy link

vercel bot commented Jun 17, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm
login ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm
nebula ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 17, 2025 9:40pm

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts (2)

103-107: Redundant await before return

return await sendTransaction(…) adds no value here (the surrounding async already unwraps the
promise) and slightly obscures stack traces.

-return await sendTransaction({
+return sendTransaction({
   transaction: sendNativeTokenTx,
   account,
 });

122-125: Same redundant await as above

Consider dropping the extra await for consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b5941f and d9fc667.

📒 Files selected for processing (2)
  • packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts (4 hunks)
  • packages/thirdweb/src/wallets/utils/getWalletBalance.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/thirdweb/src/wallets/utils/getWalletBalance.ts (1)
packages/thirdweb/src/extensions/erc20/read/getBalance.ts (1)
  • GetBalanceResult (20-28)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
packages/thirdweb/src/wallets/utils/getWalletBalance.ts (1)

42-42: Confirm all call-sites were migrated after the return-type rename

getWalletBalance now returns Promise<GetBalanceResult> instead of the removed GetWalletBalanceResult.
Search the codebase for any residual references to the old alias to avoid compile/runtime errors.

#!/bin/bash
# Locate any lingering usages of the old type alias.
rg --type ts 'GetWalletBalanceResult'
packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts (1)

137-138: maxBlocksWaitTime of 10 000 ~= 33 h on Ethereum

Is such a long upper bound intentional? A smaller value (e.g. a few hundred blocks) usually suffices
and avoids keeping the UI in a pending state for a day.

Comment on lines +90 to 102
const gasEstimate = await estimateGas({
transaction: sendNativeTokenTx,
account,
});
const balance = await getWalletBalance({
address: account.address,
chain: activeChain,
client,
});
if (toWei(amount) + gasEstimate > balance.value) {
throw new Error("Insufficient balance for transfer amount and gas");
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Gas cost comparison is incorrect – estimateGas returns units, not wei

estimateGas (EVM eth_estimateGas) returns the gas LIMIT (≈ 21 000) – not the cost in wei.
Adding raw gas units to amountWei therefore under-estimates the required balance by
≈9 orders of magnitude and will allow transactions that still revert for “insufficient funds”.

At minimum multiply the gas units by an appropriate (max) fee per gas, or use a helper that already returns the total fee.

-const gasEstimate = await estimateGas({ transaction: sendNativeTokenTx, account });
-
-if (toWei(amount) + gasEstimate > balance.value) {
+const gasUnits = await estimateGas({ transaction: sendNativeTokenTx, account });
+const { maxFeePerGas } = await getFeeData({ client, chain: activeChain }); // or gasPrice
+const gasCost = gasUnits * maxFeePerGas;
+const amountWei = toWei(amount);
+
+if (amountWei + gasCost >= balance.value) {
   throw new Error("Insufficient balance for transfer amount and gas");
 }

Failing to fix this will surface as sporadic “intrinsic gas too low / insufficient funds” errors in production.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const gasEstimate = await estimateGas({
transaction: sendNativeTokenTx,
account,
});
const balance = await getWalletBalance({
address: account.address,
chain: activeChain,
client,
});
if (toWei(amount) + gasEstimate > balance.value) {
throw new Error("Insufficient balance for transfer amount and gas");
}
const gasUnits = await estimateGas({
transaction: sendNativeTokenTx,
account,
});
const { maxFeePerGas } = await getFeeData({
client,
chain: activeChain,
});
const gasCost = gasUnits * maxFeePerGas;
const amountWei = toWei(amount);
const balance = await getWalletBalance({
address: account.address,
chain: activeChain,
client,
});
if (amountWei + gasCost >= balance.value) {
throw new Error("Insufficient balance for transfer amount and gas");
}
🤖 Prompt for AI Agents
In packages/thirdweb/src/react/core/hooks/wallets/useSendToken.ts between lines
90 and 102, the code incorrectly adds the gas estimate (in gas units) directly
to the token amount in wei, underestimating the required balance. To fix this,
multiply the gas estimate by the current gas price or max fee per gas to convert
it to wei before adding it to the amount. This ensures the balance check
accounts for the actual gas cost in wei and prevents insufficient funds errors.

Copy link
Contributor

github-actions bot commented Jun 17, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 62.49 KB (0%) 1.3 s (0%) 220 ms (+181.15% 🔺) 1.5 s
thirdweb (cjs) 350.88 KB (0%) 7.1 s (0%) 651 ms (+6.93% 🔺) 7.7 s
thirdweb (minimal + tree-shaking) 5.7 KB (0%) 114 ms (0%) 105 ms (+2031.71% 🔺) 219 ms
thirdweb/chains (tree-shaking) 531 B (0%) 11 ms (0%) 47 ms (+2624.13% 🔺) 58 ms
thirdweb/react (minimal + tree-shaking) 19.59 KB (0%) 392 ms (0%) 85 ms (+595.1% 🔺) 476 ms

@gregfromstl gregfromstl force-pushed the greg/fix-trilitech-transfer branch from 2cf3a47 to 0553bb9 Compare June 17, 2025 19:03
@gregfromstl gregfromstl force-pushed the greg/fix-trilitech-transfer branch from 0553bb9 to 7b5b7ea Compare June 17, 2025 21:09
Copy link

codecov bot commented Jun 17, 2025

Codecov Report

Attention: Patch coverage is 16.66667% with 15 lines in your changes missing coverage. Please review.

Project coverage is 52.35%. Comparing base (3f74760) to head (b6ba5bb).
Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
...rdweb/src/react/core/hooks/wallets/useSendToken.ts 11.76% 15 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7358      +/-   ##
==========================================
- Coverage   55.58%   52.35%   -3.23%     
==========================================
  Files         909      939      +30     
  Lines       58683    63160    +4477     
  Branches     4163     4215      +52     
==========================================
+ Hits        32617    33070     +453     
- Misses      25959    29983    +4024     
  Partials      107      107              
Flag Coverage Δ
packages 52.35% <16.66%> (-3.23%) ⬇️
Files with missing lines Coverage Δ
...ges/thirdweb/src/wallets/utils/getWalletBalance.ts 100.00% <100.00%> (ø)
...rdweb/src/react/core/hooks/wallets/useSendToken.ts 21.15% <11.76%> (-1.32%) ⬇️

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gregfromstl gregfromstl merged commit 55baa99 into main Jun 17, 2025
23 of 25 checks passed
@gregfromstl gregfromstl deleted the greg/fix-trilitech-transfer branch June 17, 2025 21:39
@joaquim-verges joaquim-verges mentioned this pull request Jun 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
packages SDK Involves changes to the thirdweb SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant