Loading...
Solc is a solidity compiler, The compiler can produce various outputs, ranging from simple binaries and assembly over an abstract syntax tree (parse tree) to estimations of gas usage. It can be used in many applications. We will use this library in our node project to compile solidity file.
You can check this smartbook where author deployed smart contract from node project and used solc library to compile smart contract.
> npm init
> touch index.js
> npm install solc
Let's create a storage.sol file first
> touch Storage.sol
Our storage.sol file will be as follow :
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract Storage {
uint number;
function store(uint num) public {
number = num;
}
function retrieve() public view returns (uint){
return number;
}
}
Source of our smart contract should be created first with initialising our solc file
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');
Solc provides many options for users to compile a smart contract but we will provide simple basic configuration for compilation
const input = {
language: 'Solidity',
sources: {
'Storage.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];
TempFile will have our compiler object which consists of errors, contracts, sources etc.
const path = require('path');
const fs = require('fs');
const solc = require('solc');
// Compile contract
const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
language: 'Solidity',
sources: {
'Storage.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];