我想部署一个智能合约(在.json文件中提供)并需要其地址(在testnet区块链上),然后尝试向其发送一些交易。所有这些都应通过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}`);
})()
但是它也给出了不足的气体误差。但是,我的帐户中有超过5个以太币的余额。
(node:3004) UnhandledPromiseRejectionWarning: Error: Returned error: insufficien
t funds for gas * price + value
答案 0 :(得分:2)
我可以看到您正在参考web3js文档。该文档是为使用本地节点的文档而准备的。当您使用Infura作为提供程序时,当您需要通过帐户进行交易时会遇到问题。如您所说,您不需要使用私钥,这是因为此处的部署功能假定该帐户已被解锁。对于将web3js库与infura用作提供程序时需要进行的更改,应参考“ https://infura.io/docs”。另外,您还必须使用私钥来签署交易(即从您的帐户中支付汽油费)