• Stars
    star
    1,404
  • Rank 32,209 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Javascript bindings for the Solidity compiler

CircleCI Coverage Status

solc-js

JavaScript bindings for the Solidity compiler.

Uses the Emscripten compiled Solidity found in the solc-bin repository.

Node.js Usage

To use the latest stable version of the Solidity compiler via Node.js you can install it via npm:

npm install solc

Usage on the Command-Line

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

To compile a contract that imports other contracts via relative paths:

solcjs --bin --include-path node_modules/ --base-path . MainContract.sol

Use the --base-path and --include-path options to describe the layout of your project. --base-path represents the root of your own source tree while --include-path allows you to specify extra locations containing external code (e.g. libraries installed with a package manager).

Note: ensure that all the files you specify on the command line are located inside the base path or one of the include paths. The compiler refers to files from outside of these directories using absolute paths. Having absolute paths in contract metadata will result in your bytecode being reproducible only when it's placed in these exact absolute locations.

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. Furthermore, the commandline interface to solc-js provides fewer features than the binary release.

Usage in Projects

There are two ways to use solc:

  1. Through a high-level API giving a uniform interface to all compiler versions
  2. Through a low-level API giving access to all the compiler interfaces, which depend on the version of the compiler

High-level API

The high-level API consists of a single method, compile, which expects the Compiler Standard Input and Output JSON.

It also accepts an optional set of callback functions, which include the import and the smtSolver callbacks. Starting 0.6.0 it only accepts an object in place of the callback to supply the callbacks.

The import callback function is used to resolve unmet dependencies. This callback receives a path and must synchronously return either an error or the content of the dependency as a string. It cannot be used together with callback-based, asynchronous, filesystem access. A workaround is to collect the names of dependencies, return an error, and keep re-running the compiler until all of them are resolved.

Example usage without the import callback

Example:

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
  );
}

Example usage with import callback

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
  );
}

Since version 0.5.1, the smtSolver callback function is used to solve SMT queries generated by Solidity's SMTChecker. If you have an SMT solver installed locally, it can be used to solve the given queries, where the callback must synchronously return either an error or the result from the solver. A default smtSolver callback is included in this package via the module smtchecker.js which exports the smtCallback function that takes 1) a function that takes queries and returns the solving result, and 2) a solver configuration object. The module smtsolver.js has a few predefined solver configurations, and relies on Z3, Eldarica or CVC4 being installed locally. It exports the list of locally found solvers and a function that invokes a given solver.

The API of the SMT callback is experimental and can change at any time. The last change was in version 0.8.11.

Example usage with smtSolver callback

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]) }
  )
);

The assertion is clearly false, and an assertion failure warning should be returned, together with a counterexample.

Low-level API

The low-level API is as follows:

  • solc.lowlevel.compileSingle: the original entry point, supports only a single file
  • solc.lowlevel.compileMulti: this supports multiple files, introduced in 0.1.6
  • solc.lowlevel.compileCallback: this supports callbacks, introduced in 0.2.1
  • solc.lowlevel.compileStandard: this works just like compile above, but is only present in compilers after (and including) 0.4.11

For examples how to use them, please refer to the README of the above mentioned solc-js releases.

Note: These low-level functions remain available for compatibility reasons. However, they were superseded by the compile() function and are no longer required. Starting from version 0.5.0+commit.1d4f565a, the functions compileSingle, compileMulti, and compileCallback are always null when using newer solc binary versions. It is recommended to use the latest release of solc-js, but it should also handle all the older solc binaries down to 0.1.x.

Using with Electron

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
  }
});

Using a Legacy Version

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")).

Using the Latest Development Snapshot

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
  } else {
    // NOTE: Use `solcSnapshot` here with the same interface `solc` has
    // For example:
    const output = solcSnapshot.compile(/* ... */)
  }
});

The version must be in the long format. Thus, if you would like to use version v0.8.17 you need to include the commit hash of the release. You can extract the long version string for each version from the publicly available release list.

solc.loadRemoteVersion('v0.8.17+commit.8df45f5f', function(err, solcSnapshot) { /* ... */ });

Linking Bytecode

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...' });

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);

Updating the ABI

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}]

Formatting old JSON assembly output

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)

Browser Usage

Compilation is generally a long-running and resource intensive task that cannot reasonably be performed in the main thread of the browser. Some browsers even dissallow synchronous compilation on the main thread if the module is larger than 4KB. Thus, the only supported way to use solc in a web browser is through a web worker.

Loading solc with web workers

Web Workers allow you to run javascript in the background in the browser, letting the browser's main thread free to do whatever it needs to do. Please, see the minimal example of how to use solc with web workers below or check out this repository for a full demo.

  • index.html
<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
</head>

<body>
	<script>
		var worker = new Worker('./dist/bundle.js');
		worker.addEventListener('message', function (e) {
			console.log(e.data.version)
		}, false);

		worker.postMessage({})
	</script>
</body>

</html>
  • worker.js:
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)

More Repositories

1

go-ethereum

Official Go implementation of the Ethereum protocol
Go
45,440
star
2

solidity

Solidity, the Smart Contract Programming Language
C++
22,171
star
3

wiki

The Ethereum Wiki
14,759
star
4

EIPs

The Ethereum Improvement Proposal repository
Python
12,522
star
5

mist

[DEPRECATED] Mist. Browse and use Ðapps on the Ethereum network.
JavaScript
7,428
star
6

web3.py

A python interface for interacting with the Ethereum blockchain and ecosystem.
Python
4,701
star
7

ethereum-org-website

Ethereum.org is a primary online resource for the Ethereum community.
Markdown
4,230
star
8

aleth

Aleth – Ethereum C++ client, tools and libraries
C++
3,960
star
9

consensus-specs

Ethereum Proof-of-Stake Consensus Specifications
Python
3,388
star
10

pyethereum

Next generation cryptocurrency network
2,667
star
11

remix-project

Remix is a browser-based compiler and IDE that enables users to build Ethereum contracts with Solidity language and to debug transactions.
TypeScript
2,277
star
12

remix-ide

Documentation for Remix IDE
2,227
star
13

py-evm

A Python implementation of the Ethereum Virtual Machine
Python
2,188
star
14

ethereumj

DEPRECATED! Java implementation of the Ethereum yellowpaper. For JSON-RPC and other client features check Ethereum Harmony
Java
2,166
star
15

research

Python
1,708
star
16

yellowpaper

The "Yellow Paper": Ethereum's formal specification
TeX
1,598
star
17

fe

Emerging smart contract language for the Ethereum blockchain.
Rust
1,561
star
18

pm

Project Management: Meeting notes and agenda items
Python
1,473
star
19

remix

This has been moved to https://github.com/ethereum/remix-project
JavaScript
1,174
star
20

dapp-bin

A place for all the ÐApps to live
JavaScript
1,007
star
21

remix-desktop

Remix IDE desktop
JavaScript
1,000
star
22

devp2p

Ethereum peer-to-peer networking specifications
JavaScript
910
star
23

execution-apis

Collection of APIs provided by Ethereum execution layer clients
Io
874
star
24

kzg-ceremony

Resources and documentation related to the ongoing Ethereum KZG Ceremony.
812
star
25

execution-specs

Specification for the Execution Layer. Tracking network upgrades.
Python
773
star
26

evmone

Fast Ethereum Virtual Machine implementation
C++
756
star
27

sourcify

Decentralized Solidity contract source code verification service
TypeScript
731
star
28

casper

Casper contract, and related software and tests
Python
685
star
29

js-ethereum-cryptography

Every cryptographic primitive needed to work on Ethereum, for the browser and Node.js
TypeScript
659
star
30

meteor-dapp-wallet

This is an archived repository of one of the early Ethereum wallets.
JavaScript
598
star
31

btcrelay

Ethereum contract for Bitcoin SPV: Live on https://etherscan.io/address/0x41f274c0023f83391de4e0733c609df5a124c3d4
Python
585
star
32

solidity-examples

Loose collection of Solidity example code
Solidity
531
star
33

staking-deposit-cli

Secure key generation for deposits
Python
507
star
34

tests

Common tests for all Ethereum implementations
Python
506
star
35

webthree-umbrella

Former home of cpp-ethereum (Oct 2015 to Aug 2016)
492
star
36

sharding

Sharding manager contract, and related software and tests
Python
477
star
37

trinity

The Trinity client for the Ethereum network
Python
475
star
38

homebrew-ethereum

Homebrew Tap for Ethereum
Ruby
468
star
39

ethereum-org

[ARCHIVED] ethereum.org website from 2016-2019. See https://github.com/ethereum/ethereum-org-website for current version.
HTML
402
star
40

lahja

Lahja is a generic multi process event bus implementation written in Python 3.6+ to enable lightweight inter-process communication, based on non-blocking asyncio
Python
389
star
41

solc-bin

This repository contains current and historical builds of the Solidity Compiler.
JavaScript
379
star
42

hive

Ethereum end-to-end test harness
Go
371
star
43

serpent

C++
360
star
44

evmlab

Utilities for interacting with the Ethereum virtual machine
Python
352
star
45

eth-tester

Tool suite for testing ethereum applications.
Python
334
star
46

trin

An Ethereum portal client: a json-rpc server with nearly instant sync, and low CPU & storage usage
Rust
330
star
47

evmc

EVMC – Ethereum Client-VM Connector API
C
316
star
48

populus

The Ethereum development framework with the most cute animal pictures
316
star
49

annotated-spec

Vitalik's annotated eth2 spec. Not intended to be "the" annotated spec; other documents like Ben Edgington's https://benjaminion.xyz/eth2-annotated-spec/ also exist. This one is intended to focus more on design rationale.
310
star
50

beacon-APIs

Collection of RESTful APIs provided by Ethereum Beacon nodes
HTML
301
star
51

eth-utils

Utility functions for working with ethereum related codebases.
Python
300
star
52

homestead-guide

Python
291
star
53

eth2.0-pm

ETH2.0 project management
Python
261
star
54

staking-launchpad

The deposit launchpad for staking on Ethereum 🦏
TypeScript
257
star
55

portal-network-specs

Official repository for specifications for the Portal Network
JavaScript
256
star
56

ropsten

Ropsten public testnet PoW chain
Jupyter Notebook
255
star
57

eth-account

Account abstraction library for web3.py
Python
245
star
58

cbc-casper

Python
226
star
59

eth-abi

Ethereum ABI utilities for python
Python
223
star
60

remix-live

Live deployment of the remix IDE
JavaScript
221
star
61

act

Smart contract specification language
Haskell
214
star
62

ERCs

The Ethereum Request for Comment repository
Solidity
212
star
63

hevm

symbolic EVM evaluator
Haskell
208
star
64

beacon_chain

Python
208
star
65

emacs-solidity

The official solidity-mode for EMACS
Emacs Lisp
201
star
66

moon-lang

Minimal code-interchange format
MoonScript
192
star
67

remixd

remix server
TypeScript
182
star
68

go-verkle

A go implementation of Verkle trees
Go
181
star
69

ethash

C
181
star
70

browser-solidity

Fomer location of remix-ide => https://github.com/ethereum/remix-ide
JavaScript
178
star
71

py_ecc

Python implementation of ECC pairing and bn_128 and bls12_381 curve operations
Python
175
star
72

py-solc

Python wrapper around the solc Solidity compiler.
Python
174
star
73

grid

[DEPRECATED] Download, configure, and run Ethereum nodes and tools
JavaScript
173
star
74

pos-evolution

Evolution of the Ethereum Proof-of-Stake Consensus Protocol
167
star
75

mix

The Mix Ethereum Dapp Development Tool
JavaScript
164
star
76

evmjit

The Ethereum EVM JIT
C++
163
star
77

eth-keys

A common API for Ethereum key operations.
Python
156
star
78

builder-specs

Specification for the external block builders.
HTML
156
star
79

remix-plugin

TypeScript
153
star
80

solidity-underhanded-contest

Website for the Underhanded Solidity Contest
Solidity
151
star
81

meteor-dapp-whisper-chat-client

JavaScript
150
star
82

rig

Robust Incentives Group
HTML
117
star
83

public-disclosures

117
star
84

economic-modeling

Python
117
star
85

kzg-ceremony-specs

Specs for Ethereum's KZG Powers of Tau Ceremony
107
star
86

snake-charmers-tactical-manual

Development *stuff* for the Snake Charmers EF team
107
star
87

node-crawler

Attempts to crawl the Ethereum network of valid Ethereum execution nodes and visualizes them in a nice web dashboard.
Go
106
star
88

py-trie

Python library which implements the Ethereum Trie structure.
Python
100
star
89

py-wasm

A python implementation of the web assembly interpreter
Python
99
star
90

remix-workshops

Solidity
97
star
91

py-geth

Python wrapping for running Go-Ethereum as a subprocess
Python
97
star
92

pyrlp

The python RLP serialization library
Python
96
star
93

swarm-dapps

Swarm Đapp Examples
JavaScript
96
star
94

remix-vscode

Remix VS Code extension
TypeScript
95
star
95

eth-hash

The Ethereum hashing function, keccak256, sometimes (erroneously) called sha256 or sha3
Python
95
star
96

dapp-styles

HTML
94
star
97

ens-registrar-dapp

Registrar DApp for the Ethereum Name Service
JavaScript
94
star
98

c-kzg-4844

Minimal 4844 version of c-kzg
Nim
93
star
99

retesteth

testeth via RPC. Test run, generation by t8ntool protocol
C++
93
star
100

pyethsaletool

Python
85
star