Contract-Development
如何使用 web3Js(>=1.0 版)將參數傳遞給合約建構子
我在https://www.myetherwallet.com/#contracts上,想部署一份合約。
它與帶有沒有參數的建構子的契約一起使用,但我的契約建構子如下所示:
function CrowdFunding(address _arg1, uint256 _arg2, uint256 _arg3) public { arg1 = _arg1; arg2 = _arg2; arg3 = _arg3; }
但是如何傳遞我的論點(arg1、arg2 和 arg3)?我正在使用 web3JS。
如果您使用的是較新版本的 web3(例如 1.0.0 版):
// example solidity code function ContractName(address _arg1, uint256 _arg2, uint256 _arg3) public { arg1 = _arg1; arg2 = _arg2; arg3 = _arg3; }
使用**web3.eth.abi.encodeParameter()或web3.eth.abi.encodeParameters()**對參數進行編碼並將它們連接到字節碼的末尾。
const Web3 = require("web3"); const solc = require("solc"); // compile the solidity code let compiled = solc.compile(source); // save public interface of contract let abi = JSON.parse(compiled.contracts[":ContractName"].interface) // create var with contract let CrowdFunding = new web3.eth.Contract(abi); let bytecodeWithParameters = compiled.contracts[':ContractName'].bytecode + web3.eth.abi.encodeParameters(['address', 'uint256', 'uint256'], ['0x08cf02070bb9f167556c677da58e6678bbe871fc', '100000000000000000', '10000']).slice(2); // slice(2) because we want to remove the '0x' at the beginning.
現在,您可以在https://www.myetherwallet.com/#contracts上輸入bytecodeWithParameters進行部署(帶參數)。
試試這個:
let fs = require("fs"); let Web3 = require("web3"); let web3 = new Web3(NODE_ADDRESS); async function send(transaction) { let gas = await transaction.estimateGas({from: PUBLIC_KEY}); let options = { to : transaction._parent._address, data: transaction.encodeABI(), gas : gas }; let signedTransaction = await web3.eth.accounts.signTransaction(options, PRIVATE_KEY); return await web3.eth.sendSignedTransaction(signedTransaction.rawTransaction); } async function deploy(contractName, contractArgs) { let abi = fs.readFileSync(contractName + ".abi").toString(); let bin = fs.readFileSync(contractName + ".bin").toString(); let contract = new web3.eth.Contract(JSON.parse(abi)); let handle = await send(contract.deploy({data: "0x" + bin, arguments: contractArgs})); console.log(`${contractName} contract deployed at address ${handle.contractAddress}`); return new web3.eth.Contract(JSON.parse(abi), handle.contractAddress); }
使用範例:
let crowdFunding = await deploy("CrowdFunding", [arg1, arg2, arg3]);