-
Notifications
You must be signed in to change notification settings - Fork 528
feat: USDT approve(0) reset flow for Ethereum mainnet swap #1925
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
piatoss3612
wants to merge
8
commits into
develop
Choose a base branch
from
rowan/KEPLR-1992
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 7 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
311dfc6
Add ERC20 allowance query functionality
piatoss3612 2f6f790
Add USDT allowance reset feature
piatoss3612 e8f3790
Enhance USDT allowance reset functionality in IBC swap
piatoss3612 6b491f9
fix: scope USDT approve reset to input token and recover stuck pendin…
piatoss3612 c3a53e9
fix: refresh allowance after swap tx and hide redundant approval indi…
piatoss3612 398629c
fix: notify user when approve(0) tx preparation fails
piatoss3612 896ae43
fix: clear cached spender when new quote needs no approval
piatoss3612 8a6e0d4
fix: suppress reset failure toast when user cancels signing
piatoss3612 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
308 changes: 308 additions & 0 deletions
308
apps/extension/src/pages/ibc-swap/components/usdt-allowance-reset/index.tsx
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
227 changes: 227 additions & 0 deletions
227
apps/extension/src/pages/ibc-swap/hooks/use-usdt-approval-reset.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,227 @@ | ||
| import React from "react"; | ||
| import { AppCurrency } from "@keplr-wallet/types"; | ||
| import { | ||
| EthereumAccountStore, | ||
| EthereumQueries, | ||
| UnsignedEVMTransactionWithErc20Approvals, | ||
| isApproveResetRequired, | ||
| } from "@keplr-wallet/stores-eth"; | ||
| import { SwapAmountConfig } from "@keplr-wallet/hooks-internal"; | ||
| import { IFeeConfig, IGasSimulator, ISenderConfig } from "@keplr-wallet/hooks"; | ||
| import { Dec } from "@keplr-wallet/unit"; | ||
| import { isEVMFeeConfig } from "../../../hooks/fee"; | ||
| import { IBCSwapConfig } from "../../../stores/ui-config/ibc-swap"; | ||
|
|
||
| export function useUsdtApprovalReset({ | ||
| amountConfig, | ||
| senderConfig, | ||
| inChainId, | ||
| inCurrency, | ||
| queriesStore, | ||
| ethereumAccountStore, | ||
| feeConfig, | ||
| gasSimulator, | ||
| ibcSwapConfig, | ||
| onSignComplete, | ||
| onResetSuccess, | ||
| onResetFailed, | ||
| }: { | ||
| amountConfig: SwapAmountConfig; | ||
| senderConfig: ISenderConfig; | ||
| inChainId: string; | ||
| inCurrency: AppCurrency; | ||
| queriesStore: { | ||
| get(chainId: string): EthereumQueries; | ||
| }; | ||
| ethereumAccountStore: EthereumAccountStore; | ||
| feeConfig: IFeeConfig; | ||
| gasSimulator: IGasSimulator; | ||
| ibcSwapConfig: IBCSwapConfig; | ||
| onSignComplete: () => void; | ||
| onResetSuccess: () => void; | ||
| onResetFailed: () => void; | ||
| }) { | ||
| const isApprovalResetPending = ibcSwapConfig.isApprovalResetPending; | ||
| const setIsApprovalResetPending = (pending: boolean) => | ||
| ibcSwapConfig.setIsApprovalResetPending(pending); | ||
|
|
||
| // Detect USDT from swap inputs (not getTxsIfReady) to avoid flicker | ||
| const usdtContractAddress = inCurrency.coinMinimalDenom.startsWith("erc20:") | ||
| ? inCurrency.coinMinimalDenom.replace("erc20:", "") | ||
| : undefined; | ||
| const isInputUsdtRequiringReset = | ||
| usdtContractAddress != null && | ||
| isApproveResetRequired(inChainId, usdtContractAddress); | ||
|
|
||
| // Cache the spender from tx data — survives getTxsIfReady() returning null during route transitions | ||
| const approvalSpenderRef = React.useRef<string | null>(null); | ||
| const txs = amountConfig.getTxsIfReady(); | ||
| if (txs && txs.length > 0) { | ||
| const tx = txs[0]; | ||
| if ("requiredErc20Approvals" in tx) { | ||
| const approval = (tx as UnsignedEVMTransactionWithErc20Approvals) | ||
| .requiredErc20Approvals?.[0]; | ||
| // Clear stale spender when the new quote no longer needs an approval | ||
| // (e.g., user lowered amount below existing allowance). | ||
| approvalSpenderRef.current = approval?.spender ?? null; | ||
| } | ||
| } | ||
|
|
||
| const sender = senderConfig.sender; | ||
| const allowanceQuery = | ||
| isInputUsdtRequiringReset && | ||
| sender && | ||
| usdtContractAddress && | ||
| approvalSpenderRef.current | ||
| ? queriesStore | ||
| .get(inChainId) | ||
| .ethereum.queryERC20Allowance.getAllowance( | ||
| usdtContractAddress, | ||
| sender, | ||
| approvalSpenderRef.current | ||
| ) | ||
| : null; | ||
|
|
||
| const hasValidAmount = (() => { | ||
| try { | ||
| const amount = amountConfig.amount[0]?.toCoin().amount; | ||
| return amount != null && amount !== "0"; | ||
| } catch { | ||
| return false; | ||
| } | ||
| })(); | ||
|
|
||
| const requiresApprovalReset = | ||
| hasValidAmount && | ||
| isInputUsdtRequiringReset && | ||
| (isApprovalResetPending || | ||
| (allowanceQuery != null && allowanceQuery.allowance > BigInt(0))); | ||
|
piatoss3612 marked this conversation as resolved.
|
||
|
|
||
| // P2 fallback: if pending flag is stuck after tx fulfill callback missed, | ||
| // clear it once on-chain allowance confirms the reset succeeded. | ||
| React.useEffect(() => { | ||
| if ( | ||
| isApprovalResetPending && | ||
| allowanceQuery != null && | ||
| !allowanceQuery.isFetching && | ||
| allowanceQuery.allowance === BigInt(0) | ||
| ) { | ||
| setIsApprovalResetPending(false); | ||
| } | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [ | ||
| isApprovalResetPending, | ||
| allowanceQuery?.allowance, | ||
| allowanceQuery?.isFetching, | ||
| ]); | ||
|
|
||
| const handleResetAllowance = async () => { | ||
| const txs = amountConfig.getTxsIfReady(); | ||
| if (!txs || txs.length === 0) return; | ||
|
|
||
| const tx = txs[0]; | ||
| if (!("requiredErc20Approvals" in tx)) return; | ||
|
|
||
| const approval = (tx as UnsignedEVMTransactionWithErc20Approvals) | ||
| .requiredErc20Approvals?.[0]; | ||
| if (!approval) return; | ||
|
|
||
| const chainId = `eip155:${tx.chainId!}`; | ||
| const ethereumAccount = ethereumAccountStore.getAccount(chainId); | ||
|
|
||
| const isInCurrencyErc20 = | ||
| ("type" in inCurrency && inCurrency.type === "erc20") || | ||
| inCurrency.coinMinimalDenom.startsWith("erc20:"); | ||
| if (!isInCurrencyErc20) return; | ||
|
|
||
| const resetTx = ethereumAccount.makeErc20ApprovalTx( | ||
| { | ||
| ...inCurrency, | ||
| type: "erc20", | ||
| contractAddress: inCurrency.coinMinimalDenom.replace("erc20:", ""), | ||
| }, | ||
| approval.spender, | ||
| "0" | ||
| ); | ||
|
|
||
| setIsApprovalResetPending(true); | ||
|
|
||
| try { | ||
| // Simulate gas for the approve(0) tx | ||
| const gasResult = await ethereumAccount.simulateGas(sender, resetTx); | ||
| const gasLimit = Math.ceil( | ||
| gasResult.gasUsed * gasSimulator.gasAdjustment | ||
| ); | ||
|
|
||
| // Build fee object | ||
| let feeObject: Record<string, unknown>; | ||
| if (isEVMFeeConfig(feeConfig)) { | ||
| const eip1559Fees = feeConfig.getEIP1559TxFees(feeConfig.type); | ||
| if (eip1559Fees.maxFeePerGas && eip1559Fees.maxPriorityFeePerGas) { | ||
| feeObject = { | ||
| type: 2, | ||
| maxFeePerGas: `0x${BigInt( | ||
| eip1559Fees.maxFeePerGas.truncate().toString() | ||
| ).toString(16)}`, | ||
| maxPriorityFeePerGas: `0x${BigInt( | ||
| eip1559Fees.maxPriorityFeePerGas.truncate().toString() | ||
| ).toString(16)}`, | ||
| gasLimit: `0x${gasLimit.toString(16)}`, | ||
| }; | ||
| } else { | ||
| feeObject = { | ||
| gasPrice: `0x${BigInt( | ||
| (eip1559Fees.gasPrice ?? new Dec(0)).truncate().toString() | ||
| ).toString(16)}`, | ||
| gasLimit: `0x${gasLimit.toString(16)}`, | ||
| }; | ||
| } | ||
| } else { | ||
| feeObject = { | ||
| gasLimit: `0x${gasLimit.toString(16)}`, | ||
| }; | ||
| } | ||
|
|
||
| await ethereumAccount.sendEthereumTx( | ||
| sender, | ||
| { ...resetTx, ...feeObject }, | ||
| { | ||
| onBroadcastFailed: () => { | ||
| setIsApprovalResetPending(false); | ||
| onSignComplete(); | ||
| }, | ||
| onBroadcasted: () => { | ||
| onSignComplete(); | ||
| }, | ||
|
piatoss3612 marked this conversation as resolved.
|
||
| onFulfill: (txReceipt) => { | ||
|
piatoss3612 marked this conversation as resolved.
|
||
| if (txReceipt.status === "0x1") { | ||
| if (allowanceQuery) { | ||
| allowanceQuery.fetch(); | ||
| } | ||
| onResetSuccess(); | ||
| } else { | ||
| onResetFailed(); | ||
| } | ||
| setIsApprovalResetPending(false); | ||
| }, | ||
| } | ||
| ); | ||
| } catch { | ||
| setIsApprovalResetPending(false); | ||
|
piatoss3612 marked this conversation as resolved.
Outdated
|
||
| onResetFailed(); | ||
|
piatoss3612 marked this conversation as resolved.
Outdated
|
||
| } | ||
| }; | ||
|
|
||
| const refetchAllowance = () => { | ||
| if (allowanceQuery) { | ||
| allowanceQuery.fetch(); | ||
| } | ||
| }; | ||
|
|
||
| return { | ||
| requiresApprovalReset, | ||
| isApprovalResetPending, | ||
| handleResetAllowance, | ||
| refetchAllowance, | ||
| }; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.