my goal is to create a smart contract which user can deposit erc20 and withdraw erc20 token using.i tried to implement this functionality using token transfer and transferfrom functions tried to send tokens to contract address .but its showing some error. i tried all the possible solution available on internet but no luck .please help me out
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
interface IERC20
{
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract TestFunding
{
mapping(address => uint) public users;
address public owner;
uint public minimumDeposit;
uint public totalDeposit;
uint public noOfUsers;
constructor(){
owner = msg.sender;
}
function depositToken(address _token,uint _amount) public {
IERC20(_token).approve(address(this), _amount);
IERC20(_token).transferFrom(msg.sender,address(this),_amount);
}
function depositToken2(address _token,uint _amount) public {
IERC20(_token).transfer(address(this), _amount);
}
function getUserBalance() public view returns(uint)
{
return users[msg.sender];
}
function getCurrentBalance(address _token) public view returns(uint)
{
return IERC20(_token).balanceOf(address(this)) ;
}
function getTokenBalance(address _token,address _account) public view returns(uint)
{
return IERC20(_token).balanceOf(_account) ;
}
function withdrawToken(address _token,uint _amount) public
{
IERC20(_token).approve(msg.sender, _amount);
IERC20(_token).transferFrom(address(this),msg.sender,_amount);
}
}
when i tried to transfer using depositToken function error showing transact to TestFunding.depositToken errored: VM error: revert.
revert The transaction has been reverted to the initial state. Reason provided by the contract: "ERC20: transfer amount exceeds allowance". Debug the transaction to get more information.
when i tried to transfer using depositToken function error showing transact to TestFunding.depositToken2 errored: VM error: revert.
revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
transferFrom
ethereum.stackexchange.com/questions/46457/…. You have to be aware that a contract cannot call approve on behalf of their users, the users have to call approve before executing the contract. The famous two steps approve+transferFrom.