Metamask Transactions – Send Tokens with Metamask and Custom Data Using sendTransaction

erc-20ethers.jsmetamaskweb3js

My question is similar to How to use sendTransaction to send ERC20 tokens through Metamask?. I have a contract, and currently I send a transaction to this contract through Metamask with this code:

var abiInterface = new ethers.utils.Interface(this.abi);
var functionData = abiInterface.encodeFunctionData('myFunction', [type, level]);
const transactionParameters = {
  nonce: '0x00', // ignored by MetaMask
  gasPrice: ethers.utils.hexlify(ethers.utils.parseEther(GlobalConstants.gasPrice)), // customizable by user during MetaMask confirmation.
  gas: GlobalConstants.gas, // customizable by user during MetaMask confirmation.
  to: this.contractAddress, // Required except during contract publications.
  from: ethereum.selectedAddress, // must match user's active address.
  value: ethers.utils.hexlify(ethers.utils.parseEther(price.toString())), // Only required to send ether to the recipient from the initiating external account.
  data: functionData, // Optional, but used for defining smart contract creation and interaction.
  chainId: GlobalConstants.chain, // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
}
const txHash = await ethereum.request({
    method: 'eth_sendTransaction',
    params: [transactionParameters],
  });

Now I want to send the transaction from a custom token, and according the response from Hamza Ahmed in question link above, to do it I need to remove the parameter 'value' and send some like this

contractInstance.transfer.getData(address, amount); 

in the 'data' parameter.

The problem is I need to send this

abiInterface.encodeFunctionData('myPayableFunction', [type, level]);

in the data parameter, to interact with a function in my contract.

So the question is, how can I send tokens together with the custom data to interact with the contract function?

Best Answer

ERC-20 does not support sending tokens with custom data. For that you need a different token standard.

What ERC-20 offers is two transaction pattern

  • User does approve() to allow a smart contract to spend tokens
  • User makes a transaction against a smart contract function with custom data as a parameter
  • Smart contract executes transferFrom() from user account
Related Topic