如何使用MetaMaskAPI发送一些自定义令牌? [英] How to send some custom tokens with MetaMask API?

查看:56
本文介绍了如何使用MetaMaskAPI发送一些自定义令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MetaMASK文档页面上的示例代码似乎只发送ETH。我应该如何自定义示例代码以发送一些自定义令牌?

const transactionParameters = {
  nonce: '0x00', // ignored by MetaMask
  gasPrice: '0x09184e72a000', // customizable by user during MetaMask confirmation.
  gas: '0x2710', // customizable by user during MetaMask confirmation.
  to: '0x0000000000000000000000000000000000000000', // Required except during contract publications.
  from: ethereum.selectedAddress, // must match user's active address.
  value: '0x00', // Only required to send ether to the recipient from the initiating external account.
  data:
    '0x7f7465737432000000000000000000000000000000000000000000000000000000600057', // Optional, but used for defining smart contract creation and interaction.
  chainId: '0x3', // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
};

// txHash is a hex string
// As with any RPC call, it may throw an error
const txHash = await ethereum.request({
  method: 'eth_sendTransaction',
  params: [transactionParameters],
});

推荐答案

发送ERC-20令牌的事务需要将令牌合同作为接收方(to字段),data字段包含用于执行其transfer()功能的编码指令以及令牌接收方的地址和金额。

const transactionParameters = {
    from: accounts[0],
    to: tokenContractAddress,
    data: getDataFieldValue(tokenRecipientAddress, tokenAmount),
};
await ethereum.request({
    method: 'eth_sendTransaction',
    params: [transactionParameters],
});
例如,您可以使用web3js库(docs)来编码data字段值。transfer()函数是标准化的,因此假设令牌合同遵循该标准,则它对于任何令牌合同都是相同的。

function getDataFieldValue(tokenRecipientAddress, tokenAmount) {
    const web3 = new Web3();
    const TRANSFER_FUNCTION_ABI = {"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"};
    return web3.eth.abi.encodeFunctionCall(TRANSFER_FUNCTION_ABI, [
        tokenRecipientAddress,
        tokenAmount
    ]);
}

这篇关于如何使用MetaMaskAPI发送一些自定义令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆