Interact with the contract through metamask (send ERC20 TOKEN/native TOKEN/method call) javascrpt implementation

1. First introduce the latest version of web3.js, and then introduce jquery. When encountering a contract with an ABI file, I am used to saving the ABI file separately. Read it remotely through jquery.

Interact with the contract directly on the chain after instantiating the contract

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

After the button is triggered, the code can be transferred.

 2. There is no ABI to interact with the contract, because some contracts are closed source, so we directly construct the data parameter content manually, eliminating the step of instantiating the contract

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 standard token contracts generally implement standard methods such as transfer / mint / transfer by default, and the parameters are the same, just test and call directly.

4. Blockchain native token transfer is easier

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

Guess you like

Origin blog.csdn.net/meinaozi/article/details/123220109