簡體   English   中英

使用 ethers.js 調用 erc20 批准 function

[英]Call erc20 approve function using ethers.js

我正在使用 React JS 和 ethers.js 開發智能合約的前端。 智能合約有以下function。

function buyPremiumSpin(uint256 spins) external {
    require(spins > 0, "You can't get 0 premium spins!");
    uint256 cost = premiumSpinPrize * spins;
    require(wblock.balanceOf(msg.sender) >= cost, "Not enough WBLOCKS!");
    wblock.transferFrom(msg.sender, address(teamWallet), cost);
    premiumSpins[msg.sender] += spins;
}

我嘗試使用 function 調用

const signer = provider.getSigner();
const contract = new ethers.Contract(CONTRACT_ADDRESS, abi, signer);

const transaction = await contract.buyPremiumSpin(
    spins,
    {gasLimit: gasLimit}
);  

但交易失敗並顯示消息Fail with error 'ERC20: insufficient allowance'

經過一番研究,我發現在 erc20 中批准了 function。 該用戶必須批准一個地址才能讓他們轉移令牌。 但我無法使用 javascript 實現它。

我試過了

contract.approve(account, premiumSpinPrize, {gasLimit:gasLimit})

但由於 javascript 錯誤而失敗,因為approve不是 function。

執行智能合約 function 的正確方法是什么? 如果用戶可以批准最大金額,那將是很棒的,這樣他們就不必每次都批准它。

批准發生在 ERC20 智能合約上,以批准您的智能合約代表您使用代幣。 您只需要獲取令牌 ABI 並實例化令牌的合約實例,就像您在上面對合約所做的那樣;)

var tokenContract = new ethers.Contract(tokenAddress, tokenABI, provider);
tokenContract.approve(<Your_Contract_Address>, amount, {gasLimit: gasLimit})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM