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

本文介绍了如何使用Web3.js库与智能合约进行交互,包括通过ABI文件实例化合约进行转账操作,以及在没有ABI时手动构造data参数进行函数调用。示例涵盖了ERC20代币转账和其他原生代币的交易过程。
摘要由CSDN通过智能技术生成

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);
        }
    });
    
});

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

 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);
    }
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值