通过metamask与合约交互(发送ERC20 TOKEN/原生TOKEN/方法调用) javascrpt实现

1. 首先引入web3.js最新版本 ,再引入 jquery 遇到合约有ABI文件.个人习惯单独保存ABI文件.通过jquery远程读取.

实例化合约后直接在链上与合约交互

$.getJSON('ABI文件.json',function(result){
    let MyContract = new web3.eth.Contract(result,'TOKEN合约地址');
    let data = MyContract.methods.transfer('收币人地址',web3.utils.toWei('转账金额','ether')).encodeABI();
    const transactionParameters = {
        //   nonce: '0x00', // ignored by MetaMask
        gasPrice: web3.utils.toHex(web3.utils.toWei('5','gwei')),
        //   gas: '0x2710', // customizable by user during MetaMask confirmation.
        to: 'TOKEN合约地址', // Required except during contract publications.
        from: ethereum.selectedAddress, // must match user's active address.
        // value: web3.utils.toHex('12'), // Only required to send ether to the recipient from the initiating external account.
        data: data, // Optional, but used for defining smart contract creation and interaction.
        chainId: web3.utils.toHex('56'), // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
    };
    ethereum.request({
      method: 'eth_sendTransaction',
      params: [transactionParameters],
    })
    .then(function(result){
        //result是生成的交易hash值,用于在链上查看交易状态信息的索引
        successMessage(JSON.stringify(result))
    })
    .catch(function(reason){
        if(reason.code == 4001){
            errorMessage(reason.message);
        }else{
            console.log(reason);
        }
    });
    
});

通过按钮什么的触发后就可以通过代码转账了.

通过metamask与合约交互(发送ERC20 TOKEN/原生TOKEN/方法调用) javascrpt实现_第1张图片

 2. 无ABI与合约交互,因为有的合约闭源了,所以我们直接手工构造data参数内容,免去了实例化合约的步骤

let data = web3.eth.abi.encodeFunctionCall({
	name: 'rent',
	type: 'function',
	inputs: [{
	    type: 'uint256',
	    name: 'orderId'
	},{
	    type: 'address',
	    name: 'nftAddress'
	},{
	    type: 'address',
	    name: 'tokenOwner'
	},{
	    type: 'uint256[]',
	    name: 'rentInfo'
	},{
	    type: 'address[]',
	    name: 'inviters'
	},{
	    type: 'address[]',
	    name: 'agents'
	},{
	    type: 'uint256',
	    name: 'deadline'
	},{
	    type: 'bytes',
	    name: 'signature'
	}]
	}, [order_id.toString(), nft_address,token_owner,[token_id,expire_at,web3.utils.toBN(price)],[],[],deadline,'0x'+signature]);

const transactionParameters = {
//   nonce: '0x00', // ignored by MetaMask
gasPrice: web3.utils.toHex(web3.utils.toWei('5','gwei')),
//   gas: '0x2710', // customizable by user during MetaMask confirmation.
to: '合约地址', // 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: data, // Optional, but used for defining smart contract creation and interaction.
//   chainId: '有需要就用web.utils.toHex("NETWORK十进制ID")', // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
};
ethereum.request({
	method: 'eth_sendTransaction',
	params: [transactionParameters],
})
.then(function(result){
	//result是生成的交易hash值,用于在链上查看交易状态信息的索引
	successMessage(JSON.stringify(result))
})
.catch(function(reason){
	console.log('eth_sendTransaction info');
	console.log(reason);
});

3. ERC20标准代币合约一般默认实现了transfer / mint / transfer 等等标准方法,参数也一样,直接测试调用就行了.

4. 区块链原生代币转账更加简单

const transactionParameters = {
    //   nonce: '0x00', // ignored by MetaMask
    gasPrice: web3.utils.toHex(web3.utils.toWei('5','gwei')),
    //   gas: '0x2710', // customizable by user during MetaMask confirmation.
    to: '收款人钱包地址', // Required except during contract publications.
    from: ethereum.selectedAddress, // must match user's active address.
    value: web3.utils.toHex(web3.utils.toWei('转账数量','ether')), // Only required to send ether to the recipient from the initiating external account.
    chainId: web3.utils.toHex('56'), // Used to prevent transaction reuse across blockchains. Auto-filled by MetaMask.
};
ethereum.request({
  method: 'eth_sendTransaction',
  params: [transactionParameters],
})
.then(function(result){
    successMessage(JSON.stringify(result))
})
.catch(function(reason){
    if(reason.code == 4001){
        errorMessage(reason.message);
    }else{
        console.log(reason);
    }
});

你可能感兴趣的