Interactuar con el contrato a través de metamask (enviar TOKEN ERC20/TOKEN nativo/llamada de método) implementación de javascrpt

1. Primero introduzca la última versión de web3.js y luego introduzca jquery. Cuando encuentro un contrato con un archivo ABI, estoy acostumbrado a guardar el archivo ABI por separado. Léalo de forma remota a través de jquery.

Interactuar con el contrato directamente en la cadena después de instanciar el contrato

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

Después de activar el botón, el código se puede transferir.

 2. No hay ABI para interactuar con el contrato, porque algunos contratos son de código cerrado, por lo que construimos directamente el contenido del parámetro de datos manualmente, eliminando el paso de instanciar el contrato.

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. Los contratos de token estándar ERC20 generalmente implementan métodos estándar como transferencia / menta / transferencia de forma predeterminada, y los parámetros son los mismos, solo pruebe y llame directamente.

4. La transferencia de tokens nativos de blockchain es más fácil

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

Supongo que te gusta

Origin blog.csdn.net/meinaozi/article/details/123220109
Recomendado
Clasificación