合约编译部署基本流程
文章目录
- 合约编译部署基本流程
- 项目参考
- 准备Infura Project
- 准备私钥
- 准备测试币
- 准备项目
- 执行项目
- 详细
- 合约
- index.js
- package.json
合约编译部署基本流程
项目参考
https://github.com/Dapp-Learning-DAO/Dapp-Learning/blob/main/basic/01-web3js-deploy/README-cn.md
准备Infura Project
https://developer.metamask.io/
本项目发送交易到 Infura , 需要创建相应的 Infura Project, 可以获取相应的PROJECT ID。
注册登录,完成步骤。
点击设置看到api,就是需要的项目id。
下面需要勾选以太坊的测试网络。
准备私钥
在MetaMask的账户详情中可以显示私钥。
准备测试币
准备测试币。可参考上一篇
准备项目
替换准备的私钥和项目id。
执行项目
node index.js
然后查看infura,发现会有请求。
部署成功会显示合约地址,根据合约地址可以在以太坊测试网络上查看到相应的信息。
详细
合约
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Incrementer {
uint256 public number;
constructor(uint256 _initialNumber) {
number = _initialNumber;
}
function increment(uint256 _value) public {
number = number + _value;
}
function reset() public {
number = 0;
}
function getNumber() public view returns (uint256) {
return number;
}
}
index.js
let { Web3 } = require('web3');
let solc = require('solc');
let fs = require('fs');
// Get privatekey from environment
require('dotenv').config();
let privatekey = process.env.PRIVATE_KEY;
console.log("privatekey:", privatekey);
if (privatekey.slice(0, 2) !== '0x') privatekey = '0x' + privatekey;
// Load contract
const source = fs.readFileSync('Incrementer.sol', 'utf8');
// compile solidity
const input = {
language: 'Solidity',
sources: {
'Incrementer.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const compiledCode = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = compiledCode.contracts['Incrementer.sol']['Incrementer'];
// Get bin & abi
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
// Create web3 with sepolia provider,you can change sepolia to other testnet
const web3 = new Web3('https://sepolia.infura.io/v3/' + process.env.INFURA_ID);
// Create account from privatekey
const accounts = web3.eth.accounts.wallet.add(privatekey);
/*
-- Deploy Contract --
*/
const Deploy = async () => {
// Create contract instance
const deployContract = new web3.eth.Contract(abi);
// Create Tx
const deployTx = deployContract.deploy({
data: '0x' + bytecode,
arguments: [0], // Pass arguments to the contract constructor on deployment(_initialNumber in Incremental.sol)
});
// optionally, estimate the gas that will be used for development and log it
const gas = await deployTx.estimateGas({
from: accounts,
});
console.log('estimated gas:', gas);
try {
// Deploy the contract to the Ganache network
// Your deployed contrac can be viewed at: https://sepolia.etherscan.io/address/${tx.options.address}
// You can change sepolia in above url to your selected testnet.
const tx = await deployTx.send({
from: accounts[0].address,
gas,
// gasPrice: 10000000000,
});
console.log('Contract deployed at address: ' + tx.options.address);
} catch (error) {
console.error(error);
}
};
// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
Deploy()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "Example01-deploy-contract",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"solc": "0.8.0",
"web3": "^4.0.3"
}
}