2

I read a lot of documentation in here and another web pages, I have a question and I so tried to solved but nothing works for me.

I am using this example.

It works fine with truffle, but I don't know what I need to do to make this work fine using metamask.

The problem is the next:

  • Create a ERC20 Token // works
  • Import the IRC20 Token Contract to Another Contract Named "TokenReceiver" // I think I do correctly, I only copy and paste to test in remix ethereum.
  • Deploy, Use doStuff function into the new Contract "TokenReceiver" // Error here

The error says:

Gas estimation errored with the following message (see below). The transaction execution will likely fail. Do you want to force sending? gas required exceeds allowance (10000000) or always failing transaction

The code is the same:

pragma solidity ^0.5.0;

import "./IERC20.sol";

/**
 * @title TokenReceiver
 * @dev Very simple example of a contract receiving ERC20 tokens.
 */
contract TokenReceiver {

    IERC20 private _token;

    event DoneStuff(address from);

    /**
     * @dev Constructor sets token that can be received
     */
    constructor (IERC20 token) public {
        _token = token;
    }

    /**
     * @dev Do stuff, requires tokens
     */
    function doStuff() external {

        address from = msg.sender;

        _token.transferFrom(from, address(this), 1000);

        emit DoneStuff(from);

    }
}

I read a lot but I really know I am doing something wrong but I don't know what it is, reading I see that I need to approve the function before using transfer, but nothing works for me, I am trying do this and the error is the same and I don't see the approve window with metamask:

function doStuff() external {

    address from = msg.sender;

    _token.approve(from,1000); // i trying adding this line

    _token.transferFrom(from, address(this), 1000);

    emit DoneStuff(from);

}

Somebody help me please, it is hard for me to understand what's happening but I really want to know what I am doing wrong.

1
  • does your "from" has 1000 tokens to approve? And why are you adding this line? it does not make sense "approving my self and send my token" :/
    – Majd TL
    Commented Jan 28, 2020 at 13:36

2 Answers 2

1

First of all, get rid of this (executed inside your TokenReceiver contract):

address from = msg.sender;
_token.approve(from,1000);

It allows msg.sender to transfer tokens from your contract, and not the other way round as you would hope (and it's not something that you should hope for anyway, because if that was the case then anyone could steal your tokens at will).


Second, before calling your doStuff function, you need to execute the following transaction outside your contract (e.g., using Remix, MyEtherWallet, Web3.js, Web3.py, etc):

_token.approve(yourTokenReceiverContractAddress,1000);

And you need to execute this transaction using the account which you are using for your other actions (contract deployment, etc).

3
  • thanks a lot for the answer, the problem is now solved <3
    – Kypanz
    Commented Mar 10, 2020 at 0:26
  • @Kypanz: How about accepting the answer then? Commented Mar 10, 2020 at 6:29
  • In whole internet i cant find full example of erc20 trnsaction. I am looking for simple transaction from to. Commented Mar 31, 2022 at 10:46
0

Here's a simplified example of an ERC20 token transfer using web3.js:

const Web3 = require('web3');

// Connect to an Ethereum node
const web3 = new Web3('https://mainnet.infura.io/v3/your-infura-project-id');

// Set the contract address and ABI of the ERC20 token
const contractAddress = '0x...'; // Replace with the actual contract address
const contractABI = [ /* Replace with the actual contract ABI */ ];

// Create an instance of the ERC20 token contract
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Set your account address and private key
const fromAddress = '0x...'; // Replace with your account address
const privateKey = 'your-private-key'; // Replace with your private key

// Set the recipient address and the amount to transfer
const toAddress = '0x...'; // Replace with the recipient's address
const amount = '1000000000000000000'; // Replace with the amount to transfer (in Wei)

(async () => {
  try {
    // Get the account nonce
    const nonce = await web3.eth.getTransactionCount(fromAddress);

    // Build the transaction object
    const txObject = {
      from: fromAddress,
      to: contractAddress,
      nonce: web3.utils.toHex(nonce),
      gasLimit: web3.utils.toHex(210000),
      gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
      data: contract.methods.transfer(toAddress, amount).encodeABI()
    };

    // Sign the transaction
    const signedTx = await web3.eth.accounts.signTransaction(txObject, privateKey);

    // Send the signed transaction
    const txReceipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

    console.log('Transaction hash:', txReceipt.transactionHash);
    console.log('Transaction successful!');
  } catch (error) {
    console.error('Error:', error);
  }
})();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.