如何在同一个 javascript 程序中部署和获取智能合约的地址

How to deploy and get address of smart contract in same javascript program

我想部署一个智能合约(在 .json 文件中提供)并需要它的地址(在测试网区块链上),然后尝试向它发送一些交易。这些都应该通过javascript来完成。这是我尝试部署但无法 运行 的代码。另外,我很困惑为什么在这里我们没有在部署合同期间使用我们的私钥进行签名。 更新代码:

var Tx = require('ethereumjs-tx').Transaction
const Web3 = require('web3');
const provider = new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/7f....90b30dd22f0");
const web3 = new Web3(provider);
const account1 = '0xd458d3B03A3D4025Ae3DD5a3358afDa832c7507e' 
const privateKey1 = Buffer.from('8005F9FE6F1......','hex')
var compiledContract = require('./build/MyContract.json');
// bytecode ="0x"+ compiledContract.bytecode;
//  abi = compiledContract.abi;
// console.log(web3.eth.accounts.create());

(async () => {

    const deployedContract = await new web3.eth.Contract(compiledContract.abi)
        .deploy({
            data: '0x' + compiledContract.bytecode,
            arguments: [account1]
        })
        .send({
            from: account1,
            gas: '2000000'
        });

    console.log(
        `Contract deployed at address: ${deployedContract.options.address}`
    );

这是我的输出:

    (async () => {
    ^
    TypeError: Buffer.from(...) is not a function
        at Object.<anonymous> (C:\Users\aa\MyProject\deploy.js:62:1)
        at Module._compile (internal/modules/cjs/loader.js:778:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
        at Module.load (internal/modules/cjs/loader.js:653:32)
        at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
        at Function.Module._load (internal/modules/cjs/loader.js:585:3)
        at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
        at startup (internal/bootstrap/node.js:283:19)
        at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

我也试过这个代码

(async () => {

const contract = new web3.eth.Contract(compiledContract.abi);
const params = {
    data: '0x' + compiledContract.bytecode,
    arguments: [account1]
};
const transaction = contract.deploy(params);
const options = {
    data: transaction.encodeABI(),
    gas: await transaction.estimateGas({from: account1})
};
console.log(options)
const signed = await web3.eth.accounts.signTransaction(options, privateKey1);
const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction).then(console.log);
console.log(`Contract deployed at address: ${receipt.contractAddress}`);
})()

但它也会给出 insufficient gas 错误。但是,我的账户余额超过 5 个以太币。

(node:3004) UnhandledPromiseRejectionWarning: Error: Returned error: insufficien
t funds for gas * price + value

我可以看到您指的是 web3js 文档。该文档是为使用本地 node.As 的人制作的,您使用 Infura 作为提供商,当您需要从您的帐户进行交易时,您将面临问题。正如您所说,您不需要使用私钥,那是因为此处的部署功能假定该帐户已经解锁。您应该参考“https://infura.io/docs”以了解在使用以 infura 作为提供程序的 web3js 库时需要进行的更改。此外,您必须使用私钥来签署交易(i.e.for 从您的帐户中支付汽油费)