Skip to content

Instantly share code, notes, and snippets.

@spandan114
Last active January 16, 2022 13:12
Show Gist options
  • Save spandan114/e4981f18421899a1c18fcba26c204117 to your computer and use it in GitHub Desktop.
Save spandan114/e4981f18421899a1c18fcba26c204117 to your computer and use it in GitHub Desktop.
How solidity actually compile behind the hood & how its generate ABI & Byte code .
const solc = require("solc");
// file system - read and write files to your computer
const fs = require("fs");
// web3 interface
const Web3 = require("web3");
// setup a http provider
const web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
// reading the file contents of the smart contract
const fileContent = fs.readFileSync("demo.sol").toString();
// console.log(fileContent);
// create an input structure for my solidity compiler
var input = {
language: "Solidity",
sources: {
"demo.sol": {
content: fileContent,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
var output = JSON.parse(solc.compile(JSON.stringify(input)));
// console.log("Output: ", output);
const ABI = output.contracts["demo.sol"]["Demo"].abi;
const byteCode = output.contracts["demo.sol"]["Demo"].evm.bytecode.object;
// console.log("abi: ",ABI)
// console.log("byte code: ",byteCode)
//get all acc
var getAccounts = async () => {
var allAcc = await web3.eth.getAccounts();
return allAcc;
};
//get all account balence
var getAccBalence = async () => {
var acc = await getAccounts();
acc.map(async (data) => {
var balance = await web3.eth.getBalance(data);
console.log(web3.utils.fromWei(balance, "ether"));
});
};
getAccBalence();
contract = new web3.eth.Contract(ABI);
let defaultAccount;
web3.eth.getAccounts().then((accounts) => {
console.log("Accounts:", accounts); //it will show all the ganache accounts
defaultAccount = accounts[0];
console.log("Default Account:", defaultAccount); //to deploy the contract from default Account
contract
//deploy contract
.deploy({ data: byteCode })
.send({ from: defaultAccount, gas: 470000 })
//catch event
.on("receipt", (receipt) => {
//event,transactions,contract address will be returned by blockchain
console.log("Contract Address:", receipt.contractAddress);
})
//interact with smart contract
.then((demoContract) => {
demoContract.methods.x().call((err, data) => {
console.log("Initial Value:", data);
});
});
});
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Demo{
uint public x = 10;
function setVal(uint _x) public {
x = _x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment