### Install solc via npm
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Install the latest stable version of the Solidity compiler for Node.js using npm.
```bash
npm install solc
```
--------------------------------
### Compile Contract with SMT Solver Callback
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Integrate with an SMT solver for Solidity's SMTChecker. This example requires Node.js and locally installed solvers like Z3, Eldarica, or cvc5. The SMT callback API is experimental.
```javascript
var solc = require('solc');
const smtchecker = require('solc/smtchecker');
const smtsolver = require('solc/smtsolver');
// Note that this example only works via node and not in the browser.
var input = {
language: 'Solidity',
sources: {
'test.sol': {
content: 'contract C { function f(uint x) public { assert(x > 0); } }'
}
},
settings: {
modelChecker: {
engine: "chc",
solvers: [ "smtlib2" ]
}
}
};
var output = JSON.parse(
solc.compile(
JSON.stringify(input),
{ smtSolver: smtchecker.smtCallback(smtsolver.smtSolver, smtsolver.availableSolvers[0]) }
)
);
```
--------------------------------
### Display solcjs help information
Source: https://github.com/argotorg/solc-js/blob/master/README.md
If solcjs is installed globally, this command displays all supported features.
```bash
solcjs --help
```
--------------------------------
### Compile Solidity file using solcjs CLI
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles a single Solidity file from the command line, outputting the binary and ABI to a specified directory. Requires `solcjs` to be installed globally.
```bash
# Compile a single file, output binary and ABI to ./build/
solcjs --bin --abi --output-dir ./build/ MyContract.sol
```
--------------------------------
### High-level API compilation example
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Compile Solidity code using the high-level API. This example demonstrates compiling a simple contract and extracting its bytecode.
```javascript
var solc = require('solc');
var input = {
language: 'Solidity',
sources: {
'test.sol': {
content: 'contract C { function f() public { } }'
}
},
settings: {
outputSelection: {
'*': {
'*': ['*']
}
}
}
};
var output = JSON.parse(solc.compile(JSON.stringify(input)));
// `output` here contains the JSON output as specified in the documentation
for (var contractName in output.contracts['test.sol']) {
console.log(
contractName +
': ' +
output.contracts['test.sol'][contractName].evm.bytecode.object
);
}
```
--------------------------------
### Setup Local Solidity Compiler Methods
Source: https://context7.com/argotorg/solc-js/llms.txt
Wraps a locally loaded soljson Emscripten module to create a fully functional solc wrapper. This is useful when embedding compiler binaries directly or loading from local file paths, bypassing network requests.
```javascript
const solc = require('solc');
// Load a local soljson binary (e.g. from a vendored file)
const soljson = require('/path/to/soljson-v0.8.19+commit.7dd6d404.js');
const localSolc = solc.setupMethods(soljson);
console.log(localSolc.version()); // => "0.8.19+commit.7dd6d404.Emscripten.clang"
console.log(localSolc.license()); // => "GNU GENERAL PUBLIC LICENSE..."
const result = JSON.parse(localSolc.compile(JSON.stringify({
language: 'Solidity',
sources: { 'A.sol': { content: 'pragma solidity ^0.8.0; contract A {}' } },
settings: { outputSelection: { '*': { '*': ['abi'] } } }
})));
console.log(result.contracts['A.sol']['A'].abi); // => []
```
--------------------------------
### Show solc-js Version
Source: https://context7.com/argotorg/solc-js/llms.txt
Displays the currently installed version of solc-js. This is helpful for verifying the compiler version being used.
```bash
solcjs --version
```
--------------------------------
### Get Current Compiler Version
Source: https://context7.com/argotorg/solc-js/llms.txt
Retrieves the full version string of the currently loaded Solidity compiler binary. Also provides a semver-compatible string for version comparisons.
```javascript
const solc = require('solc');
const ver = solc.version();
console.log(ver);
// => "0.8.35+commit.d9e8b749.Emscripten.clang"
const semVer = solc.semver();
console.log(semVer);
// => "0.8.35+commit.d9e8b749"
// Use version info to conditionally enable features
const semver = require('semver');
if (semver.gte(solc.semver(), '0.6.0')) {
console.log('SMT solver callback is supported');
}
```
--------------------------------
### solc.setupMethods(soljson)
Source: https://context7.com/argotorg/solc-js/llms.txt
Wraps a locally loaded Emscripten compiler module (`soljson`) to create a fully functional `solc` compatible object. This is useful for embedding compiler binaries directly or loading them from local file paths.
```APIDOC
## `solc.setupMethods(soljson)` — Wrap a locally loaded compiler module
Creates a full solc wrapper around any manually loaded `soljson` Emscripten module. Useful when embedding a compiler binary directly in a bundle or when loading it from a local file path, bypassing the network.
```javascript
const solc = require('solc');
// Load a local soljson binary (e.g. from a vendored file)
const soljson = require('/path/to/soljson-v0.8.19+commit.7dd6d404.js');
const localSolc = solc.setupMethods(soljson);
console.log(localSolc.version()); // => "0.8.19+commit.7dd6d404.Emscripten.clang"
console.log(localSolc.license()); // => "GNU GENERAL PUBLIC LICENSE..."
const result = JSON.parse(localSolc.compile(JSON.stringify({
language: 'Solidity',
sources: { 'A.sol': { content: 'pragma solidity ^0.8.0; contract A {}' } },
settings: { outputSelection: { '*': { '*': ['abi'] } } }
})));
console.log(result.contracts['A.sol']['A'].abi); // => []
```
```
--------------------------------
### Load Solc with Web Workers (HTML)
Source: https://github.com/argotorg/solc-js/blob/master/README.md
This HTML file demonstrates how to set up a web worker to load and use solc-js in the browser. It initializes the worker and listens for messages.
```html
```
--------------------------------
### solc.version() and solc.semver()
Source: https://context7.com/argotorg/solc-js/llms.txt
Retrieves the full version string and semantic version string of the currently loaded Solidity compiler binary.
```APIDOC
## `solc.version()` — Get the compiler version string
Returns the full version string of the currently loaded Solidity compiler binary.
```javascript
const solc = require('solc');
const ver = solc.version();
console.log(ver);
// => "0.8.35+commit.d9e8b749.Emscripten.clang"
const semVer = solc.semver();
console.log(semVer);
// => "0.8.35+commit.d9e8b749"
// Use version info to conditionally enable features
const semver = require('semver');
if (semver.gte(solc.semver(), '0.6.0')) {
console.log('SMT solver callback is supported');
}
```
```
--------------------------------
### Compile Multi-File Project with Base Path and npm Libraries
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles multiple Solidity files in a project, specifying a base path and including npm libraries. This is useful for projects with complex import structures.
```bash
solcjs --bin --abi \
--base-path . \
--include-path node_modules/ \
--output-dir ./build/ \
src/Token.sol
```
--------------------------------
### solcjs CLI
Source: https://context7.com/argotorg/solc-js/llms.txt
Command-line Solidity compiler. The solcjs binary compiles Solidity files from the command line. It supports Standard JSON mode (--standard-json), binary output (--bin), ABI output (--abi), optimizer settings, base/include path resolution, and optional SMT solver integration.
```APIDOC
## solcjs CLI
### Description
The `solcjs` binary compiles Solidity files from the command line. It supports Standard JSON mode (`--standard-json`), binary output (`--bin`), ABI output (`--abi`), optimizer settings, base/include path resolution, and optional SMT solver integration when a solver is locally available.
### Usage Example
```bash
# Compile a single file, output binary and ABI to ./build/
solcjs --bin --abi --output-dir ./build/ MyContract.sol
```
### Options
- `--bin`: Output binary.
- `--abi`: Output ABI.
- `--output-dir `: Specify output directory.
- `--standard-json`: Use Standard JSON input mode.
```
--------------------------------
### solc.loadRemoteVersion(versionString, callback)
Source: https://context7.com/argotorg/solc-js/llms.txt
Downloads a specific Solidity compiler version from a remote URL and provides a compatible wrapper object via a callback. Supports loading specific releases or the 'latest' development snapshot.
```APIDOC
## `solc.loadRemoteVersion(versionString, callback)` — Load a specific compiler version at runtime
Downloads the requested compiler binary from `https://binaries.soliditylang.org/bin/` and returns a fully configured `solc`-compatible wrapper object via the callback. The `versionString` must be the full release filename stem (e.g. `v0.8.17+commit.8df45f5f`). This allows compiling contracts with any historical Solidity version without changing the installed package.
```javascript
const solc = require('solc');
// Load a specific historical release
solc.loadRemoteVersion('v0.8.17+commit.8df45f5f', function (err, solcV8) {
if (err) {
console.error('Failed to load compiler:', err.message);
return;
}
console.log('Loaded compiler version:', solcV8.version());
// => "0.8.17+commit.8df45f5f.Emscripten.clang"
const output = JSON.parse(solcV8.compile(JSON.stringify({
language: 'Solidity',
sources: {
'Simple.sol': { content: 'pragma solidity ^0.8.0; contract Simple { uint x = 1; }' }
},
settings: { outputSelection: { '*': { '*': ['evm.bytecode'] } } }
})));
console.log('Bytecode:', output.contracts['Simple.sol']['Simple'].evm.bytecode.object);
});
// Load the latest development snapshot (not for production use)
solc.loadRemoteVersion('latest', function (err, solcSnapshot) {
if (!err) console.log('Dev snapshot version:', solcSnapshot.version());
});
```
```
--------------------------------
### solc.compile(input, callbacks?)
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles Solidity source code using the Standard JSON interface. This is the recommended API for compilation and supports all compiler versions down to 0.1.x.
```APIDOC
## solc.compile(input, callbacks?)
### Description
Compiles Solidity source code via Standard JSON input. It returns a Standard JSON output string. An optional `callbacks` object can provide an `import` callback for resolving source imports and an `smtSolver` callback for SMTChecker queries (compiler version 0.6.0 and above).
### Method
`solc.compile(input: string, callbacks?: { import?: (importPath: string) => { contents: string } | { error: string }, smtSolver?: (query: string) => string }) => string`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```javascript
const solc = require('solc');
const input = JSON.stringify({
language: 'Solidity',
sources: {
'Token.sol': {
content: `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Token {
string public name;
uint256 public totalSupply;
constructor(string memory _name, uint256 _supply) {
name = _name;
totalSupply = _supply;
}
}
`
}
},
settings: {
optimizer: { enabled: true, runs: 200 },
outputSelection: {
'*': {
'*': ['abi', 'evm.bytecode', 'evm.deployedBytecode', 'metadata']
}
}
}
});
const output = JSON.parse(solc.compile(input));
if (output.errors) {
output.errors.forEach(err => {
if (err.severity === 'error') console.error(err.formattedMessage);
else console.warn(err.formattedMessage);
});
}
const contract = output.contracts['Token.sol']['Token'];
console.log('ABI:', contract.abi);
console.log('Bytecode:', contract.evm.bytecode.object);
function findImports(importPath) {
const libs = {
'IERC20.sol': 'interface IERC20 { function totalSupply() external view returns (uint256); }'
};
if (libs[importPath]) return { contents: libs[importPath] };
return { error: 'File not found: ' + importPath };
}
const outputWithImport = JSON.parse(
solc.compile(
JSON.stringify({
language: 'Solidity',
sources: {
'MyToken.sol': { content: 'import "IERC20.sol"; contract MyToken is IERC20 { function totalSupply() external pure returns (uint256) { return 1e6 ether; } }' }
},
settings: { outputSelection: { '*': { '*': ['abi'] } } }
}),
{ import: findImports }
)
);
console.log(outputWithImport.contracts['MyToken.sol']['MyToken'].abi);
```
### Response
#### Success Response (200)
Returns a Standard JSON output string containing compilation results, including contract artifacts, errors, and warnings.
#### Response Example
```json
{
"contracts": {
"Token.sol": {
"Token": {
"abi": [
{
"inputs": [
{
"internalType": "string",
"name": "_name",
"type": "string"
},
{
"internalType": "uint256",
"name": "_supply",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "name",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [],
"name": "totalSupply",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
],
"evm": {
"bytecode": {
"linkReferences": {},
"object": "6080604052348015600f57600080fd5b5060043610603157600035906020596040516000600480359060200191505050603f8061004e6000396000f3fe608060405260043610603157600035906020596040516000600480359060200191505050565b600080fdfe",
"sourceMap": "..."
},
"deployedBytecode": {
"linkReferences": {},
"object": "608060405260043610603157600035906020596040516000600480359060200191505050565b600080fdfe",
"sourceMap": "..."
},
"methodIdentifiers": {
"name()": "06fdde03",
"totalSupply()": "18160ddd"
}
},
"metadata": "ipfs://..."
}
}
},
"errors": []
}
```
```
--------------------------------
### Load Latest Development Snapshot of Solc
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Use this to load the latest development snapshot of solc. This is not recommended for production due to stability concerns. Ensure you handle potential errors during loading.
```javascript
var solc = require('solc');
// getting the development snapshot
solc.loadRemoteVersion('latest', function(err, solcSnapshot) {
if (err) {
// An error was encountered, display and quit
} else {
// NOTE: Use `solcSnapshot` here with the same interface `solc` has
// For example:
const output = solcSnapshot.compile(/* ... */)
}
});
```
--------------------------------
### Create SMT Solver Callback with solc-js
Source: https://context7.com/argotorg/solc-js/llms.txt
Wraps a solver function into the callback format expected by `solc.compile()`. The returned function receives an SMTLib2 query string and returns `{ contents: result }` on success or `{ error: err }` on failure. Requires `solc`, `smtchecker`, and `smtsolver` modules.
```javascript
const solc = require('solc');
const smtchecker = require('solc/smtchecker');
const smtsolver = require('solc/smtsolver');
console.log('Available solvers:', smtsolver.availableSolvers.map(s => s.name));
// e.g. ["z3"] if z3 is installed
const input = JSON.stringify({
language: 'Solidity',
sources: {
'Assert.sol': {
content: `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Assert {
function check(uint x) public pure {
assert(x > 0); // deliberately weak — will fail for x == 0
}
}
`
}
},
settings: {
modelChecker: {
engine: 'chc',
solvers: ['smtlib2']
},
outputSelection: { '*': { '*': ['*'] } }
}
});
if (smtsolver.availableSolvers.length > 0) {
const output = JSON.parse(
solc.compile(input, {
smtSolver: smtchecker.smtCallback(smtsolver.smtSolver, smtsolver.availableSolvers[0])
})
);
output.errors?.forEach(e => console.log(e.severity + ':', e.message));
// => "warning: Assertion violation happens here" (counterexample: x = 0)
} else {
console.log('No SMT solver found — skipping formal verification');
}
```
--------------------------------
### smtchecker.handleSMTQueries
Source: https://context7.com/argotorg/solc-js/llms.txt
Batch-resolves SMT queries for a two-pass compile. When the compiler emits auxiliaryInputRequested.smtlib2queries in its output, this function invokes the solver on each query, injects the results into inputJSON.auxiliaryInput.smtlib2responses, and returns the augmented input ready for a second compilation pass. Returns null if no SMT solving is requested.
```APIDOC
## smtchecker.handleSMTQueries(inputJSON, outputJSON, solverFunction, solver?)
### Description
Batch-resolves SMT queries for a two-pass compile. When the compiler emits `auxiliaryInputRequested.smtlib2queries` in its output, this function invokes the solver on each query, injects the results into `inputJSON.auxiliaryInput.smtlib2responses`, and returns the augmented input ready for a second compilation pass. Returns `null` if no SMT solving is requested.
### Parameters
- **inputJSON**: The initial input JSON for the compilation.
- **outputJSON**: The output JSON from the first compilation pass.
- **solverFunction**: The SMT solver function to use.
- **solver?**: Optional solver instance.
### Request Example
```javascript
const solc = require('solc');
const smtchecker = require('solc/smtchecker');
const smtsolver = require('solc/smtsolver');
// ... (define inputJSON and perform first compilation pass)
if (smtsolver.availableSolvers.length > 0) {
const secondInput = smtchecker.handleSMTQueries(
inputJSON,
firstOutput,
smtsolver.smtSolver,
smtsolver.availableSolvers[0]
);
if (secondInput) {
// Second pass with SMT answers injected
const finalOutput = JSON.parse(solc.compile(JSON.stringify(secondInput)));
// ... (process finalOutput)
}
}
```
### Response
- Returns the augmented input JSON for a second compilation pass, or `null` if no SMT solving was requested.
```
--------------------------------
### smtchecker.smtCallback
Source: https://context7.com/argotorg/solc-js/llms.txt
Wraps a solver function into the callback format expected by solc.compile() as callbacks.smtSolver. The returned function receives an SMTLib2 query string and returns { contents: result } on success or { error: err } on failure.
```APIDOC
## smtchecker.smtCallback(solverFunction, solver?)
### Description
Wraps a solver function into the callback format expected by `solc.compile()` as `callbacks.smtSolver`. The returned function receives an SMTLib2 query string and returns `{ contents: result }` on success or `{ error: err }` on failure. Combine with `smtsolver.smtSolver` and `smtsolver.availableSolvers` for a fully wired local solver.
### Parameters
- **solverFunction**: The function to be wrapped as an SMT solver callback.
- **solver?**: Optional solver instance.
### Request Example
```javascript
const solc = require('solc');
const smtchecker = require('solc/smtchecker');
const smtsolver = require('solc/smtsolver');
// ... (setup input and check for available solvers)
if (smtsolver.availableSolvers.length > 0) {
const output = JSON.parse(
solc.compile(input, {
smtSolver: smtchecker.smtCallback(smtsolver.smtSolver, smtsolver.availableSolvers[0])
})
);
// ... (process output)
}
```
### Response
- Returns a callback function compatible with `solc.compile()`'s `smtSolver` option.
```
--------------------------------
### Compile Solidity Source via Standard JSON
Source: https://context7.com/argotorg/solc-js/llms.txt
Use this primary API for compiling Solidity code using the Standard JSON input format. It supports all compiler versions and can handle source imports via a callback.
```javascript
const solc = require('solc');
// --- Basic compilation ---
const input = JSON.stringify({
language: 'Solidity',
sources: {
'Token.sol': {
content: `
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Token {
string public name;
uint256 public totalSupply;
constructor(string memory _name, uint256 _supply) {
name = _name;
totalSupply = _supply;
}
}
`
}
},
settings: {
optimizer: { enabled: true, runs: 200 },
outputSelection: {
'*': {
'*': ['abi', 'evm.bytecode', 'evm.deployedBytecode', 'metadata']
}
}
}
});
const output = JSON.parse(solc.compile(input));
// Check for errors
if (output.errors) {
output.errors.forEach(err => {
if (err.severity === 'error') console.error(err.formattedMessage);
else console.warn(err.formattedMessage);
});
}
// Access compiled artifacts
const contract = output.contracts['Token.sol']['Token'];
console.log('ABI:', contract.abi);
console.log('Bytecode:', contract.evm.bytecode.object);
// Expected: ABI array + hex-encoded bytecode string
// --- Compilation with import callback ---
function findImports(importPath) {
const libs = {
'IERC20.sol': 'interface IERC20 { function totalSupply() external view returns (uint256); }'
};
if (libs[importPath]) return { contents: libs[importPath] };
return { error: 'File not found: ' + importPath };
}
const outputWithImport = JSON.parse(
solc.compile(
JSON.stringify({
language: 'Solidity',
sources: {
'MyToken.sol': { content: 'import "IERC20.sol"; contract MyToken is IERC20 { function totalSupply() external pure returns (uint256) { return 1e6 ether; } }' }
},
settings: { outputSelection: { '*': { '*': ['abi'] } } }
}),
{ import: findImports }
)
);
console.log(outputWithImport.contracts['MyToken.sol']['MyToken'].abi);
```
--------------------------------
### Compile contract with relative paths
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Compile a contract that imports other contracts using relative paths. Use --base-path and --include-path to specify project layout.
```bash
solcjs --bin --include-path node_modules/ --base-path . MainContract.sol
```
--------------------------------
### Link Bytecode with Helper
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Use the linker module to link bytecode, replacing library placeholders with actual addresses. This is necessary when deploying contracts that use libraries.
```javascript
var linker = require('solc/linker');
bytecode = linker.linkBytecode(bytecode, { MyLibrary: '0x123456...' });
```
--------------------------------
### Compile with Verbose Mode
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles a Solidity contract in verbose mode, which shows the full JSON input and output. Useful for detailed inspection of the compilation process.
```bash
solcjs --bin --abi --verbose --output-dir ./out/ MyContract.sol
```
--------------------------------
### linker.linkBytecode(bytecode, libraries)
Source: https://context7.com/argotorg/solc-js/llms.txt
Replaces all library address placeholders in hex-encoded bytecode with the supplied concrete addresses. Supports both old-style and new-style placeholders. Library addresses can be specified in various formats.
```APIDOC
## linker.linkBytecode(bytecode, libraries) — Link library placeholders in bytecode
### Description
Replaces all library address placeholders in hex-encoded bytecode with the supplied concrete addresses. Supports both old-style (`__LibName____...____`) and new-style (`__$$__`) placeholders. Library addresses may be specified as fully qualified names (`"file.sol:LibName"`), plain names, or using the nested `{"file.sol": {"LibName": "0x..."}}` format matching Standard JSON output.
### Parameters
#### Path Parameters
- **bytecode** (string) - Required - The hex-encoded bytecode containing library placeholders.
- **libraries** (object) - Required - An object mapping library names to their concrete addresses. Can be a flat map of `"file.sol:LibName": "0x..."` or a nested map `{"file.sol": {"LibName": "0x..."}}`.
### Request Example
```javascript
const linker = require('solc/linker');
const unlinkedBytecode = '6080604052348015600f57600080fd5b50__$cb901161e812ceb78cfe30ca65050c4337$__ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
const linked = linker.linkBytecode(unlinkedBytecode, {
'MathLib.sol:MathLib': '0xCAfEcAfeCAfECaFeCaFecaFecaFECafECafeCaFe'
});
console.log(linked);
```
### Response
#### Success Response (200)
- **string** - The hex-encoded bytecode with library placeholders replaced by addresses.
### Error Handling
- Throws an error if no address is provided for a library.
- Throws an error if an invalid address is specified for a library.
```
--------------------------------
### Link Library Placeholders in Bytecode with solc-js
Source: https://context7.com/argotorg/solc-js/llms.txt
Use `linker.linkBytecode` to replace library address placeholders in hex-encoded bytecode with concrete addresses. Supports old and new placeholder styles and various address input formats. Ensure a valid address is provided for each placeholder.
```javascript
const linker = require('solc/linker');
// Bytecode containing an unlinked library placeholder
const unlinkedBytecode =
'6080604052348015600f57600080fd5b50__$cb901161e812ceb78cfe30ca65050c4337$__'
+ 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
// Link with a concrete address
const linked = linker.linkBytecode(unlinkedBytecode, {
'MathLib.sol:MathLib': '0xCAfEcAfeCAfECaFeCaFecaFecaFECafECafeCaFe'
});
console.log(linked);
// All $...$ placeholders are replaced with the hex address (without 0x)
// Error cases
try {
linker.linkBytecode(unlinkedBytecode, { 'MathLib.sol:MathLib': null });
} catch (e) {
console.error(e.message); // "No address provided for library MathLib.sol:MathLib"
}
try {
linker.linkBytecode(unlinkedBytecode, { 'MathLib.sol:MathLib': 'notanaddress' });
} catch (e) {
console.error(e.message); // "Invalid address specified for MathLib.sol:MathLib"
}
// Nested format (mirrors Standard JSON settings.libraries)
const linked2 = linker.linkBytecode(unlinkedBytecode, {
'MathLib.sol': { 'MathLib': '0xCAfEcAfeCAfECaFeCaFecaFecaFECafECafeCaFe' }
});
console.log(linked2 === linked); // true
```
--------------------------------
### Load Solc with Web Workers (Worker Script)
Source: https://github.com/argotorg/solc-js/blob/master/README.md
This JavaScript file is designed to be used as a web worker. It imports the solc compiler and exposes its version via messages.
```javascript
importScripts('https://binaries.soliditylang.org/bin/soljson-v0.8.19+commit.7dd6d404.js')
import wrapper from 'solc/wrapper';
self.addEventListener('message', () => {
const compiler = wrapper(self.Module)
self.postMessage({
version: compiler.version()
})
}, false)
```
--------------------------------
### Batch-resolve SMT Queries with solc-js
Source: https://context7.com/argotorg/solc-js/llms.txt
Resolves SMT queries from a first compilation pass and injects results for a second pass. Returns `null` if no SMT solving is requested. Requires `solc`, `smtchecker`, and `smtsolver` modules.
```javascript
const solc = require('solc');
const smtchecker = require('solc/smtchecker');
const smtsolver = require('solc/smtsolver');
const inputJSON = {
language: 'Solidity',
sources: {
'Verify.sol': {
content: `
pragma solidity ^0.8.0;
contract Verify {
function safe(uint256 a, uint256 b) public pure returns (uint256) {
require(b != 0);
return a / b;
}
}
`
}
},
settings: {
modelChecker: { engine: 'chc', solvers: ['smtlib2'] },
outputSelection: { '*': { '*': ['*'] } }
}
};
// First compilation pass — may request SMT queries
const firstOutput = JSON.parse(solc.compile(JSON.stringify(inputJSON)));
if (smtsolver.availableSolvers.length > 0) {
// Resolve any outstanding SMT queries and build a second-pass input
const secondInput = smtchecker.handleSMTQueries(
inputJSON,
firstOutput,
smtsolver.smtSolver,
smtsolver.availableSolvers[0]
);
if (secondInput) {
// Second pass with SMT answers injected
const finalOutput = JSON.parse(solc.compile(JSON.stringify(secondInput)));
finalOutput.errors?.forEach(e => console.log(e.severity + ':', e.message));
} else {
console.log('No SMT queries requested by compiler');
}
}
```
--------------------------------
### Compile Contract with Optimizer Enabled
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles a Solidity contract with the optimizer enabled for a specified number of runs. Use this for production builds where performance is critical.
```bash
solcjs --bin --abi --optimize --optimize-runs 200 --output-dir ./build/ MyContract.sol
```
--------------------------------
### Compile using Standard JSON Mode
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles Solidity contracts using the Standard JSON input mode, reading from stdin and writing to stdout. This is suitable for integration with build systems.
```bash
cat input.json | solcjs --standard-json
```
--------------------------------
### Load Remote Solidity Compiler Version
Source: https://context7.com/argotorg/solc-js/llms.txt
Downloads and loads a specific Solidity compiler version from a remote URL. Use this to compile contracts with historical or specific versions. The 'latest' keyword can be used to load the most recent development snapshot, but it's not recommended for production.
```javascript
const solc = require('solc');
// Load a specific historical release
solc.loadRemoteVersion('v0.8.17+commit.8df45f5f', function (err, solcV8) {
if (err) {
console.error('Failed to load compiler:', err.message);
return;
}
console.log('Loaded compiler version:', solcV8.version());
// => "0.8.17+commit.8df45f5f.Emscripten.clang"
const output = JSON.parse(solcV8.compile(JSON.stringify({
language: 'Solidity',
sources: {
'Simple.sol': { content: 'pragma solidity ^0.8.0; contract Simple { uint x = 1; }' }
},
settings: { outputSelection: { '*': { '*': ['evm.bytecode'] } } }
})));
console.log('Bytecode:', output.contracts['Simple.sol']['Simple'].evm.bytecode.object);
});
// Load the latest development snapshot (not for production use)
solc.loadRemoteVersion('latest', function (err, solcSnapshot) {
if (!err) console.log('Dev snapshot version:', solcSnapshot.version());
});
```
--------------------------------
### Find Library Link References in Bytecode with solc-js
Source: https://context7.com/argotorg/solc-js/llms.txt
Use `linker.findLinkReferences` to scan hex-encoded bytecode for library placeholders. It returns a map of placeholder names to their byte offsets and lengths within the binary representation. An empty map indicates fully linked bytecode.
```javascript
const linker = require('solc/linker');
const bytecodeWithRefs =
'608060405234801561001057600080fd5b50'
+ '__MathLib_sol_MathLib____________________' +
'6040518263ffffffff1660e01b815260040180828152602001915050';
const refs = linker.findLinkReferences(bytecodeWithRefs);
console.log(JSON.stringify(refs, null, 2));
// {
// "MathLib_sol_MathLib": [
// { "start": 18, "length": 20 }
// ]
// }
// Detect whether bytecode is fully linked
const isFullyLinked = Object.keys(linker.findLinkReferences(bytecodeWithRefs)).length === 0;
console.log('Fully linked:', isFullyLinked); // false
```
--------------------------------
### Format Legacy Assembly JSON with solc-js
Source: https://context7.com/argotorg/solc-js/llms.txt
Converts legacy assembly JSON output into a human-readable text format, similar to Remix IDE's display. An optional `source` string can annotate opcodes with corresponding source snippets.
```javascript
const translate = require('solc/translate');
// assemblyJSON is the object from output.contracts[file][name].evm.legacyAssembly
const assemblyJSON = {
'.code': [
{ name: 'PUSH', value: '80', begin: 0, end: 11 },
{ name: 'PUSH', value: '40', begin: 0, end: 11 },
{ name: 'MSTORE', begin: 0, end: 11 }
],
'.data': {}
};
const sourceCode = 'pragma solidity ^0.4.0; contract X {}';
const prettyOutput = translate.prettyPrintLegacyAssemblyJSON(assemblyJSON, sourceCode);
console.log(prettyOutput);
// .code
// PUSH 80 pragma solidity ^0.4...
// PUSH 40 pragma solidity ^0.4...
// MSTORE pragma solidity ^0.4...
// .data
```
--------------------------------
### Pretty-print Standard JSON Output
Source: https://context7.com/argotorg/solc-js/llms.txt
Compiles Solidity contracts using Standard JSON mode and pretty-prints the output to stdout. This aids in debugging and readability of compiler output.
```bash
cat input.json | solcjs --standard-json --pretty-json
```
--------------------------------
### Compile Contract with Import Callback
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Use this snippet to compile Solidity contracts that have import statements. The `findImports` function must be provided to resolve imported files.
```javascript
var solc = require('solc');
var input = {
language: 'Solidity',
sources: {
'test.sol': {
content: 'import "lib.sol"; contract C { function f() public { L.f(); } }'
}
},
settings: {
outputSelection: {
'*': {
'*': ['*']
}
}
}
};
function findImports(path) {
if (path === 'lib.sol')
return {
contents:
'library L { function f() internal returns (uint) { return 7; } }'
};
else return { error: 'File not found' };
}
// New syntax (supported from 0.5.12, mandatory from 0.6.0)
var output = JSON.parse(
solc.compile(JSON.stringify(input), { import: findImports })
);
// `output` here contains the JSON output as specified in the documentation
for (var contractName in output.contracts['test.sol']) {
console.log(
contractName +
': ' +
output.contracts['test.sol'][contractName].evm.bytecode.object
);
}
```
--------------------------------
### solc.lowlevel
Source: https://context7.com/argotorg/solc-js/llms.txt
Provides direct bindings to the underlying Emscripten-compiled C functions for older compiler versions. Prefer `solc.compile()` for new code.
```APIDOC
## `solc.lowlevel` — Low-level compiler bindings
Direct bindings to the underlying Emscripten-compiled C functions. These are preserved for backward compatibility only. `compileSingle` (pre-0.1.6), `compileMulti` (0.1.6+), `compileCallback` (0.2.1+), and `compileStandard` (0.4.11+) map directly to the raw compiler ABI. Prefer `solc.compile()` for all new code.
```javascript
const solc = require('solc');
// compileStandard — available from 0.4.11+
if (solc.lowlevel.compileStandard) {
const rawOutput = solc.lowlevel.compileStandard(JSON.stringify({
language: 'Solidity',
sources: { 'X.sol': { content: 'contract X {}' } },
settings: { outputSelection: { '*': { '*': ['abi'] } } }
}));
console.log(JSON.parse(rawOutput).contracts['X.sol']['X'].abi); // => []
}
// compileCallback — available from 0.2.1, null on newer compilers
if (solc.lowlevel.compileCallback) {
const out = solc.lowlevel.compileCallback(
JSON.stringify({ sources: { 'X.sol': 'contract X {}' } }),
false, // optimize
(path) => ({ error: 'not found' })
);
console.log(out); // raw JSON string
}
```
```
--------------------------------
### linker.findLinkReferences(bytecode)
Source: https://context7.com/argotorg/solc-js/llms.txt
Scans hex-encoded bytecode for all library address placeholders and returns their positions and lengths in a `LinkReferences` map. The returned format mirrors the `evm.bytecode.linkReferences` field in Standard JSON output.
```APIDOC
## linker.findLinkReferences(bytecode) — Locate unlinked library placeholders
### Description
Scans hex-encoded bytecode for all library address placeholders and returns their positions and lengths in a `LinkReferences` map. The returned format mirrors the `evm.bytecode.linkReferences` field in Standard JSON output. Offsets and lengths are in bytes of the *binary* (not hex-encoded) representation.
### Parameters
#### Path Parameters
- **bytecode** (string) - Required - The hex-encoded bytecode to scan for library placeholders.
### Request Example
```javascript
const linker = require('solc/linker');
const bytecodeWithRefs = '608060405234801561001057600080fd5b50__MathLib_sol_MathLib____________________6040518263ffffffff1660e01b815260040180828152602001915050';
const refs = linker.findLinkReferences(bytecodeWithRefs);
console.log(JSON.stringify(refs, null, 2));
```
### Response
#### Success Response (200)
- **object** - A map where keys are library names and values are arrays of objects, each containing `start` (byte offset) and `length` (in bytes) of the placeholder.
### Example Response
```json
{
"MathLib_sol_MathLib": [
{ "start": 18, "length": 20 }
]
}
```
### Usage Notes
- Can be used to detect whether bytecode is fully linked by checking if the returned object is empty.
```
--------------------------------
### Format Legacy JSON Assembly Output
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Employ the translate.prettyPrintLegacyAssemblyJSON helper to format old JSON assembly output into a text format compatible with earlier versions of Remix IDE.
```javascript
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)
```
--------------------------------
### Load Specific Solc Version with Commit Hash
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Load a specific version of solc using its long format, which includes the commit hash. This is required for versions 0.4.11 and later.
```javascript
solc.loadRemoteVersion('v0.8.17+commit.8df45f5f', function(err, solcSnapshot) { /* ... */ });
```
--------------------------------
### solc.features
Source: https://context7.com/argotorg/solc-js/llms.txt
An object containing boolean flags that indicate which compiler capabilities are supported by the loaded binary. Useful for writing version-agnostic code.
```APIDOC
## `solc.features` — Query supported compiler capabilities
An object of boolean flags indicating which compilation interfaces the loaded compiler binary supports. Useful for writing code that gracefully handles both old and new compiler versions.
```javascript
const solc = require('solc');
console.log(solc.features);
// {
// legacySingleInput: true, // compileJSON (single file, very old)
// multipleInputs: true, // compileJSONMulti or Standard JSON
// importCallback: true, // import resolution callback is available
// nativeStandardJSON: true // native compileStandard / solidity_compile
// }
// Guard legacy-only code paths
if (!solc.features.nativeStandardJSON) {
console.warn('This compiler does not support Standard JSON natively; a compatibility shim will be used.');
}
```
```
--------------------------------
### Access Low-Level Compiler Bindings
Source: https://context7.com/argotorg/solc-js/llms.txt
Provides direct bindings to the underlying Emscripten-compiled C functions for backward compatibility. Prefer `solc.compile()` for new code. Includes functions like `compileStandard` and `compileCallback`.
```javascript
const solc = require('solc');
// compileStandard — available from 0.4.11+
if (solc.lowlevel.compileStandard) {
const rawOutput = solc.lowlevel.compileStandard(JSON.stringify({
language: 'Solidity',
sources: { 'X.sol': { content: 'contract X {}' } },
settings: { outputSelection: { '*': { '*': ['abi'] } } }
}));
console.log(JSON.parse(rawOutput).contracts['X.sol']['X'].abi); // => []
}
// compileCallback — available from 0.2.1, null on newer compilers
if (solc.lowlevel.compileCallback) {
const out = solc.lowlevel.compileCallback(
JSON.stringify({ sources: { 'X.sol': 'contract X {}' } }),
false, // optimize
(path) => ({ error: 'not found' })
);
console.log(out); // raw JSON string
}
```
--------------------------------
### Find Link References in Bytecode
Source: https://github.com/argotorg/solc-js/blob/master/README.md
Utilize the findLinkReferences method from the linker module to identify link references within bytecode generated by older compilers. This is useful for preparing bytecode for linking.
```javascript
var linker = require('solc/linker');
var linkReferences = linker.findLinkReferences(bytecode);
```
--------------------------------
### translate.prettyPrintLegacyAssemblyJSON
Source: https://context7.com/argotorg/solc-js/llms.txt
Formats legacy assembly output. Converts the JSON assembly object returned by old compiler versions (available in evm.legacyAssembly) into a human-readable text representation similar to the display format used by Remix IDE. The optional source string is used to annotate opcodes with the corresponding source snippet.
```APIDOC
## translate.prettyPrintLegacyAssemblyJSON(assembly, source?)
### Description
Formats legacy assembly output. Converts the JSON assembly object returned by old compiler versions (available in `evm.legacyAssembly`) into a human-readable text representation similar to the display format used by Remix IDE. The optional `source` string is used to annotate opcodes with the corresponding source snippet.
### Parameters
- **assembly**: The JSON assembly object (e.g., from `output.contracts[file][name].evm.legacyAssembly`).
- **source?**: Optional source code string to annotate opcodes.
### Request Example
```javascript
const translate = require('solc/translate');
const assemblyJSON = {
'.code': [
{ name: 'PUSH', value: '80', begin: 0, end: 11 },
{ name: 'PUSH', value: '40', begin: 0, end: 11 },
{ name: 'MSTORE', begin: 0, end: 11 }
],
'.data': {}
};
const sourceCode = 'pragma solidity ^0.4.0; contract X {}';
const prettyOutput = translate.prettyPrintLegacyAssemblyJSON(assemblyJSON, sourceCode);
console.log(prettyOutput);
```
### Response
- Returns a human-readable string representation of the legacy assembly.
```