I trying to using ERC20 token in another contract but I am stuck in this error "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."
I defined my token contract in this way:
> import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
> import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
> contract Points is ERC20, ERC20Permit {
> // Constructor
> // ...
> constructor() ERC20("MyToken", "MYT") ERC20Permit("MyToken") {
> _mint(msg.sender, 1000);
> }
>
> // Functions
> function decimals() public view virtual override returns (uint8) {
>
> return 10;
> }
And the another contract like this:
> contract myContract {
> IERC20 private hpContract;
> ......
> constructor(address token_address){
> service_owner = msg.sender;
> hpContract = ERC20(token_address);
> }
> .......
> function initialize() public {
>
> address from = msg.sender;
> // Get contract balance
> uint256 tokenBalance = hpContract .balanceOf(address(this));
>
> // Transfer al tokens
> hpContract.transferFrom(from, address(this), tokenBalance);
> }
> ....
This makes no sense at all.
You are attempting to transfer an amount equal to the contract balance, but you are attempting to do so from the sender to the contract, which means that by the end of that operation, the contract will have doubled its balance.
If it IS indeed what you're trying to achieve, then you need to execute the following transaction, using the same account which you are trying to execute the contract function with, and before you execute that function:
token.approve(myContract.address, token.balanceOf(myContract.address))
Where token
points to the ERC20 contract deployed at token_address
.
I am trying to transfer the 1000 token from ERC Contract to mycontract. I did the toke approve, calling to the function from REMIX (for testing purpose).
The ERC20 contract is just a ledger.
It holds a table which indicates how many tokens are entitled to each account, and it implements several functions which allow the caller to change the contents in that table.
For example, when contract ccc
executes token.transferFrom(x, y, n)
, where token
is an ERC20 contract, the following update takes place inside the token
contract:
table[x] = table[x] - n
table[y] = table[y] + n
If you allow everyone to execute this operation, then the token
contract becomes financially-worthless.
In order to keep it financially-meaningful, you must allow this operation to be executed only after the owner of account x
has executed a preliminary approval.
In the example above, the owner of account x
will need to:
- Sign the transaction
token.approve(ccc.address, n)
with the private key of account x
- Execute this transaction
- Execute the function in contract
ccc
which internally executes token.transferFrom(x, y, n)
I solved it, the problem was I was using wrong contract address for testing.
Thabk you.