Hello,
I have two separate contracts, one for the ERC20 token and another one to accept the ERC20 token. I am using the approve() and then transferFrom() method to first approve an allowance and then transfer the ERC20 tokens to the contract address but the allowance doesn't seem to be getting allocated to the contract for some reason. Here is the code:
ERC20 Token Contract
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title SimpleToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `ERC20` functions.
* Based on https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/examples/SimpleToken.sol
*/
contract SimpleToken is ERC20 {
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor(
string memory name,
string memory symbol,
uint256 initialSupply
) public ERC20(name, symbol) {
_mint(msg.sender, initialSupply);
}
}
Contract to receive ERC20 tokens
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
// Contract that uses any ERC20 token
contract UsingERC20 {
IERC20 public associatedToken;
// Constructor. Pass it the token you want this contract to work with
constructor(IERC20 _token) public {
associatedToken = _token;
}
function approveContract() public {
associatedToken.approve(address(this), 100000000000000000000000);
}
function doSomethingThatRequiresERC20tokens() public {
associatedToken.transferFrom(msg.sender, address(this), 100000000000000000000000);
// Ok, now the tokens are transferred successfully, let's do some cool stuff!
// emit YayIReceivedTokens(100, msg.sender, associatedToken.balanceOf(address(this)));
}
function getContractAllowance() public view returns (uint256) {
uint256 _tmpa;
_tmpa = associatedToken.allowance(msg.sender, address(this));
return _tmpa;
}
function getContractBalance() public view returns (uint256) {
uint256 _balc;
_balc = associatedToken.balanceOf(address(this));
return _balc;
}
function getUserBalance() public view returns (uint256) {
uint256 _balc2;
_balc2 = associatedToken.balanceOf(msg.sender);
return _balc2;
}
// event YayIReceivedTokens(uint256 amount, address fromAccount, uint256 totalBalance);
}
I am executing the approveContract() function to allocate allowance to the contract, and then checking the allocated allowance using getContractAllowance() function, but the allowance stays 0 even after executing the approveContract() function. And off course, if I try executing doSomethingThatRequiresERC20tokens() function it reverts with "ERC20: transfer amount exceeds allowance".