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

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

 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
    评论
要使用web3js通过eth_sign方法实现ERC20授权,需要以下步骤: 1. 首先,确保用户已经连接到以太坊网络,并且已经解锁了他们的以太坊钱包。这可以通过调用web3.eth.getAccounts()方法来完成,如果返回一个非空数组,则表示用户已经连接并解锁了他们的钱包。 2. 然后,需要获取代币合约的实例。可以使用web3.eth.Contract()方法来创建代币合约实例,需要传递代币合约的ABI和地址。 3. 然后,需要调用代币合约的approve()方法,传递授权的数量和授权的接收者地址。这将生成一个待签名的消息,需要使用eth_sign()方法对其进行签名。 4. 最后,使用eth_sign()方法对待签名的消息进行签名。eth_sign()方法需要传递三个参数:用户的以太坊地址,待签名的消息和一个回调函数,该回调函数将在签名完成后被调用。 以下是一个示例代码,可以作为参考: ```javascript // 获取用户的以太坊地址 let accounts = await web3.eth.getAccounts(); let userAddress = accounts[0]; // 创建代币合约实例 let tokenContract = new web3.eth.Contract(tokenAbi, tokenAddress); // 调用approve()方法,生成待签名的消息 let approveMessage = tokenContract.methods.approve(spenderAddress, amount).encodeABI(); // 使用eth_sign()方法签名消息 web3.eth.personal.sign(approveMessage, userAddress, function (error, signature) { if (error) { console.error(error); } else { // 签名成功,将签名结果发送到服务器进行验证 console.log(signature); } }); ``` 在实际使用中,需要将签名结果发送到服务器进行验证,以确保签名的消息和签名结果都有效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值