Web3js

將地址、數據和氣體分配給智能合約以使用 Node-js 進行部署

  • May 22, 2021

我使用本指南使用 Node-js 部署智能合約。就我的契約被創建為一個對象而言,我遵循了這一點。因為提到的指南是舊的,現在一些 web3 方法發生了變化。所以看起來我無法繼續關注。我的問題是“我如何將地址、數據和氣體分配給我的契約對像以進行部署?”。請用適當的程式碼指導我部署契約。

應用程序.js:

var Web3=require('web3');
var fs=require('fs');
var solc=require('solc');
var web3=new Web3('ws://127.0.0.1:8545');
var address="0xdC3881248306fd62bbA5d9F0FDD39b5693bd1737";
var contractAbi=[
   {
       "constant": true,
       "inputs": [],
       "name": "notation",
       "outputs": [
           {
               "internalType": "string",
               "name": "",
               "type": "string"
           }
       ],
       "payable": false,
       "stateMutability": "pure",
       "type": "function"
   }
];
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
for (let contractName in contract_compiled.contracts) {
var contract_byteCode=contract_compiled.contracts[contractName].bytecode;
}
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var contract_object=new web3.eth.Contract(contractAbi);

只需在問題程式碼的末尾添加以下程式碼:

contract_object.deploy().send({from:<...>, gas:<...>, gasPrice:<...>});

我建議您閱讀以下文件以清除語法:

https://web3js.readthedocs.io/en/v1.2.7/web3-eth-contract.html

假設你已經編譯了合約,並且它的 abi 和字節碼分別在文件<ContractName>.abi<ContractName>.bin,你可以使用這個腳本(web3 v1.2.1):

const fs   = require("fs");
const Web3 = require("web3");

const NODE_ADDRESS  = "...";
const PRIVATE_KEY   = "...";
const CONTRACT_NAME = "...";
const CONTRACT_ARGS = [...];

async function scan(message) {
   process.stdout.write(message);
   return await new Promise(function(resolve, reject) {
       process.stdin.resume();
       process.stdin.once("data", function(data) {
           process.stdin.pause();
           resolve(data.toString().trim());
       });
   });
}

async function getGasPrice(web3) {
   while (true) {
       const nodeGasPrice = await web3.eth.getGasPrice();
       const userGasPrice = await scan(`Enter gas-price or leave empty to use ${nodeGasPrice}: `);
       if (/^\d+$/.test(userGasPrice))
           return userGasPrice;
       if (userGasPrice == "")
           return nodeGasPrice;
       console.log("Illegal gas-price");
   }
}

async function getTransactionReceipt(web3) {
   while (true) {
       const hash = await scan("Enter transaction-hash or leave empty to retry: ");
       if (/^0x([0-9A-Fa-f]{64})$/.test(hash)) {
           const receipt = await web3.eth.getTransactionReceipt(hash);
           if (receipt)
               return receipt;
           console.log("Invalid transaction-hash");
       }
       else if (hash) {
           console.log("Illegal transaction-hash");
       }
       else {
           return null;
       }
   }
}

async function send(web3, account, transaction) {
   while (true) {
       try {
           const options = {
               data    : transaction.encodeABI(),
               gas     : await transaction.estimateGas({from: account.address}),
               gasPrice: await getGasPrice(web3),
           };
           const signed  = await web3.eth.accounts.signTransaction(options, account.privateKey);
           const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction);
           return receipt;
       }
       catch (error) {
           console.log(error.message);
           const receipt = await getTransactionReceipt(web3);
           if (receipt)
               return receipt;
       }
   }
}

async function run() {
   const web3        = new Web3(NODE_ADDRESS);
   const account     = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
   const abi         = fs.readFileSync(CONTRACT_NAME + ".abi", {encoding: "utf8"});
   const bin         = fs.readFileSync(CONTRACT_NAME + ".bin", {encoding: "utf8"});
   const contract    = new web3.eth.Contract(JSON.parse(abi));
   const options     = {data: "0x" + bin, arguments: CONTRACT_ARGS};
   const transaction = contract.deploy(options);
   const receipt     = await send(web3, account, transaction);
   console.log(receipt.contractAddress);
   if (web3.currentProvider.constructor.name == "WebsocketProvider")
       web3.currentProvider.connection.close();
}

run();

引用自:https://ethereum.stackexchange.com/questions/80422