Using Web3
This guide walks you through the process of using the Solidity compiler and web3.js to deploy and interact with a Solidity-based smart contract on Harmony. Given Harmony's Ethereum compatibility features, the web3.js library can be used directly with a Harmony node.
Completed code can be found here.

Installation

1
npm i dotenv
2
npm i solc
3
npm i @truffle/hdwallet-provider web3
Copied!

Create a file Counter.sol in root.

1
pragma solidity >=0.4.22;
2
3
contract Counter {
4
uint256 private count = 0;
5
uint256 moneyStored = 0;
6
7
function incrementCounter() public {
8
count += 1;
9
}
10
function decrementCounter() public {
11
count -= 1;
12
}
13
14
function addMoney() payable public {
15
moneyStored += msg.value;
16
}
17
18
function getCount() public view returns (uint256) {
19
return count;
20
}
21
22
function getMoneyStored() public view returns (uint256){
23
return moneyStored;
24
}
25
}
Copied!

Create compile.js

The only purpose of the compile.js file, is to use the Solidity compiler to output the bytecode and interface of our contract.
1
const path = require("path");
2
const fs = require("fs");
3
const solc = require("solc");
4
5
// Compile contract
6
const contractPath = path.resolve(__dirname, "Counter.sol");
7
const source = fs.readFileSync(contractPath, "utf8");
8
const input = {
9
language: "Solidity",
10
sources: {
11
"Counter.sol": {
12
content: source,
13
},
14
},
15
settings: {
16
outputSelection: {
17
"*": {
18
"*": ["*"],
19
},
20
},
21
},
22
};
23
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
24
const contractFile = tempFile.contracts["Counter.sol"]["Counter"];
25
module.exports = contractFile;
26
Copied!

Create Deploy.js

1
require("dotenv").config();
2
const Web3 = require("web3");
3
const contractFile = require("./compile");
4
const HDWalletProvider = require("@truffle/hdwallet-provider");
5
6
const bytecode = contractFile.evm.bytecode.object;
7
const abi = contractFile.abi;
8
9
const provider = new HDWalletProvider(
10
process.env.mneumonic,
11
process.env.rpcEndpoint
12
);
13
14
const web3 = new Web3(provider);
15
16
const deploy = async () => {
17
console.log("Deploying....");
18
I;
19
const accounts = await web3.eth.getAccounts();
20
const result = await new web3.eth.Contract(abi)
21
.deploy({ data: "0x" + bytecode })
22
.send({ gas: "3000000", from: accounts[0] });
23
24
console.log("Contract deployed to", result.options.address);
25
process.exit();
26
};
27
28
deploy();
29
Copied!

Finally

1
node deploy.js
Copied!

Congratulations

You just deployed your first smart contract on Harmony using web3.js.
Export as PDF
Copy link