Copy npm init
npm i dotenv solc @truffle/hdwallet-provider web3
Copy MNEMONIC=<YOUR_MNEMONIC>
RPC_ENDPOINT=https://api.harmony.one
Create a file Counter.sol in root
Copy pragma solidity >=0.4.22;
contract Counter {
uint256 private count = 0;
uint256 moneyStored = 0;
function incrementCounter() public {
count += 1;
}
function decrementCounter() public {
count -= 1;
}
function addMoney() payable public {
moneyStored += msg.value;
}
function getCount() public view returns (uint256) {
return count;
}
function getMoneyStored() public view returns (uint256){
return moneyStored;
}
}
Copy const path = require("path");
const fs = require("fs");
const solc = require("solc");
// Compile contract
const contractPath = path.resolve(__dirname, "Counter.sol");
const source = fs.readFileSync(contractPath, "utf8");
const input = {
language: "Solidity",
sources: {
"Counter.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts["Counter.sol"]["Counter"];
module.exports = contractFile;
Copy require("dotenv").config();
const { Web3 } = require("web3");
const contractFile = require("./compile");
const HDWalletProvider = require("@truffle/hdwallet-provider");
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const provider = new HDWalletProvider(
process.env.MNEMONIC,
process.env.RPC_ENDPOINT
);
const web3 = new Web3(provider);
const deploy = async () => {
console.log("Deploying....");
const accounts = await web3.eth.getAccounts();
const result = await new web3.eth.Contract(abi)
.deploy({ data: "0x" + bytecode })
.send({ gas: "3000000", from: accounts[0] });
console.log("Contract deployed to", result.options.address);
process.exit();
};
deploy();
You just deployed your first smart contract on Harmony using web3.js.