From ff672fe2e3e79623abdb7e2fdfc8f24e49659e77 Mon Sep 17 00:00:00 2001 From: 0xFirekeeper <0xFirekeeper@gmail.com> Date: Thu, 28 Mar 2024 06:24:44 +0300 Subject: [PATCH] [Pay] check allowance before asking to approve --- .../Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs b/Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs index 69a4ef47..a7d3976b 100644 --- a/Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs +++ b/Assets/Thirdweb/Core/Scripts/Pay/ThirdwebPay.BuyWithCrypto.cs @@ -1,3 +1,4 @@ +using System.Numerics; using System.Threading.Tasks; namespace Thirdweb.Pay @@ -18,8 +19,16 @@ public static async Task BuyWithCrypto(BuyWithCryptoQuoteResult buyWithC { ThirdwebDebug.Log("Approving ERC20..."); var erc20ToApprove = sdk.GetContract(buyWithCryptoQuote.Approval.TokenAddress); - var approvalRes = await erc20ToApprove.ERC20.SetAllowance(buyWithCryptoQuote.Approval.SpenderAddress, buyWithCryptoQuote.Approval.AmountWei.ToEth()); - ThirdwebDebug.Log($"Approval transaction receipt: {approvalRes}"); + var currentAllowance = await erc20ToApprove.ERC20.Allowance(buyWithCryptoQuote.Approval.SpenderAddress); + if (BigInteger.Parse(currentAllowance.value) >= BigInteger.Parse(buyWithCryptoQuote.Approval.AmountWei)) + { + ThirdwebDebug.Log("Already approved"); + } + else + { + var approvalRes = await erc20ToApprove.ERC20.SetAllowance(buyWithCryptoQuote.Approval.SpenderAddress, buyWithCryptoQuote.Approval.AmountWei.ToEth()); + ThirdwebDebug.Log($"Approval transaction receipt: {approvalRes}"); + } } ThirdwebDebug.Log("Sending swap transaction...");