中文 / English
Through this basic task, you can learn the processes of compiling and deploying a smart contract, as well as learn how to use the basic APIs of web3js
.
-
You need to create a project on Infura, and get the
PROJECT ID
, change yourENDPOINTS
toGoerli
; -
Create an account on
MetaMask
, which is a browser extension;- Get a wallet
address
, and the private key; - Go
Settings
-advanced
and openShow test networks
;- Select
Goerli
, and record this address
- Select
- Top up your account through faucets or others web services;
- Wait for minutes, and see the balance on
MetaMask
- Get a wallet
-
Create a
.env
file, and add the following lines:PRIVATE_KEY=YOUR_PRIVATE_KEY INFURA_ID=YOUR_PROJECT_ID
| Note: You can check the
.env.example
file. -
If you know Chinese, you can check these tasks on BILIBILI.
Understanding The Functions of the Smart Contract
Constructor
: The constructor function of the smart contract, which is called when the contract is deployed, at the same time it will initialize thenumber
to_initialNumber
;increment
: The function of incrementing thenumber
by given_value
;rest
: The function of resetting thenumber
to 0;getNumber
: The function of getting thenumber
.
- Install dependencies:
npm install
- Copy the configuration file:
cp .env.example .env
- Edit the configuration file:
vim .env
, copy your project ID and private key to the.env
filePRIVATE_KEY=YOUR_PRIVATE_KEY INFURA_ID=YOUR_PROJECT_ID
- Run the
index.js
file:node index.js
index.js
contains the most important part of this task, which includes the following functions:
For security sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv
plugin will automatically read the configurations in the .env
file and load them as environment variables, and then you can use the private key and other environment variables via process.env
.
Here is the code:
require("dotenv").config();
const privatekey = process.env.PRIVATE_KEY;
You can not use .sol
files directly, you need to compile it to binary file firstly.
// Load contract
const source = fs.readFileSync("Incrementer.sol", "utf8");
const input = {
language: "Solidity",
sources: {
"Incrementer.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
| Note: The version of solidity in this task is 0.8.0
, different versions may have different compile ways.
const contractFile = tempFile.contracts["Incrementer.sol"]["Incrementer"];
// Get bin & abi
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
web3
is the main API of the web3js
library. It is used to interact with the blockchain.
// Create web3 with goerli provider,you can change goerli to other testnet
const web3 = new Web3(
"https://goerli.infura.io/v3/" + process.env.INFURA_ID
);
| Note: The INFURA_ID
is the PROJECT ID
of the Infura
project you created in Preparation part.
On blockchain, each user has a address
, which is unique for others, and you can get the address
by the private key. In this task, you can use to web3.eth.accounts.privateKeyToAccount
API to get your account
address by passing the private key as a parameter.
// Create account from privatekey
const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
privateKey: privatekey,
accountAddress: account.address,
};
In the 3rd step, you got the bytecode
and abi
, so you can create the contract instance by the abi
// Create contract instance
const deployContract = new web3.eth.Contract(abi);
// Create Tx
const deployTx = deployContract.deploy({
data: bytecode,
arguments: [5],
});
Use your private key to sign the deploy
transaction.
const deployTransaction = await web3.eth.accounts.signTransaction(
{
data: deployTx.encodeABI(),
gas: 8000000,
},
account_from.privateKey
);
Send your deploy
transaction to the blockchain. You will receive a receipt, and get this contract address from the receipt.
const deployReceipt = await web3.eth.sendSignedTransaction(
deployTransaction.rawTransaction
);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);
- Web3js Official Documents: https://web3js.readthedocs.io/en/v1.2.11/getting-started.html
- Code and Examples: https://docs.moonbeam.network/getting-started/local-node/deploy-contract/
- How to use web3js: https://www.dappuniversity.com/articles/web3-js-intro
- Nodejs APIs Documents: http://nodejs.cn/api/fs.html