使用 Web3 和 Truffle HDWalletProvider 在 Infura 上部署智能合约 (Kovan Testnet)



不管是好是坏,我正在学习2018年末的教程,帮助我了解如何在Kovan testnet上部署智能合约。我知道版本控制可能是一个问题,所以在我显示deploy.js之前,这里是我的package.json:

"dependencies": {
"ganache-cli": "^6.10.2",
"mocha": "^4.1.0",
"solc": "^0.4.25",
"truffle-hdwallet-provider": "0.0.3",
"web3": "^1.0.0-beta.26"
},

我的.env:

WALLET_SEED="some 12 word seed phrase"
INFURA_ENDPOINT="https://kovan.infura.io/v3/PROJECT_ID"

deploy.js:

const dotenv = require("dotenv").config();
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const { interface, bytecode } = require('./compile');
const provider = new HDWalletProvider(
process.env.WALLET_SEED,
process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);
const deploy = async () => {
const accounts = await web3.eth.getAccounts();

console.log('Attempting to deploy from account', accounts[0]);
const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!']})
.send({ gas: '1000000', from: accounts[0] });
console.log('Contract deployed to: ', result.options.address);
}
deploy();

编译工作正常,但当我部署时,我会收到以下错误:

UnhandledPromiseRejectionWarning: Error: Insufficient funds. The account you tried to send transaction from does not have enough funds. Required 10000000000000000 and got: 0.
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/web3.js:15:44
at XMLHttpRequest.request.onreadystatechange (/Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/truffle-hdwallet-provider/node_modules/web3/lib/web3/httpprovider.js:118:13)

我的Kovan钱包里肯定有1个ETH。有趣的是:当我在下面的代码中查询我的钱包时,我得到了以下输出:

const balance = await web3.eth.getBalance('0x...............actualaccount');
console.log(balance)
// => 1000000000000 etc.

但当我从我的助记符短语中查询Web3提供商生成的accounts变量时,我得到了一个完全不同的帐户:

const provider = new HDWalletProvider(
process.env.WALLET_SEED,
process.env.INFURA_ENDPOINT
);
const web3 = new Web3(provider);
const accounts = await web3.eth.getAccounts();
console.log(accounts)
// [ '0x..............XYZ']

当我检查web3为我构建的账户中的资金时,我确认余额确实为0:

const balance = await web3.eth.getBalance('0x...............XYZ');
console.log(balance)
// => 0

但当我将我的实际钱包地址硬编码到部署脚本中时,它会告诉我该帐户不存在!

const result = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['Hi there!']})
.send({ gas: '1000000', from: '0x.................actualaccount' });
(node:93528) UnhandledPromiseRejectionWarning: Error: Unknown address - unable to sign transaction for this address: "0x.....................actualaddress"
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:185:35
at /Users/richardjarram/code/catonmat/udemy-solidity/solidity_sandbox/node_modules/web3-provider-engine/subproviders/hooked-wallet.js:207:5

在您的truffle-config.js中,您定义了要使用的网络add'from:'0x…',确保从您知道有余额的帐户部署合同。

最新更新