soliditysmartcontractsweb3js

Approve token and transfer


Good afternoon, I can’t make a contract so that the user would approve in my contract and would allow spending tokens from contract2, after which the owner could send tokens from the wallet of the one who performed approve to another wallet

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface ERC20 {
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function approve(address spender, uint256 amount) external returns (bool);
}

contract TokenTransfer {
    address public tokenAddress;
    ERC20 public token;

    constructor(address _tokenAddress) {
        tokenAddress = _tokenAddress;
        token = ERC20(_tokenAddress);
    }

    function approveTokens(address spender, uint256 amount) external {
        require(token.approve(spender, amount), "Approval failed");
    }

    function transferTokens(address sender, address to, uint256 amount) external {
        require(token.transferFrom(sender, to, amount), "Transfer failed");
    }
}

help


Solution

  • By doing token.approve(spender, amount) the contract becomes the one who approves, not the user. You should have the user call the token contract directly with spender = your contract address.