繁体   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