
Research
NPM targeted by malware campaign mimicking familiar library names
Socket uncovered npm malware campaign mimicking popular Node.js libraries and packages from other ecosystems; packages steal data and execute remote code.
The solc npm package is a JavaScript binding for the Solidity compiler. It allows developers to compile Solidity code from within a JavaScript environment, making it easier to integrate smart contract compilation into web applications, development tools, and automated scripts.
Compile Solidity Source Code
This feature allows you to compile Solidity source code. The code sample demonstrates how to compile a simple Solidity contract using the solc package.
const solc = require('solc');
const source = 'contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } }';
const input = {
language: 'Solidity',
sources: {
'SimpleStorage.sol': {
content: source
}
},
settings: {
outputSelection: {
'*': {
'*': ['*']
}
}
}
};
const output = JSON.parse(solc.compile(JSON.stringify(input)));
console.log(output);
Get Compiler Version
This feature allows you to retrieve the version of the Solidity compiler being used. The code sample demonstrates how to get the compiler version using the solc package.
const solc = require('solc');
console.log(solc.version());
Compile with Specific Compiler Version
This feature allows you to compile Solidity code using a specific version of the Solidity compiler. The code sample demonstrates how to compile a contract using a specific compiler version.
const solc = require('solc');
const solcVersion = 'v0.8.6+commit.11564f7e';
const solcjs = require(`solc/soljson-${solcVersion}.js`);
const input = {
language: 'Solidity',
sources: {
'SimpleStorage.sol': {
content: 'contract SimpleStorage { uint storedData; function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } }'
}
},
settings: {
outputSelection: {
'*': {
'*': ['*']
}
}
}
};
const output = JSON.parse(solcjs.compile(JSON.stringify(input)));
console.log(output);
Truffle is a development environment, testing framework, and asset pipeline for Ethereum. It provides a suite of tools for developing smart contracts, including compilation, linking, deployment, and binary management. Unlike solc, which focuses solely on compilation, Truffle offers a more comprehensive suite of tools for the entire smart contract development lifecycle.
Hardhat is a development environment for Ethereum that helps developers manage and automate the recurring tasks inherent to building smart contracts and DApps. It includes a built-in Solidity compiler, but also offers additional features like task runners, testing, and debugging. Hardhat provides a more integrated development experience compared to solc, which is focused on compilation.
Embark is a framework for developing and deploying decentralized applications (DApps) that integrates with Ethereum blockchains. It includes a Solidity compiler, but also offers features for managing smart contract deployment, testing, and communication with decentralized storage and messaging systems. Embark provides a broader range of functionalities compared to solc, which is specialized in compilation.
JavaScript bindings for the Solidity compiler.
Uses the Emscripten compiled Solidity found in the solc-bin repository.
To use the latest stable version of the Solidity compiler via Node.js you can install it via npm:
npm install solc
If this package is installed globally (npm install -g solc
), a command-line tool called solcjs
will be available.
To see all the supported features, execute:
solcjs --help
Note: this commandline interface is not compatible with solc
provided by the Solidity compiler package and thus cannot be
used in combination with an Ethereum client via the eth.compile.solidity()
RPC method. Please refer to the
Solidity compiler documentation for instructions to install solc
.
It can also be included and used in other projects:
var solc = require('solc')
var input = 'contract x { function g() {} }'
// Setting 1 as second paramateractivates the optimiser
var output = solc.compile(input, 1)
for (var contractName in output.contracts) {
// code and ABI that are needed by web3
console.log(contractName + ': ' + output.contracts[contractName].bytecode)
console.log(contractName + '; ' + JSON.parse(output.contracts[contractName].interface))
}
Starting from version 0.1.6, multiple files are supported with automatic import resolution by the compiler as follows:
var solc = require('solc')
var input = {
'lib.sol': 'library L { function f() returns (uint) { return 7; } }',
'cont.sol': 'import "lib.sol"; contract x { function g() { L.f(); } }'
}
var output = solc.compile({ sources: input }, 1)
for (var contractName in output.contracts)
console.log(contractName + ': ' + output.contracts[contractName].bytecode)
Note that all input files that are imported have to be supplied, the compiler will not load any additional files on its own.
Starting from version 0.2.1, a callback is supported to resolve missing imports as follows:
var solc = require('solc')
var input = {
'cont.sol': 'import "lib.sol"; contract x { function g() { L.f(); } }'
}
function findImports (path) {
if (path === 'lib.sol')
return { contents: 'library L { function f() returns (uint) { return 7; } }' }
else
return { error: 'File not found' }
}
var output = solc.compile({ sources: input }, 1, findImports)
for (var contractName in output.contracts)
console.log(contractName + ': ' + output.contracts[contractName].bytecode)
The compile()
method always returns an object, which can contain errors
, sources
and contracts
fields. errors
is a list of error mesages.
Starting from version 0.4.11 there is a new entry point named compileStandardWrapper()
which supports Solidity's standard JSON input and output. It also maps old compiler output to it.
var solc = require('solc')
// 'input' is a JSON string corresponding to the "standard JSON input" as described in the link above
// 'findImports' works as described above
var output = solc.compileStandardWrapper(input, findImports)
// Ouput is a JSON string corresponding to the "standard JSON output"
There is also a direct method, compileStandard
, which is only present on recent compilers and works the same way. compileStandardWrapper
is preferred however because it provides the same interface for old compilers.
Starting from version 0.4.20 a Semver compatible version number can be retrieved on every compiler release, including old ones, using the semver()
method.
Note:
If you are using Electron, nodeIntegration
is on for BrowserWindow
by default. If it is on, Electron will provide a require
method which will not behave as expected and this may cause calls, such as require('solc')
, to fail.
To turn off nodeIntegration
, use the following:
new BrowserWindow({
webPreferences: {
nodeIntegration: false
}
})
In order to compile contracts using a specific version of Solidity, the solc.loadRemoteVersion(version, callback)
method is available. This returns a new solc
object that uses a version of the compiler specified.
You can also load the "binary" manually and use setupMethods
to create the familiar wrapper functions described above:
var solc = solc.setupMethods(require("/my/local/soljson.js"))
.
By default, the npm version is only created for releases. This prevents people from deploying contracts with non-release versions because they are less stable and harder to verify. If you would like to use the latest development snapshot (at your own risk!), you may use the following example code.
var solc = require('solc')
// getting the development snapshot
solc.loadRemoteVersion('latest', function (err, solcSnapshot) {
if (err) {
// An error was encountered, display and quit
}
var output = solcSnapshot.compile("contract t { function g() {} }", 1)
})
When using libraries, the resulting bytecode will contain placeholders for the real addresses of the referenced libraries. These have to be updated, via a process called linking, before deploying the contract.
The linker
module (require('solc/linker')
) offers helpers to accomplish this.
The linkBytecode
method provides a simple helper for linking:
var linker = require('solc/linker')
bytecode = linker.linkBytecode(bytecode, { 'MyLibrary': '0x123456...' })
(Note: linkBytecode
is also exposed via solc
as solc.linkBytecode
, but this usage is deprecated.)
As of Solidity 0.4.11 the compiler supports standard JSON input and output which outputs a link references map. This gives a map of library names to offsets in the bytecode to replace the addresses at. It also doesn't have the limitation on library file and contract name lengths.
There is a method available in the linker
module called findLinkReferences
which can find such link references in bytecode produced by an older compiler:
var linker = require('solc/linker')
var linkReferences = linker.findLinkReferences(bytecode)
The ABI generated by Solidity versions can differ slightly, due to new features introduced. There is a tool included which aims to translate the ABI generated by an older Solidity version to conform to the latest standard.
It can be used as:
var abi = require('solc/abi')
var inputABI = [{"constant":false,"inputs":[],"name":"hello","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function"}]
var outputABI = abi.update('0.3.6', inputABI)
// Output contains: [{"constant":false,"inputs":[],"name":"hello","outputs":[{"name":"","type":"string"}],"payable":true,"type":"function"},{"type":"fallback","payable":true}]
There is a helper available to format old JSON assembly output into a text familiar to earlier users of Remix IDE.
var translate = require('solc/translate')
// assemblyJSON refers to the JSON of the given assembly and sourceCode is the source of which the assembly was generated from
var output = translate.prettyPrintLegacyAssemblyJSON(assemblyJSON, sourceCode)
FAQs
Solidity compiler
The npm package solc receives a total of 523,041 weekly downloads. As such, solc popularity was classified as popular.
We found that solc demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Socket uncovered npm malware campaign mimicking popular Node.js libraries and packages from other ecosystems; packages steal data and execute remote code.
Research
Socket's research uncovers three dangerous Go modules that contain obfuscated disk-wiping malware, threatening complete data loss.
Research
Socket uncovers malicious packages on PyPI using Gmail's SMTP protocol for command and control (C2) to exfiltrate data and execute commands.