0

我创建了一个扩展 openzeppelin ERC20 的简单合约。我正在尝试将令牌从一个地址转移到另一个地址。

合约代码如下:

文件名:Token.sol

pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {
    uint256 public INITIAL_SUPPLY = 100000;

    constructor() ERC20("My Token", "MYT") {
        _mint(msg.sender, INITIAL_SUPPLY);
    }
}

测试文件中的代码:

const { expect } = require("chai");

describe("Send token from second address in the block", function () {

    it("Send 100 MYT to the third account", async function () {

        const Token = await ethers.getContractFactory("Token");
        const token = await Token.deploy();

        // get accounts from the network
        const [owner, secondAccount, thirdAccount] = await ethers.getSigners();

        // send some credit to the second account
        await token.transfer(secondAccount.address, 500);

        // Approve token transfer
        await token.approve(secondAccount.address, 200);

        // Transfer credit from second account to the third account (This step is not working)
        await token.transferFrom(secondAccount.address, thirdAccount.address, 100);
    });
});

收到错误:

     Error: VM Exception while processing transaction: reverted with reason string 'ERC20: transfer amount exceeds allowance'
      at Token.sub (@openzeppelin/contracts/math/SafeMath.sol:171)
      at Token.transferFrom (@openzeppelin/contracts/token/ERC20/ERC20.sol:154)
      at processTicksAndRejections (internal/process/task_queues.js:94:5)
      at runNextTicks (internal/process/task_queues.js:63:3)
      at listOnTimeout (internal/timers.js:501:9)
      at processTimers (internal/timers.js:475:7)
      at EthModule._estimateGasAction (node_modules/hardhat/src/internal/hardhat-network/provider/modules/eth.ts:421:9)
      at HardhatNetworkProvider.request (node_modules/hardhat/src/internal/hardhat-network/provider/provider.ts:105:18)
      at EthersProviderWrapper.send (node_modules/@nomiclabs/hardhat-ethers/src/internal/ethers-provider-wrapper.ts:13:20)

感谢您的帮助。

4

1 回答 1

3

如果您检查 Approve if erc20,则函数参数address _spender, uint256 _value应作为参数。在您的情况下,您批准secondAccount提取 200 个代币。

这意味着secondAccount可以将这些代币从token合约转移到他的账户。为此,您尝试await token.connect(secondAccount).transferFrom(token.address,secondAccount.address,100);

于 2021-07-14T18:53:44.097 回答