i want my smart contract to accept erc20 token, so i used the approve function to approve some tokens to my smart contract, but when i check using the allowance function it returns zero
Hi, Can you share the code and test case?
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
contract weth {
IERC20Permit token;
constructor(address _token) public {
token = IERC20Permit(_token);
}
function deposit(uint _amount) public {
token.transferFrom(msg.sender, address(this), _amount);
}
function approve(uint _amount) public returns(bool){
return token.approve(address(this), _amount);
}
function allow(address _owner, address _spender) public view returns(uint){
return token.allowance(_owner, _spender);
}
function getBalance(address _address) public view returns(uint){
return token.balanceOf(_address);
}
}
the thing is when i call the approve function and i approve, let say 10 tokens for the contract to spend, when i call the allowance function to check its still return zero
first of all the user needs to call the approve function manually.
The spender is your contract.
After that your contract an initate the Transferfrom method.
can't the user approve through the function through the contract i created, i mean if they manually aprrove it, how do dex like uniswap work
No, because the token thinks that the contract wants to approve tokens to itself
You need to approve tokens on uniswap before trading
you dont understand me i have already approved some token to the contract, but i seems the approval function is not working
here's the approval function
it is working, it must be a problem from you.
can you publish your code?
IERC20Permit token;
constructor(address _token) public {
token = IERC20Permit(_token);
}
function deposit(uint _amount) public {
token.transferFrom(msg.sender, address(this), _amount);
}
function approve(uint _amount) public returns(bool){
return token.approve(address(this), _amount);
}
function allow(address _owner, address _spender) public view returns(uint){
return token.allowance(_owner, _spender);
}
function getBalance(address _address) public view returns(uint){
return token.balanceOf(_address);
}
and this me trying use transferFrom to deposit
function approve(uint _amount) public returns(bool){ return token.approve(address(this), _amount); }
that's the error.
what happens:
user call your contract. your contract calls token.
what should happen:
user calls token contract
The user need to approve manually
i understand now it's my contract that's calling token contract instead of user
yeah, thats right. Your user needs to call it directly