1

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?

1 Answer 1

0

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
2
  • Thank you for the answer. Is there a way I can do this with metamask? Dec 2, 2020 at 21:56
  • Yes. All DeFi services do it all day long. I suggest you try to use services like Uniswap, Aave and Synthetix before building your own services and see how tokens work. Dec 3, 2020 at 9:41

Your Answer

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

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