-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: [Sale Widget] Skip sending approve txn to wallet when allowance…
… balance is sufficient (#1627) Co-authored-by: Mimi Tran <[email protected]>
- Loading branch information
1 parent
003da5f
commit 65cd502
Showing
2 changed files
with
59 additions
and
5 deletions.
There are no files selected for viewing
48 changes: 48 additions & 0 deletions
48
packages/checkout/widgets-lib/src/widgets/sale/functions/signUtils.ts
This file contains 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,48 @@ | ||
import { BigNumber, ethers } from 'ethers'; | ||
import { Web3Provider } from '@ethersproject/providers'; | ||
|
||
import { SignedTransaction } from '../types'; | ||
|
||
export const filterAllowedTransactions = async ( | ||
transactions: SignedTransaction[], | ||
provider: Web3Provider, | ||
): Promise<SignedTransaction[]> => { | ||
try { | ||
const signer = provider.getSigner(); | ||
const signerAddress = await signer.getAddress(); | ||
const approveTxn = transactions.find((txn) => txn.methodCall.startsWith('approve')); | ||
|
||
if (!approveTxn || !signer || !signerAddress) { | ||
return transactions; | ||
} | ||
|
||
const contract = new ethers.Contract( | ||
approveTxn.tokenAddress, | ||
['function allowance(address,address) view returns (uint256)'], | ||
signer, | ||
); | ||
|
||
const allowance = await signer?.call({ | ||
to: approveTxn.tokenAddress, | ||
data: contract.interface.encodeFunctionData('allowance', [ | ||
signerAddress, | ||
approveTxn.params.spender, | ||
]), | ||
}); | ||
|
||
const currentAmount = BigNumber.from(allowance); | ||
const desiredAmount = approveTxn.params.amount ? BigNumber.from(approveTxn.params.amount) : BigNumber.from(0); | ||
|
||
const isAllowed = currentAmount.gte(BigNumber.from('0')) && currentAmount.gte(desiredAmount); | ||
|
||
if (isAllowed) { | ||
return transactions.filter((txn) => txn.methodCall !== approveTxn.methodCall); | ||
} | ||
} catch { | ||
/* Ignoring errors, as we don't need block wallet from | ||
* sending the approve when it's not possible to check the allowance | ||
*/ | ||
} | ||
|
||
return transactions; | ||
}; |
This file contains 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