3rdstage's Wiki



  • Ethash : PoW algorithm for Ethereum 1.0


  • EIPs (Ethereum Improvement Proposals)
    • describe standards for the Ethereum platform, including core protocol specifications, client APIs, and contract standards.
  • EIP List
EIP/ERC Title Description Category Status Remarks Related
EIP-20 Token Standard A standard interface for tokens. ERC Final totalSupply, balanceOf, transfer, transferFrom, approve, ... ERC-2612
EIP-55 Mixed-case checksum address encoding ERC Final
EIP-100 Change difficulty adjustment to target mean block time including uncles the formula to compute the difficulty of a block Core Final
EIP-101 Serenity Currency and Crypto Abstraction Accounts now have only two fields in their RLP encoding: code and storage Core Draft Ethereum 2.0
EIP-155 Simple replay attack protection provide a way to send transactions that work on Ethereum without working on ETC or the Morden testnet. Core Final
EIP-165 Standard Interface Detection Creates a standard method to publish and detect what interfaces a smart contract implements. ERC Final ERC-1820
EIP-191 Signed Data Standard Proposes a specification about how to handle signed data in Ethereum contracts. ERC Final
EIP-712 Ethereum typed structured data hashing and signing a standard for hashing and signing of typed structured data as opposed to just bytestrings. Interface Draft ABI, RLP, keccak256, eth_signTypedData
EIP-721 Non-Fungible Token Standard A standard interface for non-fungible tokens, also known as deeds. ERC Final supportsInterface(bytes4 _if)
EIP-725 Proxy Account A standard interface for a simple proxy account. ERC Draft execute(...), getData(bytes32 key), setData(bytes32 key, bytes value)
EIP-777 Token Standard standard interfaces and behaviors for token contracts. ERC Final operators, send/receive hooks ERC-1820
EIP-1066 Status Codes Broadly applicable status codes for smart contracts. ERC Draft
EIP-1102 Opt-in account exposure describes a communication protocol between dapps and Ethereum-enabled DOM environments that allows the Ethereum-enabled DOM environment to choose what information to supply the dapp with and when. Interface Draft eth_requestAccounts
EIP-1155 Multi Token Standard A standard interface for contracts that manage multiple token types. ERC Final
EIP-1193 Ethereum Provider JavaScript API A JavaScript Ethereum Provider API for consistency across clients and applications. Interface Last Call Provider.request()
EIP-1271 Standard Signature Validation Method for Contracts a standard way for any contracts to verify whether a signature on a behalf of a given contract is valid ERC Final isValidSignature(bytes32 hash, bytes signature)
EIP-1474 Remote procedure call specification defines a standard set of remote procedure call methods that an Ethereum node should implement. Interface Draft JSON-RPC, Error Codes, Methods
EIP-1559 Fee market change for ETH 1.0 chain A transaction pricing mechanism that includes fixed-per-block network fee that is burned and dynamically expands/contracts block sizes to deal with transient congestion. Core Review London hard fork EIP-2718
EIP 1820 Pseudo-introspection Registry Contract defines a universal registry smart contract where any address (contract or regular account) can register which interface it supports and which smart contract is responsible for its implementation. ERC Final ERC-820, ERC-165
EIP-2309 ERC-721 Consecutive Transfer Extension A standardized event emitted when creating/transferring one, or many non-fungible tokens using consecutive token identifiers. ERC Final ERC-721
EIP-2612 permit – 712-signed approvals A function permit extending ERC-20 which allows for approvals to be made via secp256k1 signatures. ERC Draft ERC-20, ERC-712
EIP-2711 Sponsored, expiring and batch transactions Creates a new transaction type that supports sponsored transactions (separate gas payer from sender), batch transactions (multiple transactions executed in sequence), and expiring transactions (transactions which are not valid after a certain timestamp) Core Draft EIP-2718
EIP-2718 Typed Transaction Envelope Defines a new transaction type that is an envelope for future transaction types. Core Final Berlin hard fork
EIP-2771 Secure Protocol for Native Meta Transactions defines a minimal contract-level protocol that a compliant Recipient contract needs to support in order to be capable of accepting a meta transaction through a compliant Forwarder contract that it trusts to help it identify the address of the Transaction Signer. ERC Draft
EIP-3091 Block Explorer API Routes Standard API Routes for Blockchain explorers Interface Draft /block/{BLOCK_HASH_OR_HEIGHT}, /tx/{TX_HASH}, /address/{ACCOUNT_ADDRESS}, /token/{TOKEN_ADDRESS}
EIP-4400 ERC-721 Consumable Extension Defines standard functions outlining a `consumer` role for instance(s) of ERC-721 ERC Final consumerOf(uint256 tokenId) view external returns (address)
EIP-4626 Tokenized Vault Standard Allows for the implementation of a standard API for tokenized Vaults representing shares of a single underlying ERC-20 token ERC Final ERC-20
  • ERC-725 Alliance
    • The home of ERC 725, a proposed standard for blockchain-based identity authored by Fabian Vogelsteller, creator of the ERC 20 standard and Web3.js.
EIPs by Topic
  • Common smart contract
  • Fungible token related
  • Non-fungible token related
  • Token related
  • Transaction related
  • JSON-RPC related
  • JavaScript API related
  • ETH2 related
  • Hardfork Meta

EIP Candidates

ERC Title Description Category Remarks
EIP 677 transferAndCall Token Standard Adds a new function to ERC20 token contracts, transferAndCall which can be called to transfer tokens to a contract and then call the contract with the additional data provided. ERC ERC 20
EIP 734 Key Manager A contract for key management of a blockchain proxy account. ERC ERC 725
EIP 735 Claim Holder Describes standard functions for adding, removing and holding of claims. ERC ERC 725, ERC 734
EIP 780 Ethereum Claims Registry Describes a proposal for an Ethereum Claims Registry (ECR) which allows persons, smart contracts, and machines to issue claims about each other, as well as self issued claims. ERC ERC 735
EIP 1024 Add web3.eth.encrypt and web3.eth.decrypt functions to JSON-RPC Proposes a cross-client method for requesting encryption/decryption. Interface
EIP 1238 Non-transferrable tokens (Badges) Defines a set of standard APIs allowing the identification of statements (called badges) attributed to a public key, such that different dapps and smart contract can use to filter users or to provide user with different badges different experiences. ERC
ERC 1400 Security Token Standard Represents a library of standards for security tokens on Ethereum. ERC EIPs/issues/1411
ERC 1404 Simple Restricted Token Standard An open source standard for security tokens ERC
ERC-1776 Native Meta Transactions allows users that simply own ERC20 or ERC777 (ERC1155 could be added too) tokens to perform operations on the ethereum network without needing to own ether themselves by letting a third party, the relayer, the responsibility to execute a transaction on the ethereum network carrying the desired operations ERC
                            +--- Transferrable ---------- EIP 20
       +--- Fungible -------+
       |                    |
       |                    +--- Non Transferrable ----- 
       |                    +--- Transferable ---------- EIP 721
       |                    |
       +--- Non Fungible ---+
                            +--- Non Transferrable ----- ERC 1238, ERC 735


  • Ether
    • 1 wei = 10-18 ether
    • 1 Gwei (shannon) = 109 wei = 10-9 ether
  • Account Types, Gas, and Transactions
    • Externally Owned Account, Contract Account, Transaction, Message, Gas
  • What is coinbase? (Apr 16 '16)
  • The address of that contract is not the zero address but an address derived from the sender and its number of transactions sent (the “nonce”).
  • The gas price is a value set by the creator of the transaction, who has to pay gas_price * gas up front from the sending account. If some gas is left after the execution, it is refunded to the creator in the same way.
  • The Ethereum Virtual Machine has three areas where it can store data- storage, memory and the stack
  • Mining
  • How to Mine Ethereum.
    • Once you’ve successfully mined a block, you are entitled to receive a three ETH reward. Along with the reward, miners receive fees associated with the transaction.

Keys and Address

Element Size Remarks
Bits Bytes Hex Characters
Private Key 256 32 64 a randomly selected positive integer (represented as a byte array of length 32 in big-endian form) in the range [1, secp256k1n − 1]
Public Key 512 64 128 a byte array of size 64 (formed from the concatenation of two positive integers each < 2 256)
Address 160 20 40 the right most 160-bits of the Keccak hash of the corresponding ECDSA public key.


A : address
pr : private key
KEC : Keccak-256 hash function

  • secp256k1 domain parameters
Parameter Name Value Decimal Value Remarks
P underlying field size 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F 115792089237316195423570985008687907853269984665640564039457584007908834671663 2256 - 232 - 977
a curve parameter 0 0
b curve parameter 7 7
Gx generator(base point) x coordinate 0x79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy generator(base point) y coordinate 0x483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8 32670510020758816978083085130507043184471273380659243275938904335757337482424
n order of generator 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141 115792089237316195423570985008687907852837564279074904382605163141518161494337 secp256k1n
h cofactor 1 1
Account State
Field Symbol Description Remarks
nonce σ[a]n A scalar value equal to the number of transactions sent from this address or, in the case of accounts with associated code, the number of contract-creations made by this account.
balance σ[a]b A scalar value equal to the number of Wei owned by this address.
storageRoot σ[a]s A 256-bit hash of the root node of a Merkle Patricia tree that encodes the storage contents of the account.
codeHash σ[a]c The hash of the EVM code of this account—this is the code that gets executed should this address receive a message call. immutable


A transaction (formally, T) is a single cryptographically-signed instruction constructed by an actor externally to the scope of Ethereum.

Field Symbol Description Remarks
nonce Tn A scalar value equal to the number of transactions sent by the sender
gasPrice Tp A scalar value equal to the number of Wei to be paid per unit of gas for all computation costs incurred as a result of the execution of this transaction
gasLimit Tg A scalar value equal to the maximum amount of gas that should be used in executing this transaction. This is paid up-front, before any computation is done and may not be increased
to Tt The 160-bit address of the message call’s recipient or, for a contract creation transaction, ∅
value Tv A scalar value equal to the number of Wei to be transferred to the message call’s recipient or, in the case of contract creation, as an endowment to the newly created account.
v, r, s Tw, Tr, Ts Values corresponding to the signature of the transaction and used to determine the sender of the transaction.
init Ti An unlimited size byte array specifying the EVM-code for the account initialisation procedure. a contract creation transaction only
data Td An unlimited size byte array specifying the input data of the message call. a message call transaction only


Transaction Signing

Library API Description Remarks
JSON-RPC eth_signTransaction(tx) signs a transaction that can be submitted to the network at a later time using with eth_sendRawTransaction
web3.j web3.eth.signTransaction(tx, address [, callback]) Signs a transaction.
web3.eth.accounts.signTransaction(tx, privateKey [, callback]) Signs an Ethereum transaction with a given private key.
Element Symbol Property Remarks
private key pr a randomly selected positive integer
public key pu
signature v, r, s

address A(pr) the right most 160-bits of the Keccak hash of the corresponding ECDSA public key
field size secp256k1n 115792089237316195423570985008687907852837564279074904382605163141518161494337 2256 - 232 - 977
Library API Description Formula Remarks
JSON-RPC eth_sign(address, message) calculates an Ethereum specific signature sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))) -> [v:bytes1, r:bytes32, s:bytes32]
Solidity ecrecover(hash, v, r, s) recover the address associated with the public key from elliptic curve signature
OpenZeppelin ECDSA.toEthSignedMessageHash()
 * Should be called to get hex representation (prefixed by 0x) of utf8 string
 * @method utf8ToHex
 * @param {String} str
 * @returns {String} hex representation of input string
var utf8ToHex = function(str) {
    str = utf8.encode(str);
    var hex = "";

    // remove \u0000 padding from either side
    str = str.replace(/^(?:\u0000)*/,'');
    str = str.split("").reverse().join("");
    str = str.replace(/^(?:\u0000)*/,'');
    str = str.split("").reverse().join("");

    for(var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i)
        // if (code !== 0) {
        var n = code.toString(16);
        hex += n.length < 2 ? '0' + n : n;
        // }

    return "0x" + hex;
Legacy Transaction Signing
  • Transaction signing in practice
    1. Create a transaction data structure, containing 9 fields: nonce, gasPrice, gasLimit, to, value, data, chainID, 0, 0
    2. Produce an RLP-encoded serialized message of the transaction data structure
    3. Compute the Keccak256 hash of this serialized message
    4. Compute the ECDSA signature, signing the hash with the originating EOA’s private key.
    5. Append the ECDSA signature’s computed v, r, and s values to the transaction.
  • Transaction signature

Signature = Fsig(Fkeccak256(m), k) = (r, s)

m : encoded transaction
k : signer's private key
Fkeccak256 : Keccak-256 hash function
Fsig : Signing algorithm

  • Ethereum Transaction Signing (Legacy)
    • 2 times serialization using RLP : each before and after signing
    • sign hashed message
// https://eips.ethereum.org/EIPS/eip-155
tx = [nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0]
serialized tx = RLP(tx)     // signing data (data to sign)
signature = (r, s, v) = sign(keccak256(RLP(tx)))
serialized signed tx = RLP([nonce, gasPrice, gasLimit, to, value, data, chainId, r, s])
Item Fomula Remarks
Transaction (Message)

Transaction Hash (Message Hash)
Signed Transaction r = , s =
  • Web3.js transaction siging codes
Method Remarks
Accounts.prototype.signTransaction = function signTransaction(tx, privateKey, callback) web3.js
static TransactionFactory.fromTxData() @ethereumjs/tx
Transaction.getMessageToSign() RLP encoding and Keccak hashing before ECDSA signing
rlphash ethereumjs-util
ecsign ethereumjs-util
Transaction._processSignature(v, r, s) EIP-155
Transaction.serialize() RLP encoding after ECDSA signing
rlp.encode() ethereumjs-util
keccak256() transaction hash !! web3-utils (? why not from ethereumjs)
  • Web3j transaction signing codes
Method Remarks
org.web3j.tx.RawTransactionManager.sendTransaction() just delegating
org.web3j.crypto.RawTransaction.createTransaction() just delegating
org.web3j.crypto.transaction.type.LegacyTransaction.createTransaction() static factory method
org.web3j.crypto.transaction.type.LegacyTransaction.LegacyTransaction() constructor, remove hexa prefix for data field
org.web3j.crypto.RawTransaction.RawTransaction() constructor
org.web3j.tx.RawTransactionManager.sign() check chain ID


Transaction Receipt

Field Type Size Description Remarks
blockHash String 32 Bytes hash of the block where this transaction was in.
blockNumber Number block number where this transaction was in.
transactionHash String 32 Bytes hash of the transaction.
transactionIndex Number integer of the transactions index position in the block.
from String 20 Bytes address of the sender.
to String 20 Bytes address of the receiver. null : a contract creation transaction.
cumulativeGasUsed Number total amount of gas used when this transaction was executed in the block.
gasUsed Number the amount of gas used by this specific transaction alone.
contractAddress String the contract address created, if the transaction was a contract creation, otherwise null.
logs Array Array of log objects, which this transaction generated.
status String '0x0' indicates transaction failure , '0x1' indicates transaction succeeded.
Component Description Remark
address the address of the contract (intrinsically provided by Ethereum)
topics[0] keccak(event-signature) not generated for anonymous event
topics[n] abi_encode(event-args[indexed][n - 1]) indexed arguments
data abi_encode(join(event-args[non-indexed])) non-indexed arguments

Typed Transaction

EIP Title Transaction Type Transaction Payload
EIP-1559 Fee market change for ETH 1.0 chain 0x02 RLP([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList, signatureYParity, signatureR, signatureS])
EIP-2711 Sponsored, expiring and batch transactions 0x02 RLP([...SenderPayload, ...SenderSignature, ...GasPayerPayload, ...GasPayerSignature])
ERC-1776 Native Meta Transactions

Meta Transaction

  • Ethereum Meta Transactions : Our Take (Jan 17, 2020)
    • Meta transactions are a type of transaction which is signed by a given key pair, but is funded by a “relay”. The relay submits the transaction to the network as if they are the sender, and pay the gas fee. The destination contract of the transaction can determine the original user, their intent and can process the contract call accordingly.
bytes32 h = keccak256(_from,_to,_value,_fee,nonce);
if(_from != ecrecover(h,_v,_r,_s)) revert();
let msg = web3.sha3(_from,_to,_value,_fee,nonce)
let signature = web3.eth.sign(_from, msg)


Ethereum Block Structure
Block Header
Field Symbol Description Remarks
parentHash Hp The Keccak 256-bit hash of the parent block’s header, in its entirety.
ommersHash Ho The Keccak 256-bit hash of the ommers list portion of this block.
beneficiary Hc The 160-bit address to which all fees collected from the successful mining of this block be transferred.
stateRoot Hr The Keccak 256-bit hash of the root node of the state trie, after all transactions are executed and finalisations applied;
transactionsRoot Ht The Keccak 256-bit hash of the root node of the trie structure populated with each transaction in the transactions list portion of the block.
receiptsRoot He The Keccak 256-bit hash of the root node of the trie structure populated with the receipts of each transaction in the transactions list portion of the block.
logsBloom Hb The Bloom filter composed from indexable information (logger address and log topics) contained in each log entry from the receipt of each transaction in the transactions list.
difficulty Hd A scalar value corresponding to the difficulty level of this block. This can be calculated from the previous block’s difficulty level and the timestamp.
number Hi A scalar value equal to the number of ancestor blocks. 0 for genesis block
gasLimit Hl A scalar value equal to the current limit of gas expenditure per block
gasUsed Hg A scalar value equal to the total gas used in transactions in this block.
timestamp Hs A scalar value equal to the reasonable output of Unix’s time() at this block’s inception.
extraData Hx An arbitrary byte array containing data relevant to this block. This must be 32 bytes or fewer.
mixHash Hm A 256-bit hash which, combined with the nonce, proves that a sufficient amount of computation has been carried out on this block.
nonce Hn A 64-bit value which, combined with the mixhash, proves that a sufficient amount of computation has been carried out on this block.
  • ommer (uncle) block
    • The term "ommer" is the preferred gender-neutral term for the sibling of a parent block, but this is also sometimes referred to as an "uncle".

World State

  • Diving into Ethereum’s world state (Feb 11, 2018)
    • There is one, and one only, global state trie in Ethereum.
    • A storage trie is where all of the contract data lives.
    • Each Ethereum account has its own storage trie.
    • Transaction trie — one per block
    • Ethereum’s Rust client Parity uses rocksdb. Whereas Ethereum’s Go, C++ and Python clients all use leveldb.

Merkle Patricia Tree

  • Trie
    • an ordered tree data structure used to store a dynamic set or associative array where the keys are usually strings.
    • Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated.
  • Radix Tree
    • a data structure that represents a space-optimized trie (prefix tree) in which each node that is the only child is merged with its parent.


def hashimoto(header, nonce, full_size, dataset_lookup):
    n = full_size / HASH_BYTES
    mixhashes = MIX_BYTES / HASH_BYTES
    # combine header+nonce into a 64 byte seed
    s = sha3_512(header + nonce[::-1])
    # start the mix with replicated s
    mix = []
    for _ in range(MIX_BYTES / HASH_BYTES):
    # mix in random dataset nodes
    for i in range(ACCESSES):
        p = fnv(i ^ s[0], mix[i % w]) % (n // mixhashes) * mixhashes
        newdata = []
        for j in range(MIX_BYTES / HASH_BYTES):
            newdata.extend(dataset_lookup(p + j))
        mix = map(fnv, mix, newdata)
    # compress mix
    cmix = []
    for i in range(0, len(mix), 4):
        cmix.append(fnv(fnv(fnv(mix[i], mix[i+1]), mix[i+2]), mix[i+3]))
    return {
        "mix digest": serialize_hash(cmix),
        "result": serialize_hash(sha3_256(s+cmix))

def hashimoto_light(full_size, cache, header, nonce):
    return hashimoto(header, nonce, full_size, lambda x: calc_dataset_item(cache, x))

def hashimoto_full(full_size, dataset, header, nonce):
    return hashimoto(header, nonce, full_size, lambda x: dataset[x])

def mine(full_size, dataset, header, difficulty):
    # zero-pad target to compare with hash on the same digit
    target = zpad(encode_int(2**256 // difficulty), 64)[::-1]
    from random import randint
    nonce = randint(0, 2**64)
    while hashimoto_full(full_size, dataset, header, nonce) > target:
        nonce = (nonce + 1) % 2**64
    return nonce
  • JavaScript code snippet to calculate target in hexa with given difficulty
    • > (2n**256n / 24091770185844n).toString(16).padStart(64, '0') // difficulty: 24091770185844


  • What is Gas?
    • If you want to pay less and are lowering the gas limit below the recommended gas limit, then this will not work. Instead, try lowering the gas price.
  • Gas and Gas Price
    • transaction gas limit : max amount of gas your willing to use for your transaction, set by you
    • block gas limit : max amount of gas allowed in a block, set by the network
  • What is Ethereum Gas?
Item Full Name Description Remarks
`base fee` `base fee per gas` Move up or down each block according to a formula which is a function of gas used in parent block and gas target (block gas limit divided by elasticity multiplier) of parent block will be burned
`priority fee` `max priority fee per gas` Maximum fee per gas they are willing to give to miners to incentivize them to include their transaction
`max fee` `max fee per gas` The maximum fee per gas they are willing to pay total
transaction fee = (base fee + priority fee) * gas used

max fee > base fee + priority fee

gas price = base fee + priority fee
  • What is EIP-1559? How Will It Change Ethereum? (June 22, 2021)
    • During periods of high network congestion, the base fee will adjust by 12.5% depending how much demand surpasses the ideal gas limit per block until that demand abates. Instead of a first-price auction, users will have a better sense of how congested the network is by how high the base fee is. If it is too congested, the user can either pay that price or not, like they would buy an item at a store. Or, they submit a lower fee and wait for the price to go down in the future.


Call vs Send
Library API Description Remarks
JSON-RPC eth_call Executes a new message call immediately without creating a transaction on the block chain. No signing, 0 gas
eth_sendTransaction Creates new message call transaction or a contract creation, if the data field contains code.
eth_sendRawTransaction Creates new message call transaction or a contract creation for signed transactions. single parameter for the signed transaction data.
web3js 1.2 methods.myMethod.call Will call a “constant” method and execute its smart contract method in the EVM without sending any transaction. Note calling can not alter the smart contract state. constant function -> view function in Solidity 0.5
methods.myMethod.send Will send a transaction to the smart contract and execute its method. Note this can alter the smart contract state.
Typed Structured Data Signing (EIP-712)

Hard Forks

Fork Date Block # Meta Spec Included EIPs / Features Remarks
Gray Glacier ~ 2022-06-29 15,050,000 gray-glacier.md
Arrow Glacier 2021-12-09 13,773,000 arrow-glacier.md
Altair 2021-10-27 Beacon Chain
London 2021-08-05 12,965,000 london.md
Berlin 2021-04-15 12,244,000 EIP-2070 berlin.md
Muir Glacier 2020-01-02 9,200,000 EIP-2387 muir-glacier.md
Istanbul 2019-12-07 9,069,000 EIP-1679 istanbul.md
Metropolis: Constantinople 2019-02-28 7,280,000 EIP-1013 constantinople.md
Metropolis: Byzantium 2017-10-16 4,370,000 EIP-609 byzantium.md
Spurious Dragon 2016-11-22 2,675,000 EIP-607 spurious-dragon.md
Tangerine Whistle 2016-10-18 2,463,000 EIP-608 tangerine-whistle.md DDoS resistance
DAO Fork 2016-06-20 1,192,000 EIP-779 dao-fork.md
  • To restore $50M stolen in DAO hack
Ethereum Classic
Homestead 2016-03-14 1,150,000 EIP-606 homestead.md Solidity, Mist wallet
Frontier 2015-06-30 0
  • The 1st official public mainnet
Block Reward, Gas
Olympic 2015-05-09 N/A
  • The final PoC testnet


Unlike memory, storage is a persistent area and can only be addressed by words. It is a key-value mapping of 2²⁵⁶ slots of 32 bytes each. A contract can neither read nor write to any storage apart from its own.

Solidity will automatically map every defined state variable of your contract to a slot in storage. The strategy is fairly simple — statically sized variables (everything except mappings and dynamic arrays) are laid out contiguously in storage starting from position 0.

For dynamic arrays, this slot (p) stores the length of the array and its data will be located at the slot number that results from hashing p(keccak256(p)). For mappings, this slot is unused and the value corresponding to a key k will be located at keccak256(k,p).


Object Description Properties Remarks
transaction from, to, gas, gasPrice, value, data, nonce
transaction receipt
JSON-RPC Method Description JavaScript API Python API
eth_chainId a single string result for an integer value in hexadecimal format, describing the currently configured CHAIN_ID value used for signing replay-protected transactions web3.eth.getChainId() web3.eth.chain_id
eth_protocolVersion the current ethereum protocol version web3.eth.getProtocolVersion() web3.eth.protocolVersion
eth_blockNumber the number of most recent block web3.eth.getBlockNumber() web3.eth.blockNumber
eth_getBlockByNumber information about a block by block number. web3.eth.getBlock() web3.eth.get_block()
eth_getBlockTransactionCountByNumber the number of transactions in a block matching the given block number. web3.eth.getBlockTransactionCount() web3.eth.get_block_transaction_count()
eth_getTransactionByBlockNumberAndIndex information about a transaction by block number and transaction index position. web3.eth.getTransactionByBlock()
eth_gasPrice the current gas price oracle determined by the last few blocks median gas price. web3.eth.getGasPrice() web3.eth.gasPrice
web3_clientVersion the current client version web3.eth.getNodeInfo() web3.clientVersion
eth_coinbase the coinbase address to which mining rewards will go web3.eth.getCoinbase() web3.eth.coinbase
eth_syncing an object with data about the sync status or false web3.eth.isSyncing() web3.eth.syncing
eth_mining whether the node is mining or not web3.eth.isMining() web3.eth.mining
eth_hashrate the number of hashes per second that the node is mining with web3.eth.getHashrate() web3.eth.hashrate
eth_accounts a list of addresses owned by client web3.eth.getAccounts() web3.eth.accounts
eth_getBalance the balance of the account of given address web3.eth.getBalance() web3.eth.get_balance()
eth_getTransactionCount the number of transactions sent from an address. (nonce) web3.eth.getTransactionCount() web3.eth.getTransactionCount()
eth_getCode code at a given address web3.eth.getCode() web3.eth.getCode()
eth_getStorageAt the value from a storage position at a given address. web3.eth.getStorageAt() web3.eth.get_storage_at()
eth_sign calculates an Ethereum specific signature web3.eth.sign() web3.eth.sign()
eth_signTransaction signs a transaction that can be submitted to the network at a later time. web3.eth.signTransaction() web3.eth.signTransaction()
eth_sendTransaction creates new message call transaction or a contract creation web3.eth.sendTransaction() web3.eth.sendTransaction()
eth_sendRawTransaction creates new message call transaction or a contract creation for signed transactions. web3.eth.sendSignedTransaction() web3.eth.sendRawTransaction()
eth_call executes a new message call immediately without creating a transaction on the block chain. web3.eth.call() we3.eth.call()
net_version the current network id web3.eth.net.getId() web3.net.version
net_peerCount number of peers currently connected to the client. web3.eth.net.getPeerCount() web3.net.peer_count
net_listening whether or not client is actively listening for network connections. web3.eth.net.isListening() web3.net.listening
web3_sha3 Keccak-256 (not the standardized SHA3-256) of the given data. web3.utils.sha3() Web3.keccak()
  • Looking around the local client using JSON RPC API
$ # Get the client coinbase address. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_coinbase)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":11}'

$ # Get the client version. (https://github.com/ethereum/wiki/wiki/JSON-RPC#web3_clientversion)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":21}'

$ # Get the Ethereum protocol version. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_protocolversion)
$ # For more on Ethereum protocol version, refer https://github.com/ethereum/devp2p/blob/master/caps/eth.md
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_protocolVersion","params":[],"id":31}'

$ # Get the number of peers currently connected to the client. (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_peercount)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":41}'

$ # Check whether the client is mining or not. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_mining)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_mining","params":[],"id":51}'

$ # Get a list of addresses owned by client (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_accounts)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":61}'

$ # Get the network ID. (https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_version","params":[],"id":71}'

$ # Get the current price per gas in wei. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gasprice)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":81}'

$ # Get the number of most recent block. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_blocknumber)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":91}'

$ # Get the gas limit of the most recent block
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["latest", false],"id":92}' | jq .result.gasLimit

$ # Get information about a block by block number. (https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getblockbynumber)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[0, false],"id":101}' | jq .  # block 0
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x1", false],"id":102}' | jq .  # block 1
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":[2, false],"id":103}' | jq .  # block 1
#! /bin/bash

function print_help {
  echo "Executes some basic Ethereum JSON RPC method to check the specified Ethereum client."
  echo ""
  echo "Usage:"
  echo "  $ ${0##*/}  [-h | --help | rpc_addr]"
  echo ""
  echo "If '-h' or '--help' is given, only display this help and quit."
  echo "If rpc_addr is given, execute some basic Ethereum JSON RPC "
  echo "methods to the specified address."
  echo "If no argument is given, excute the same method to local RPC"
  echo "address of ''."

if [ $# -gt 1 ]; then
  echo "Too many parameters. At the most, one parameter is possible"
  echo ""
  exit 100

declare rpc_addr=''

if [ $# -eq 1 ]; then
  if [ "$1" == "-h" -o "$1" == "--help" ]; then
    exit 0

# check the specified RPC address
curl -sS $rpc_addr
if [ $? -ne 0 ]; then
  echo "Fail to connect to the specified RPC adderss '$rpc_addr'"
  exit 200

echo "Executing some basic JSON RPC methods to '$rpc_addr'"
echo ""

declare -ar titles=(
'the client coinbase address'
'current client version'
'the current ethereum protocol version'
'number of peers currently connected to the client'
'whether or not client is actively mining new blocks'
'a list of addresses owned by client'
'current network ID'
'the current price per gas in wei'
'the number of most recent block'
'about the genesis block'

declare -ar data=(
'{"jsonrpc":"2.0","method":"eth_getBlockByNumber","params":["0x0", false],"id":101}'

for (( i = 0; i < ${#titles[@]}; i++ )); do

  cmd="curl -sSX POST --data '${data[$i]}' $rpc_addr"

  echo "// ${titles[$i]}"
  echo $cmd
  eval $cmd
  echo -e "\n"
  • Verifying a confusing result or situation at the most fundamental level using eth_getTransactionByHash and eth_getTransactionReceipt APIs for each transaction concenred
$ # Get information for the specified transaction (result is not included) (https://eth.wiki/json-rpc/API#eth_gettransactionbyhash)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionReceipt","params":["0x10f612a42b04ace427b0057caf76d7c7446840f419d4b424f117ecb1bd2cb0e8"],"id":201}'

$ # Get the receipt for the specified transaction, which include the result status and logs (https://eth.wiki/json-rpc/API#eth_gettransactionreceipt)
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0x10f612a42b04ace427b0057caf76d7c7446840f419d4b424f117ecb1bd2cb0e8"],"id":211}'


Network Chain Chain ID Network ID Consensus Avg. Block Time Faucet Explorer GitHub Remark
Ethereum Mainnet ETH 1 1 PoW
Ethereum Classic Mainnet ETC 61 1 PoW
Ropsten ETH 3 3 PoW 30 sec. https://faucet.ropsten.be/ https://ropsten.etherscan.io/ https://github.com/ethereum/ropsten
Rinkeby ETH 4 4 PoA 15 sec. https://faucet.rinkeby.io/ https://www.rinkeby.io/#explorer
Kovan ETH 42 42 PoA 4 sec. https://faucet.kovan.network/
https://kovan.etherscan.io/ https://github.com/kovan-testnet
Görli ETH 5 5 PoA 15 sec. https://goerli.etherscan.io/ https://github.com/goerli/testnet
Binance Smart Chain Mainnet BSC 56 56 https://bscscan.com
Binance Smart Chain Testnet BSC 97 97 https://testnet.binance.org/faucet-smart https://testnet.bscscan.com


Chain Faucet Amount Remarks
Ropsten http://fauceth.komputing.org?chain=3&address=${ADDRESS}
Rinkeby https://faucet.rinkeby.io/ 3 ETH/8 hours, 18.75 ETH/3 days Require Tweet or Facebook account
https://faucets.chain.link/rinkeby 0.1 ETH
https://rinkeby.faucet.epirus.io/ 0.2 ETH
Kovan http://fauceth.komputing.org?chain=42&address=${ADDRESS}
https://faucets.chain.link/kovan 0.1 ETH


Ehtereum Mainnet
Topic Charts and Tables Remarks
Performance Average Block Time Chart
Mining Difficulty Etherscan / Ethereum Network Difficulty Chart
Ethereum Difficulty Chart
Data Size Full Node Data Size Chart
Archive Node Data Size Chart
Average Block Size Chart

Milestone Blocks

Block # Hash Date Difficulty Block Reward Fee Reward Transactions
10,000,000 0xaa20f7bde5be60603f11a45fc4923aab7552be775403fc00c2e6b805e6297dbe 2020-05-04 2 0.07667 103
9,500,000 0xfd233684d9cbabc563ccc5c3b316ab1f3a22c46cb1495777264f191f5fb96115 2020-02-17 2,230,523,668,588,724 2 0.04033 33
9,000,000 0x388f34dd94b899f65bbd23006ee93d61434a2f2a57053c9870466d8e142960e3 2019-11-26 2,573,664,196,528,490 2 0.14161 95
8,000,000 0x4e454b49dc8a2e2a229e0ce911e9fd4d2aa647de4cf6e0df40cf71bff7283330 2019-06-21 2,037,888,242,889,388 2 0.09102 168
7,000,000 0x17aa411843cb100e57126e911f51f295f5ddb7e9a3bd25e708990534a828c4b7 2019-01-03 2,553,711,764,445,236 3 0.01631 38
6,000,000 0xbe847be2bceb74e660daf96b3f0669d58f59dc9101715689a00ef864a5408f43 2018-07-21 3,483,739,548,912,554 3 0.17281 101
3,000,000 0xee396a86beaade9d6057b72a92b7bf5b40be4997745b437857469557b562a7c3 2017-01-16 103,975,266,902,792 5 0.00851 6
2,000,000 0xc0f4906fea23cf6f3cce98cb44e8e1449e455b28d684dfa9ff65426495584de6 2016-08-03 49,824,742,724,615 5 0.00063 1
1 0x88e96d4537bea4d9c05d12549907b32561d3bf31f45aae734cdc119f13406cb6 2015-07-31 17,171,480,576 5 0 0

Famous Contracts

Service Contract Network Address Remarks
Uniswap V2 Router Rinkeby 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
ChainLink Token Rinkeby 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 ERC-20
Kovan 0xa36085F69e2889c224210F603D836748e7dC0088 ERC-20

Layer 2

Layer 2 is a collective term for solutions designed to help scale your application by handling transactions off the Ethereum mainnet (layer 1), while taking advantage of the robust decentralized security model of mainnet.

Solution Type Description Remarks
OMG Network (a.k.a OmiseGo) Plazma leverages Layer-2 Plasma architecture to provide high throughput and strong safety guarantees for third parties who wish to build scalable, decentralized payment apps on the Ethereum Network
Polygon Sidechain a protocol and a framework for building and connecting Ethereum-compatible blockchain networks
Optimism Optimistic Roll-up an EVM-compatible Optimistic Rollup chain designed to be fast, simple, and secure sources / docs
zkSync ZK Roll-up a scaling and privacy engine for Ethereum sources / docs
StarkEx ZK Roll-up a battle-tested L2 scalability engine, deployed on Mainnet since June 2020
Aztec ZK Roll-up an open source layer 2 network bringing scalability and privacy too Ethereum sources / docs

Ethereum 2.0




Feature MetaMask KaiKas
Mnemonic Support O
Multiple Mnemonics Support
Initializing without Mnemonic X
Importing Private Key in Plaintext O
Exporting Private Key into Keystore File X

HD Wallet

const { hdkey } = require('ethereumjs-wallet'); // https://www.npmjs.com/package/ethereumjs-wallet
const bip39 = require("bip39"); // https://www.npmjs.com/package/bip39

// https://dev.to/dongri/ethereum-wallet-sample-code-10o2
const mnemonic = '...'; // TODO find sample mnemonic
const parentKey = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath("m/44'/60'/0'/0");

const wallets = [];
for(let i = 0; i < 10; i++){

console.log(`Mnemonic : ${mnemonic}`);
for(i in wallets){
  console.log(`  Account : ${i}th`)
  console.log(`    Private Key : ${wallets[i].getPrivateKeyString()}`);
  console.log(`    Address     : ${wallets[i].getChecksumAddressString()}`);


Explorer Token Contract Type Count ('21/10/19) Remarks
Etherscan Top ERC-20 Tokens 458,890
Top ERC-721 Tokens 20,735
Top ERC-1155 Tokens 3,800 (?) OpenSea Shared Storefront, Rarible(RARI), parallel(LL), Zapper NFT

Fungible Token

EIP Title Status Description Remarks
EIP-20 Token Standard Final A standard interface for tokens.
EIP-2612 permit – 712-signed approvals Review ERC-20 approvals via secp256k1 signatures function permit()
function nonces()
  • EIP-20 Interface
// https://eips.ethereum.org/EIPS/eip-20
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/token/ERC20/

interface IERC20 {

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    function name() external view returns (string); //optional

    function symbol() external view returns (string); //optional
    unction decimals() external view returns (uint8); //optional

    function totalSupply() external view returns (uint256);

    function balanceOf(address account) external view returns (uint256);

    function transfer(address recipient, uint256 amount) external returns (bool);

    function transferFrom(address sender, address recipient, uint256 amount) 
			external returns (bool);

    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 amount) external returns (bool);


Non-Fungible Token

EIP Title Status Description Remarks
EIP-721 Non-Fungible Token Standard Final A standard interface for non-fungible tokens, also known as deeds.
EIP-1155 Multi Token Standard Final A standard interface for contracts that manage multiple token types
EIP-2309 ERC-721 Consecutive Transfer Extension Final A standardized event emitted when creating/transferring one, or many non-fungible tokens using consecutive token identifiers.
EIP-2981 NFT Royalty Standard Final A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal support for royalty payments across all NFT marketplaces and ecosystem participants.
EIP-998 Composable Non-Fungible Token Standard Draft An extension of the ERC-721 standard to enable ERC721 tokens to own other ERC721 tokens and ERC20 tokens.
EIP-1523 Standard for Insurance Policies as ERC-721 Non Fungible Tokens Draft A standard interface for insurance policies, based on ERC 721.
EIP-3525 Semi-Fungible Token Standard Draft A standard for semi-fungible tokens. <ID, SLOT, AMOUNT> triple scalar model
EIP-4400 ERC-721 Consumable Extension Draft Defines standard functions outlining a consumer role for instance(s) of ERC-721. function consumerOf(uint256 _tokenId)
EIP-4494 Permit for ERC-721 NFTs Draft ERC-712-singed approvals for ERC-721 NFTs function permit()
function nonces()
EIP-4521 721/20-compatible transfer Draft Recommends a simple extension to make NFTs compatible with apps and contracts that handle fungibles.
EIP-2615 Non-Fungible Token with mortgage and rental functions Stagnant Proposes an extension to ERC721 Non-Fungible Tokens (NFTs) to support rental and mortgage functions.
  • EIP-721 Interfaces
// https://eips.ethereum.org/EIPS/eip-721
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.3.2/contracts/token/ERC721/

interface ERC721 /* is ERC165 */ {

    event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
    event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

    function balanceOf(address _owner) external view returns (uint256);

    function ownerOf(uint256 _tokenId) external view returns (address);

    function transferFrom(address _from, address _to, uint256 _tokenId) external payable;

    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;

    function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;

    function approve(address _approved, uint256 _tokenId) external payable;

    function getApproved(uint256 _tokenId) external view returns (address);

    function setApprovalForAll(address _operator, bool _approved) external;

    function isApprovedForAll(address _owner, address _operator) external view returns (bool);

interface ERC165 {
    function supportsInterface(bytes4 interfaceID) external view returns (bool);

interface ERC721TokenReceiver {

    function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);

interface ERC721Metadata { //optional

    function name() external view returns (string _name);

    function symbol() external view returns (string _symbol);

    function tokenURI(uint256 _tokenId) external view returns (string);

interface ERC721Enumerable { //optional

    function totalSupply() external view returns (uint256);

    function tokenByIndex(uint256 _index) external view returns (uint256);

    function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
  • EIP-1155 Interfaces
// https://eips.ethereum.org/EIPS/eip-1155
// https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v4.3.2/contracts/token/ERC1155

interface ERC1155 /* is ERC165 */ {

    event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _typeId, uint256 _value);

    event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _typeId, uint256[] _values);

    event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

    event URI(string _value, uint256 indexed _typeId);

    function safeTransferFrom(address _from, address _to, uint256 _typeId, uint256 _value, bytes calldata _data) external;

    function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _typeIds, uint256[] calldata _values, bytes calldata _data) external;

    function balanceOf(address _owner, uint256 _typeId) external view returns (uint256);

    function balanceOfBatch(address[] calldata _owners, uint256[] calldata _typeIds) external view returns (uint256[] memory);

    function setApprovalForAll(address _operator, bool _approved) external;

    function isApprovedForAll(address _owner, address _operator) external view returns (bool);

interface ERC1155TokenReceiver {

    function onERC1155Received(address _operator, address _from, uint256 _tpyeId, uint256 _value, bytes calldata _data) external returns(bytes4);

    function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _typeIds, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);       

interface ERC1155Metadata_URI {

    function uri(uint256 _typeId) external view returns (string memory);
  • EIP-2309 Interface
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress);

Security Token

Model Description Features Remarks
ERC-1450 A compatible security token for issuing and trading SEC-compliant securities
  • Fungible token
  • Agent transfer
Stagnant EIP
EIP-1462 Base Security Token
  • Fungible token
  • Ownership and transfer
  • Limited delegation
  • Transfer control
  • Document management
Stagnant EIP
  • Partially fungible token (token class, series investment)
  • Limited delegation
  • Full delegation
  • Transfer control
  • Forced transfer
  • Document management
Codefi/ConsenSys, Polymath

Famous Tokens

Token Symbol Type Description Remarks
ChainLink Token LINK ERC-677
Wrapped Ether WETH ERC-20
Token Chain Contract Address Faucet Remarks
LINK Ethereum Mainnet 0x514910771af9ca656af840dff83e8264ecf986ca
LINK Ethereum Rinkeby 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 https://faucets.chain.link/rinkeby
LINK Ethereum Kovan 0xa36085F69e2889c224210F603D836748e7dC0088 https://faucets.chain.link/kovan
LINK Ethereum Goerli 0x326c977e6efc84e512bb9c30f76e30c160ed06fb
LINK Binance Smart Chain Mainnet 0x404460c6a5ede2d891e8297795264fde62adbb75
WETH Ethereum Mainnet 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
WETH Ethereum Rinkeby 0xc778417e063141139fce010982780140aa0cd5ab

Cross Chain

Token Bridge

Bridge Description Documentation Remarks
POA Bridge Smart Contracts https://docs.tokenbridge.net/
RSK <-> ETH Token Bridge https://developers.rsk.co/tools/tokenbridge/
Cross Bridge V1 a trustless peg-in/peg-out bridge that allows users to easily hop between Ethereum (ERC20) and Binance Smart Chain (BEP20). https://hotcross.com/bridge
Cross Bridge V2 allows end users to security transfer ERC20 tokens from the Ethereum network to the Binance Smart Chain (BSC) and vice versa. https://hotcross.com/bridge2


DAOs are an effective and safe way to work with like-minded folks around the globe.

The backbone of a DAO is its smart contract. The contract defines the rules of the organisation and holds the group's treasury.

DAO Description Contracts Remarks
MakerDAO https://github.com/makerdao
Moloch DAO https://github.com/MolochVentures/moloch
DAOhaus DAOhaus is a no-code platform for launching and running DAOs. Moloch DAO based
Aragon Aragon is a suite of applications and services that enable new forms of global communities.



  • Zero-Knowledge Proof Cryptography: A Gateway to Enterprise Blockchain Adoption (Sep 30, 2019)
  • New Zero Knowledge Proof Services Provide Complete Transaction Privacy (Sep 15, 2019)
    • Zether protocol allows ethereum accounts holding ERC20 token balances to fund Zether accounts and obtain ZTH tokens in exchange. Transfer of ZTH tokens among the Zether accounts are conducted with zero knowledge proofs, thus concealing the balances, transfer amount as well as the identity of the trading parties.
    • You can seamlessly transition from executing asset transfers with ERC20/721 tokens, which leak data on the blockchain, to privacy-preserving asset transfers that leverage zero-knowledge proof cryptography, keeping sensitive transactional data off the blockchain.



  • What Is an Automated Market Maker?
    • Human Market Maker vs. Automated Market Maker
    • Order Book vs. Liquidity Pools
    • On AMM-based decentralized exchanges, the traditional order book is replaced by liquidity pools that are pre-funded on-chain for both assets of the trading pair.
    • One decentralized exchange that has implemented an AMM is Uniswap.
  • What Is an Automated Market Maker (AMM)? (Binance Academy)
Protocol Description Sources Remarks
Uniswap https://github.com/Uniswap
Curve an exchange liquidity pool on Ethereum designed for: extremely efficient stablecoin trading, low risk, supplemental fee income for liquidity providers, without an opportunity cost. https://github.com/curvefi
PancakeSwap The #1 AMM and yield farm on Binance Smart Chain. https://github.com/pancakeswap







Hacking Network Occurred At Type Scale Summary
Axie Infinity Axie Infinity Hack Mar '22 $625M (173,600 ETH and 25.5M USDC) The attack focused on the bridge to Sky Mavis’ Ronin blockchain, an intermediary between Axie Infinity and other cryptocurrency blockchains like Ethereum.
BitMart Hack Dec '21 Exchange Hack $200M
Bitgrail Hack 2018 Exchange Hack $120M (17M NANO)
Coincheck Hack 2018 Exchange Hack $400M (500M NEM)
Bithumb Hack 2018 Exchange Hack ₩35B
Parity Wallet Hack Ethereum 2017 Wallet Bug $300M
DAO Hack Ethereum 2016 Smart Contract Bug $90M
Bitfinex Hack 2016 Exchange Hack $72M (120K BTC)
Mt. Cox Hack 2014 Exchange Hack $473M (750K BTC)




  • Solidity (on Wikipedia)
    • an object-oriented programming language for writing smart contracts.
Data types Address Array
Contracts Functions Structs
Inheritance Interfaces Libraries
Units / Global Variables Block / Transaction Time Units
Pragmas Cheatsheet
  • Solidity v0.6.0 Breaking Changes
    • Function overriding should be explicit. - virtual, override keywords
    • Array's length property become immutable.
    • Abstract contract should be explicit. - abstract keyword
    • State variable shadowing become disallowed.
Data types Address Array
Contracts Functions Structs
Inheritance Interfaces Libraries
Units / Global Variables Block / Transaction Time Units
Pragmas Cheatsheet
  • Solidity v0.5.0 Breaking Changes
    • Function visibility (external, public, internal, private) should be explicit.
    • Data location for reference types (struct, array, mapping) should be explicit.
    • Conversion from contract type to address should be explicit. - address(contract).balance
    • Explicit conversion between unrelated contract types are disallowed.
    • Split address type into address type and address payable type.
    • For a contract c, address(c) is address payable iff c has payable fallback function.

Breaking Changes

Version Category Change Remark
0.8 Arithmetic Operation Arithmetic operations revert on underflow and overflow.
ABI Coder v2 ABI coder v2 is activated by default. pragma abicoder
Opcode Failing assertions and other internal checks like division by zero or arithmetic overflow do not use the invalid opcode but instead the revert opcode.
Data-type The type byte has been removed. bytes1
Data-type Address literals have the type address instead of address payable. payable()
Function Function call options can only be given once.
Global Function The global functions log0, log1, log2, log3 and log4 have been removed. inline assembly
Global Variable The global variables tx.origin and msg.sender have the type address instead of address payable. payable(tx.origin), payable(msg.sender)
Type Conversion Explicit conversion into address type always returns a non-payable address type.
0.7 Function Ether and gas is now specified using a new syntax: x.f{gas: 10000, value: 2 ether}(arg1, arg2).
Global Variable The global variable now is deprecated. block.timestamp
Data-type String literals now can only contain printable ASCII characters and this also includes a variety of escape sequences, such as hexadecimal (\xff) and unicode escapes (\u20ac).
Data-type Unicode string literals are supported now. unicode"Hello 😃"
State Mutability The state mutability of functions can now be restricted during inheritance.
Mapping If a struct or array contains a mapping, it can only be used in storage.
Mapping Assignments to structs or arrays in storage does not work if they contain mappings.
Constructor Visibility (public / external) is not needed for constructors anymore. abstract contract
Function Disallow virtual for library functions since libraries cannot be inherited from.
Inheritance using A for B is NOT inherited.
Shift Operation Shifts by signed types are disallowed.
Variable The keyword var cannot be used anymore. (compile-time) parser error


Contract = State Variable*, Function*, Function Modifier*, Event*, Struct Type*, Enum Type*

function (<parameter types>) {internal|external} [pure|view|payable] [returns (<return types>)]
  • Reference Types
    • Every reference type, i.e. arrays and structs, has an additional annotation, the “data location”, about where it is stored.
    • All complex types must now give an explicit data location.
  • Functions
    • Functions may also return an arbitrary number of values as output.
    • Data location must be memory for return parameter in function
  • Constructors
    • Before the constructor code is executed, state variables are initialised to their specified value if you initialise them inline, or zero if you do not.
    • After the constructor has run, the final code of the contract is deployed to the blockchain.
    • The constructors of all the base contracts will be called following the linearization rules explained below.
  • Contracts
    • State variables are accessed via their name and not via e.g. `this.owner`. Functions can be accessed directly or through `this.f`, but the latter provides an external view to the function. Especially in the constructor, you should not access functions externally, because the function does not exist yet.


Visibility Description Remarks
external Part of the contract interface, which means they can be called from other contracts and via transactions but cannot be called internally f() does not work, but this.f() works
public Part of the contract interface and can be either called internally or via messages.
internal Can only be accessed internally (i.e. from within the current contract or contracts deriving from it)
private Only visible for the contract they are defined in and not in derived contracts.


Mutability Description Remarks
pure Promise not to read from or modify the state.
view Promise not to modify the state.
nonpayable Does not accept Ether
payable Accepts Ether


Category Types Remarks
Value Type Booleans, Integers, Fixed Point Number, Address, Fixed-size Byte Array, Enum
Reference Type Arrays, Structs, Mappings
Value Types
Type Description Remarks
int8, int16, int24, ... , int248, int256 signed integer in 8 ~ 256 bits 8 bits step
uint8, uint16, uint24, ... , uint248, uint256 unsigned integer in 8 ~ 256 bits 8 bits step
int alias for int256 2256 ~ 1077
uint alias for uint256 2256 ~ 1077
address Holds a 20 byte value (size of an Ethereum address)
address payable Same as address, but with the additional members transfer and send
bool b1 = true;   // boolean literal 'true'
bool b2 = false;   // boolean literal 'false'

uint[] arr1 = [uint(1), 2, 3];   // array literal using square bracket
Address Type
Member Description Remarks
transfer(uint256 amount)
send(uint256 amount) returns (bool)
call(bytes memory) returns (bool, bytes memory) issue low-level CALL with the given payload, returns success condition and return data, forwards all available gas, adjustable
delegatecall(bytes memory) returns (bool, bytes memory) issue low-level DELEGATECALL with the given payload, returns success condition and return data, forwards all available gas, adjustable.
staticcall(bytes memory) returns (bool, bytes memory) issue low-level STATICCALL with the given payload, returns success condition and return data, forwards all available gas, adjustable.
Reference Types
Type Description Remarks
Array Type
Category Variable/Function Type Description Remarks
Array length ...
push() for dynamic storage arrays and bytes, not for string
pop() for dynamic storage arrays and bytes, not for string
bytes concat()
Feature fixed-size storage array dynamic-size storage array fixed-size memory array dynamic-size memory array
new operator support X O X O
push(), pop() support X O X X
initialized with array literal O O O X
initialized from fixed-size array O O O X
initialized from dynamic-size array X X

Arrays can have a compile-time fixed size, or they can have a dynamic size. The type of an array of fixed size k and element type T is written as T[k], and an array of dynamic size as T[]. You should use bytes over byte[] because it is cheaper, since byte[] adds 31 padding bytes between the elements. Memory arrays with dynamic length can be created using the new operator. As opposed to storage arrays, it is not possible to resize memory arrays (e.g. the .push member functions are not available). Fixed size memory arrays cannot be assigned to dynamically-sized memory arrays. If you want to initialize dynamically-sized memory arrays, you have to assign the individual elements.

  • bytes
    • similar to but cheaper than bytes[]
    • packed tightly in calldata and memory.
    • should be used for arbitrary-length raw byte data
  • string
    • equal to bytes
    • not allow length or index access
    • should be used for for arbitrary-length UTF-8 data
    • no built-in manipulation function
    • comparing two strings  : keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2))
    • concatenating two strings : abi.encodePacked(s1, s2)
  • Solidity Tutorial : all about Bytes (Aug 1, 2019·11)
    • When defining a multidimensional array, the notation is reversed compared to other programming languages. : T[m][n] vs. T[n][m]
    • When accessing a multidimensional array, the notation is in the right to left order like other programming language. : a[i][j]
Syntax Dimension Type Remarks
T[k] 1 fixed-size
T[] 1 dynamic-size
T[n][m] 2 fixed-size
T[][] 2 dynamic-size
T[][m], T[n][] 2 mixed-size
T[][3][2][][9][] 6 mixed-size
Mapping Types

You can think of mappings as hash tables, which are virtually initialised such that every possible key exists and is mapped to a value whose byte-representation is all zeros, a type’s default value.

... mappings do not have a length or a concept of a key or value being set, and therefore cannot be erased without extra information regarding the assigned keys.

Mappings can only have a data location of storage and thus are allowed for state variables, as storage reference types in functions, or as parameters for library functions. They cannot be used as parameters or return parameters of contract functions that are publicly visible.

Data Location

Data Location Features Lifetime
memory non-persistent function call
calldata non-modifiable, non-persistent
  • Currently, reference types comprise structs, arrays and mappings.
  • All reference types(array, struct, mapping) must give an explicit data location when used in function parameter, local variable.
  • Data location for reference type state variable is always storage implicitly.
  • Data location for reference type local variable should be 'storage' or 'memory'.
  • Data location for reference type return parameter should be 'memory'.
  • Data location for reference type external function parameter should be 'calldata'.
  • If you can, try to use calldata as data location because it will avoid copies and also makes sure that the data cannot be modified. Arrays and structs with calldata data location can also be returned from functions, but it is not possible to allocate such types.
Case Data Location Remarks
state variable always storage implicitly
local variable storage or memory
external function parameter calldata
return parameter memory
  • Data location and assignment
Assignment Semantics Remarks
Assignments between storage and memory always create an independent copy
Assignments from memory to memory only create references
Assignments from storage to a local storage variable only assign a reference
Assignments to state variables always copy
Assignments to members of local variables of storage struct type always copy
  • Ethereum Solidity: Memory vs Storage & When to Use Them (Mar 18, 2018)
    • storage cannot be newly created in a function. Any storage referenced variable in a function always refers a piece of data pre-allocated on the contract storage (state variable). Any mutation persists after function call.
    • memory can only be newly created in a function. It can either be newly instantiated complex types like array/struct (e.g. via new int[...]) or copied from a storage referenced variable.
    • As references are passed internally through function parameters, remember they default to memory and if the variable was on storage it would create a copy and any modification would not persist.
Usage storage memory calldata Preferred Remarks
State variables O X X forced to storage
Parameters of external functions X X O forced to calldata
Parameters and returns of functions O O O memory
Local variables O O O


Type Literal Remarks
address 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF Hexadecimal literals that are between 39 and 41 digits long

Default Values (Zero Values)

Type Default Value Remarks
bool false
uint, int 0
address address(0)
enum the first element of the enum
fixed sized array zero-valued array an array of the fixed size where all elements are set to initial values
dynamic sized array empty array []
string empty string ""
mapping empty mapping
struct empty struct a struct value where all members are set to initial values

Special Variables and Functions

Category Variable/Function Description Remarks
Block/Transaction block.coinbase::address payable current block miner’s address
block.number::uint current block number
block.timestamp::uint current block timestamp as seconds since unix epoch
msg.sender::address payable sender of the message
msg.data::bytes complete calldata
msg.sig::bytes4 first four bytes of the calldata function identifier(selector)
msg.value::uint number of wei sent with the message
tx.origin::address payable sender of the transaction (full call chain) tx = ∑call
Address/Address Payable <address>.balance::uint balance of the address in wei
<address payable>.transfer() send given amount of wei to address
<address payable>.send() send given amount of wei to address
<address>.call() issue low-level CALL with the given payload, returns success condition and return data
<address>.delegatecall() issue low-level DELEGATECALL with the given payload, returns success condition and return data
<address>.staticcall() issue low-level STATICCALL with the given payload, returns success condition and return data
Contract this the current contract address(this)
address(contr) the address of the specified contract instance
address(this) the address object of current contract address(this).balance
payable(contr) the address payable of the specified contract instance
Error Handling assert(bool condition) causes an invalid opcode and thus state change reversion if the condition is not met - to be used for internal errors.
require(bool condition) reverts if the condition is not met - to be used for errors in inputs or external components.
Mathematics/Cryptography keccak256() compute the Keccak-256 hash of the input
sha256() compute the SHA-256 hash of the input
ecrecover() recover the address associated with the public key from elliptic curve signature or return zero on error
Type/Contract type(I).interfaceId A bytes4 value containing the EIP-165 interface identifier of the given interface I


  • A constructor is optional. Only one constructor is allowed.
  • If there is no constructor, the contract will assume the default constructor, which is equivalent to constructor() public {}.
  • Before the constructor code is executed, state variables are initialised to their specified value if you initialise them inline, or zero if you do not.
  • The deployment of the code costs additional gas linear to the length of the code.
  • Constructor functions can be either public or internal.
  • A constructor set as internal causes the contract to be marked as abstract.
  • If the base constructors have arguments, derived contracts need to specify all of them.
  • If a derived contract does not specify the arguments to all of its base contracts’ constructors, it will be abstract.
  • Contracts may be marked as abstract even though all functions are implemented.
  • Abstract contracts can not be instantiated directly.
  • Abstract contracts cannot override an implemented virtual function with an unimplemented one.
  • We perform an explicit type conversion from `address` to `TokenCreator` and assume that the type of the calling contract is `TokenCreator`, there is no real way to verify that. This does not create a new contract.
    • TokenCreator creator;
    • creator = TokenCreator(msg.sender);
  • Explicit conversions to and from address are allowed for integers, integer literals, bytes20 and contract types with the following caveat: The result of a conversion of the form address(x) has the type address payable, if x is of integer or fixed bytes type, a literal or a contract with a receive or payable fallback function. If x is a contract without a receive or payable fallback function, then address(x) will be of type address.
  • Functions with the private visibility cannot be virtual.

Interface ID

A bytes4 value containing the EIP-165 interface identifier of the given interface I. This identifier is defined as the XOR of all function selectors defined within the interface itself - excluding all inherited functions.
Interface Interface ID Method Method ID Code
IAccessControl 0x7965db0b
IAccessControlEnumerable 0x5a05180f
IERC721 0x80ac58cd
IERC721Metadata 0x5b5e139f
IERC721Enumerable 0x780e9d63 totalSupply() 0x18160ddd web3.eth.abi.encodeFunctionSignature('totalSupply()')
tokenOfOwnerByIndex(address,uint256) 0x2f745c59 web3.eth.abi.encodeFunctionSignature('tokenOfOwnerByIndex(address,uint256)')
tokenByIndex(uint256) 0x4f6ccce7 web3.eth.abi.encodeFunctionSignature('tokenByIndex(uint256)')


If library functions are called, their code is executed in the context of the calling contract,... ...

As a library is an isolated piece of source code, it can only access state variables of the calling contract if they are explicitly supplied... ...

Furthermore, internal functions of libraries are visible in all contracts, just as if the library were a base contract.

Error Handling

Built-in Description Remarks
assert(bool) causes an invalid opcode and thus state change reversion if the condition is not met - to be used for internal errors. imply bug, revert operation(0xfd)
require(bool) reverts if the condition is not met - to be used for errors in inputs or return values from calls to external contracts. invalid operation (0xfe)
  • Solidity performs a revert operation (instruction 0xfd) for a require-style exception and executes an invalid operation (instruction 0xfe) to throw an assert-style exception. In both cases, this causes the EVM to revert all changes made to the state.
  • assert-style exceptions consume all gas available to the call, while require-style exceptions do not consume any gas starting from the Metropolis release.


  • The Log and its event data is not accessible from within contracts (not even from the contract that created them)


  • JSON Description of Contract ABI
Category Element/Field Type/Value Description Remarks
Function type 'constructor' | 'receive' | 'fallback' the type of the function
name string the name of the function
inputs array input parameters
inputs.[*].name string the name of input parameter
inputs.[*].type string the canonical type of input parameter 'address' | 'uint256'
inputs.[*].components array used for tuple types
outputs array output parameters
stateMutability 'view' | 'nonpayable' | 'payable' function mutability
Event type 'event'
name string event name
inputs array event fields
inputs.[*].name string
inputs.[*].type string
inputs.[*].components array
inputs.[*].indexed boolean
anonymous boolean
truffle(development)> Migrations.new().then(c => c.abi)
    inputs: [],
    name: 'last_completed_migration',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x445df0ac'
    inputs: [],
    name: 'owner',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x8da5cb5b'
    inputs: [ [Object] ],
    name: 'setCompleted',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
    constant: undefined,
    payable: undefined,
    signature: '0xfdacd576'
  • Libraries
Package Class/Function Description Remarks
web3.js web3.eth.abi.encodeFunctionSignature() Encodes the function name to its ABI signature encodeFunctionSignature('myMethod(uint256,string)')
web3.eth.abi.encodeEventSignature() Encodes the event name to its ABI signature
web3.eth.abi.encodeParameters() Encodes a function parameters encodeParameters(['uint256','string'], ['2345675643', 'Hello!%'])
web3.eth.abi.decodeParameters() Decodes ABI encoded parameters to its JavaScript types.
web3.eth.abi.decodeLog() Decodes ABI-encoded log data and indexed topic data.
Web3j org.web3j.abi.TypeEncoder Ethereum ABI encoding for types.
org.web3j.abi.TypeDecoder Ethereum ABI decoding for types.
  • Sample Codes
// expecting "0x2fbebd38"

// expecting "0x00000000000000000000000000000000000000000000000000000000002dc6c0"

// expecting "0x1e15f6d3"

// expecting "0x000000000000000000000000000000000000000000000000000000000f32fdc0"

// expecting "0x6cd57036"

// expecting '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000cb00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000000000000000000000000000000000006a18a500' 

// expecting "0xd3ca0cb6"

// expecting '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001b48eb57e0000000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000042d2887600000000000000000000000000000000000000000000000000000000000000001f00000000000000000000000000000000000000000000000000000000013463aa000000000000000000000000000000000000000000000000000000000000007e'






Ether Transfer









  • awesome-solidity : A curated list of awesome Solidity resources, libraries, tools and more


Best Practices

Category Title Description Package Remarks
Wallet Multi-sig contract Multi-sig, daily-limited account proxy/wallet.
Gnosis Safe Multisig Wallet
Argent Wallet Smart Contracts an Ethereum Smart Contract based mobile wallet. guarded, recoverable, lockable and upgradable
BitGo’s Multisig Wallet Multi-sig contract suitable for use in wallets. 2-of-3 multisig
NFT CryptoPunks contracts 10,000 unique collectible characters with proof of ownership stored on the Ethereum blockchain.
Decentraland Land Contracts Contracts for Decentraland's World
Decentraland ERC721 Contracts Contracts for the standard implementation of the ERC721 by Decentraland. erc721
Decentraland Collection Contracts Decentralanad Collection Contracts Collection V2 contract, Collection V2 Store contract
Decentraland Marketplace Contracts Decentralanad Marketplace Contracts
STO Security Token Standard contracts ERC-1400
ConsenSys Codefi Universal Token a hybrid token standard precisely designed for the use case of tokenized financial assets ERC-1400
DeFi MakerDao Multi Collateral Dai contracts
Wallet Authereum contracts
DEX Uniswap V2 contracts
Uniswap V3 core contracts the core smart contracts for the Uniswap V3 Protocol
Uniswap V3 periphery contracts the periphery smart contracts for the Uniswap V3 Protocol
Oracle Chainlink's Solidity contracts
Bridge POA Bridge Smart Contracts implement the logic to relay assets between two EVM-based blockchain networks.
RSK <-> ETH Token Bridge allows to move ERC20 tokens from one chain to the other.
Contract Chain Instance Source Remarks
Exportable ERC721 Contract Mainnet 0x92b1A8fFd8FD2beD592abbb75F705ED415567cce
Rinkeby 0x21E7d3253a0cFe7ECA331312181440990F155961 source
ERC721 Factory Contract Mainnet 0xD51a54Ca4d356138c8A8D89495100a83C33541F0 source
Rinkeby 0xc6166699654359F894821d17681A1caE404FD1fb source
ERC721 Bridge Mainnet 0x0bf6bf849C75BF466cb6e3C7450e967BdBCC258E source
Rinkeby 0xd2F7FF4F72645645420a79706b59a777D5d17CF4 source
OpenSea Aware ERC721 Contract Rinkeby 0xC89f8C65af5105F4C304B760af8992a1A0D710E1 source Collection/OpenSea


Library Description License Remarks
Fixidity A fixed point mathematics library for Solidity MIT
solidity-sigutils A solidity library for verifying Ethereum message multi-signatures. Apache License, Version 2.0

Tips and Tricks

Typical Codes

// looping array using `length` property
address[] contracts = ...
uint256 n = contracts.length;
for(uint256 i; i < n; i++){

// setting nested mapping value to new struct object
struct Request {
  address owner;
  uint256 at;

mapping(address => mapping(uint256 => Request) requests;
requests[tokenContract][assetId] = Request(msg.sender, block.timestamp); // no `new` to create a new struct object

// declaring and initializing dynamic-sized memory array
uint256 l = ...
address[] memory owners = new address[](l);

// creating local struct array
struct Score {
  address owner;
  uint256 value;

uint256 l = ...
Score[] memory srcs = new Score[](l); // new struct array with `new` statement and length parameter

Playing with Arrays

struct Land{
  string name;
  uint256 area; // area in square killometers

contract SolidityTest{
  function testArrayInitialization() public pure returns(uint256[] memory, bytes[3] memory, string[] memory, Land[] memory){

    //creating arrays without explicit initializing.
    uint256 len = 5;
    uint[] memory scores = new uint[](len); // initialized with default value

    //initializing fixed-size arrays using array literals
    bytes[3] memory rgb = [bytes('RED'), 'GREEN', 'BLUE'];

    //initializing dynamic-size arrays
    //''If you want to initialize dynamically-sized arrays, you have to assign the individual elements'' (from Solidity documentation)
    string[] memory innerPlanets  = new string[](2);
    innerPlanets[0] = 'Mercury';
    innerPlanets[1] = 'Venus';

    Land[] memory continents = new Land[](7);
    continents[0] = Land('Africa', 30_370_000);
    continents[1] = Land('Antarctica', 14_000_000);
    continents[2] = Land('Asia', 44_579_000);
    continents[3] = Land('Europe', 10_180_000);
    continents[4] = Land('North America', 24_709_000);
    continents[5] = Land('South America', 17_840_000);
    continents[6] = Land('Australia', 8_600_000);

    return(scores, rgb, innerPlanets, continents);

Conversions between bytesM, bytes and string

function testStaticBytesDynamicBytesAndString() public pure returns(bytes[7] memory, bytes32[] memory, bytes[] memory, string[] memory){

  bytes[7] memory rainbow = [bytes('Red'), 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Viloet'];

  uint256 n = rainbow.length;
  bytes32[] memory colorsInBytes32 = new bytes32[](n);
  for(uint i = 0; i < n; i++){
    colorsInBytes32[i] = bytes32(rainbow[i]); // explicit conversion from `bytes`(dynamic bytes) to `bytes32` (supported from Solidity 0.8.5)

  bytes[] memory colorsInBytes = new bytes[](n);
  string[] memory colorsInString = new string[](n);

  for(uint i = 0; i < n; i++){
    colorsInBytes[i] = bytes.concat(colorsInBytes32[i]);
    colorsInString[i] = string(bytes.concat(colorsInBytes32[i])); // explicit conversion from `bytes32`, via `bytes`, to `string` 

  return (rainbow, colorsInBytes32, colorsInBytes, colorsInString);



Go Ethereum


$ geth --help
   geth - the go-ethereum command line interface

   Copyright 2013-2021 The go-ethereum Authors

   geth [options] [command] [command options] [arguments...]
   account                            Manage accounts
   attach                             Start an interactive JavaScript environment (connect to node)
   console                            Start an interactive JavaScript environment
   copydb                             Create a local chain from a target chaindata folder
   db                                 Low level database operations
   dump                               Dump a specific block from storage
   dumpconfig                         Show configuration values
   dumpgenesis                        Dumps genesis block JSON configuration to stdout
   export                             Export blockchain into file
   export-preimages                   Export the preimage database into an RLP stream
   import                             Import a blockchain file
   import-preimages                   Import the preimage database from an RLP stream
   init                               Bootstrap and initialize a new genesis block
   js                                 Execute the specified JavaScript files
   license                            Display license information
   makecache                          Generate ethash verification cache (for testing)
   makedag                            Generate ethash mining DAG (for testing)
   removedb                           Remove blockchain and state databases
   show-deprecated-flags              Show flags that have been deprecated
   snapshot                           A set of commands based on the snapshot
   version                            Print version numbers
   version-check                      Checks (online) whether the current version suffers from any known security vulnerabilities
   wallet                             Manage Ethereum presale wallets
   help, h                            Shows a list of commands or help for one command
  --config value                      TOML configuration file
  --datadir value                     Data directory for the databases and keystore (default: "/Users/3rdstage/Library/Ethereum")
  --datadir.ancient value             Data directory for ancient chain segments (default = inside chaindata)
  --datadir.minfreedisk value         Minimum free disk space in MB, once reached triggers auto shut down (default = --cache.gc converted to MB, 0 = disabled)
  --keystore value                    Directory for the keystore (default = inside the datadir)
  --usb                               Enable monitoring and management of USB hardware wallets
  --pcscdpath value                   Path to the smartcard daemon (pcscd) socket file
  --networkid value                   Explicitly set network id (integer)(For testnets: use --ropsten, --rinkeby, --goerli instead) (default: 1)
  --mainnet                           Ethereum mainnet
  --goerli                            Görli network: pre-configured proof-of-authority test network
  --rinkeby                           Rinkeby network: pre-configured proof-of-authority test network
  --yolov3                            YOLOv3 network: pre-configured proof-of-authority shortlived test network.
  --ropsten                           Ropsten network: pre-configured proof-of-work test network
  --syncmode value                    Blockchain sync mode ("fast", "full", "snap" or "light") (default: fast)
  --exitwhensynced                    Exits after block synchronisation completes
  --gcmode value                      Blockchain garbage collection mode ("full", "archive") (default: "full")
  --txlookuplimit value               Number of recent blocks to maintain transactions index for (default = about one year, 0 = entire chain) (default: 2350000)
  --ethstats value                    Reporting URL of a ethstats service (nodename:secret@host:port)
  --identity value                    Custom node name
  --lightkdf                          Reduce key-derivation RAM & CPU usage at some expense of KDF strength
  --whitelist value                   Comma separated block number-to-hash mappings to enforce (<number>=<hash>)
  --light.serve value                 Maximum percentage of time allowed for serving LES requests (multi-threaded processing allows values over 100) (default: 0)
  --light.ingress value               Incoming bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
  --light.egress value                Outgoing bandwidth limit for serving light clients (kilobytes/sec, 0 = unlimited) (default: 0)
  --light.maxpeers value              Maximum number of light clients to serve, or light servers to attach to (default: 100)
  --ulc.servers value                 List of trusted ultra-light servers
  --ulc.fraction value                Minimum % of trusted ultra-light servers required to announce a new head (default: 75)
  --ulc.onlyannounce                  Ultra light server sends announcements only
  --light.nopruning                   Disable ancient light chain data pruning
  --light.nosyncserve                 Enables serving light clients before syncing
  --dev                               Ephemeral proof-of-authority network with a pre-funded developer account, mining enabled
  --dev.period value                  Block period to use in developer mode (0 = mine only if transaction pending) (default: 0)
  --ethash.cachedir value             Directory to store the ethash verification caches (default = inside the datadir)
  --ethash.cachesinmem value          Number of recent ethash caches to keep in memory (16MB each) (default: 2)
  --ethash.cachesondisk value         Number of recent ethash caches to keep on disk (16MB each) (default: 3)
  --ethash.cacheslockmmap             Lock memory maps of recent ethash caches
  --ethash.dagdir value               Directory to store the ethash mining DAGs (default: "${HOME}/Library/Ethash")
  --ethash.dagsinmem value            Number of recent ethash mining DAGs to keep in memory (1+GB each) (default: 1)
  --ethash.dagsondisk value           Number of recent ethash mining DAGs to keep on disk (1+GB each) (default: 2)
  --ethash.dagslockmmap               Lock memory maps for recent ethash mining DAGs
  --txpool.locals value               Comma separated accounts to treat as locals (no flush, priority inclusion)
  --txpool.nolocals                   Disables price exemptions for locally submitted transactions
  --txpool.journal value              Disk journal for local transaction to survive node restarts (default: "transactions.rlp")
  --txpool.rejournal value            Time interval to regenerate the local transaction journal (default: 1h0m0s)
  --txpool.pricelimit value           Minimum gas price limit to enforce for acceptance into the pool (default: 1)
  --txpool.pricebump value            Price bump percentage to replace an already existing transaction (default: 10)
  --txpool.accountslots value         Minimum number of executable transaction slots guaranteed per account (default: 16)
  --txpool.globalslots value          Maximum number of executable transaction slots for all accounts (default: 4096)
  --txpool.accountqueue value         Maximum number of non-executable transaction slots permitted per account (default: 64)
  --txpool.globalqueue value          Maximum number of non-executable transaction slots for all accounts (default: 1024)
  --txpool.lifetime value             Maximum amount of time non-executable transaction are queued (default: 3h0m0s)
  --cache value                       Megabytes of memory allocated to internal caching (default = 4096 mainnet full node, 128 light mode) (default: 1024)
  --cache.database value              Percentage of cache memory allowance to use for database io (default: 50)
  --cache.trie value                  Percentage of cache memory allowance to use for trie caching (default = 15% full mode, 30% archive mode) (default: 15)
  --cache.trie.journal value          Disk journal directory for trie cache to survive node restarts (default: "triecache")
  --cache.trie.rejournal value        Time interval to regenerate the trie cache journal (default: 1h0m0s)
  --cache.gc value                    Percentage of cache memory allowance to use for trie pruning (default = 25% full mode, 0% archive mode) (default: 25)
  --cache.snapshot value              Percentage of cache memory allowance to use for snapshot caching (default = 10% full mode, 20% archive mode) (default: 10)
  --cache.noprefetch                  Disable heuristic state prefetch during block import (less CPU and disk IO, more time waiting for data)
  --cache.preimages                   Enable recording the SHA3/keccak preimages of trie keys
  --unlock value                      Comma separated list of accounts to unlock
  --password value                    Password file to use for non-interactive password input
  --signer value                      External signer (url or path to ipc file)
  --allow-insecure-unlock             Allow insecure account unlocking when account-related RPCs are exposed by http
  --ipcdisable                        Disable the IPC-RPC server
  --ipcpath value                     Filename for IPC socket/pipe within the datadir (explicit paths escape it)
  --http                              Enable the HTTP-RPC server
  --http.addr value                   HTTP-RPC server listening interface (default: "localhost")
  --http.port value                   HTTP-RPC server listening port (default: 8545)
  --http.api value                    API's offered over the HTTP-RPC interface
  --http.rpcprefix value              HTTP path path prefix on which JSON-RPC is served. Use '/' to serve on all paths.
  --http.corsdomain value             Comma separated list of domains from which to accept cross origin requests (browser enforced)
  --http.vhosts value                 Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --ws                                Enable the WS-RPC server
  --ws.addr value                     WS-RPC server listening interface (default: "localhost")
  --ws.port value                     WS-RPC server listening port (default: 8546)
  --ws.api value                      API's offered over the WS-RPC interface
  --ws.rpcprefix value                HTTP path prefix on which JSON-RPC is served. Use '/' to serve on all paths.
  --ws.origins value                  Origins from which to accept websockets requests
  --graphql                           Enable GraphQL on the HTTP-RPC server. Note that GraphQL can only be started if an HTTP server is tarted as well.
  --graphql.corsdomain value          Comma separated list of domains from which to accept cross origin requests (browser enforced)
  --graphql.vhosts value              Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (default: "localhost")
  --rpc.gascap value                  Sets a cap on gas that can be used in eth_call/estimateGas (0=infinite) (default: 25000000)
  --rpc.txfeecap value                Sets a cap on transaction fee (in ether) that can be sent via the RPC APIs (0 = no cap) (default: 1)
  --rpc.allow-unprotected-txs         Allow for unprotected (non EIP155 signed) transactions to be submitted via RPC
  --jspath loadScript                 JavaScript root path for loadScript (default: ".")
  --exec value                        Execute JavaScript statement
  --preload value                     Comma separated list of JavaScript files to preload into the console
  --bootnodes value                   Comma separated enode URLs for P2P discovery bootstrap
  --discovery.dns value               Sets DNS discovery entry points (use "" to disable DNS)
  --port value                        Network listening port (default: 30303)
  --maxpeers value                    Maximum number of network peers (network disabled if set to 0) (default: 50)
  --maxpendpeers value                Maximum number of pending connection attempts (defaults used if set to 0) (default: 0)
  --nat value                         NAT port mapping mechanism (any|none|upnp|pmp|extip:<IP>) (default: "any")
  --nodiscover                        Disables the peer discovery mechanism (manual peer addition)
  --v5disc                            Enables the experimental RLPx V5 (Topic Discovery) mechanism
  --netrestrict value                 Restricts network communication to the given IP networks (CIDR masks)
  --nodekey value                     P2P node key file
  --nodekeyhex value                  P2P node key as hex (for testing)
  --mine                              Enable mining
  --miner.threads value               Number of CPU threads to use for mining (default: 0)
  --miner.notify value                Comma separated HTTP URL list to notify of new work packages
  --miner.gasprice value              Minimum gas price for mining a transaction (default: 1000000000)
  --miner.gastarget value             Target gas floor for mined blocks (default: 8000000)
  --miner.gaslimit value              Target gas ceiling for mined blocks (default: 8000000)
  --miner.etherbase value             Public address for block mining rewards (default = first account) (default: "0")
  --miner.extradata value             Block extra data set by the miner (default = client version)
  --miner.recommit value              Time interval to recreate the block being mined (default: 3s)
  --miner.noverify                    Disable remote sealing verification
  --gpo.blocks value                  Number of recent blocks to check for gas prices (default: 20)
  --gpo.percentile value              Suggested gas price is the given percentile of a set of recent transaction gas prices (default: 60)
  --gpo.maxprice value                Maximum gas price will be recommended by gpo (default: 500000000000)
  --vmdebug                           Record information useful for VM and contract debugging
  --vm.evm value                      External EVM configuration (default = built-in interpreter)
  --vm.ewasm value                    External ewasm configuration (default = built-in interpreter)
  --fakepow                           Disables proof-of-work verification
  --nocompaction                      Disables db compaction after import
  --verbosity value                   Logging verbosity: 0=silent, 1=error, 2=warn, 3=info, 4=debug, 5=detail (default: 3)
  --log.json                          Format logs with JSON
  --vmodule value                     Per-module verbosity: comma-separated list of <pattern>=<level> (e.g. eth/*=5,p2p=4)
  --backtrace value                   Request a stack trace at a specific logging statement (e.g. "block.go:271")
  --debug                             Prepends log messages with call-site location (file and line number)
  --pprof                             Enable the pprof HTTP server
  --pprof.addr value                  pprof HTTP server listening interface (default: "")
  --pprof.port value                  pprof HTTP server listening port (default: 6060)
  --pprof.memprofilerate value        Turn on memory profiling with the given rate (default: 524288)
  --pprof.blockprofilerate value      Turn on block profiling with the given rate (default: 0)
  --pprof.cpuprofile value            Write CPU profile to the given file
  --trace value                       Write execution trace to the given file
  --metrics                           Enable metrics collection and reporting
  --metrics.expensive                 Enable expensive metrics collection and reporting
  --metrics.addr value                Enable stand-alone metrics HTTP server listening interface (default: "")
  --metrics.port value                Metrics HTTP server listening port (default: 6060)
  --metrics.influxdb                  Enable metrics export/push to an external InfluxDB database
  --metrics.influxdb.endpoint value   InfluxDB API endpoint to report metrics to (default: "http://localhost:8086")
  --metrics.influxdb.database value   InfluxDB database name to push reported metrics to (default: "geth")
  --metrics.influxdb.username value   Username to authorize access to the database (default: "test")
  --metrics.influxdb.password value   Password to authorize access to the database (default: "test")
  --metrics.influxdb.tags value       Comma-separated InfluxDB tags (key/values) attached to all measurements (default: "host=localhost")
ALIASED (deprecated) OPTIONS:
  --nousb                             Disables monitoring for and managing USB hardware wallets (deprecated)
  --rpc                               Enable the HTTP-RPC server (deprecated and will be removed June 2021, use --http)
  --rpcaddr value                     HTTP-RPC server listening interface (deprecated and will be removed June 2021, use --http.addr) (default: "localhost")
  --rpcport value                     HTTP-RPC server listening port (deprecated and will be removed June 2021, use --http.port) (default: 8545)
  --rpccorsdomain value               Comma separated list of domains from which to accept cross origin requests (browser enforced) (deprecated and will be removed June 2021, use --http.corsdomain)
  --rpcvhosts value                   Comma separated list of virtual hostnames from which to accept requests (server enforced). Accepts '*' wildcard. (deprecated and will be removed June 2021, use --http.vhosts) (default: "localhost")
  --rpcapi value                      API's offered over the HTTP-RPC interface (deprecated and will be removed June 2021, use --http.api)
  --snapshot                          Enables snapshot-database mode (default = enable)
  --bloomfilter.size value            Megabytes of memory allocated to bloom-filter for pruning (default: 2048)
  --help, -h                          show help
  --override.berlin value             Manually specify Berlin fork-block, overriding the bundled setting (default: 0)

   Copyright 2013-2021 The go-ethereum Authors
  • JavaScript Console
    • $ geth attach ipc:/some/custom/path
    • $ geth attach
    • $ geth attach ws://
  • APIs
    • JSON-RPC API, Console API, Go API
Namespace Description Remarks
admin Gives you access to several non-standard RPC methods, which will allow you to have a fine grained control over your Geth instance, including but not limited to network peer and RPC endpoint management.
clique Provides access to the state of the clique consensus engine.
debug Gives you access to several non-standard RPC methods, which will allow you to inspect, debug and set certain debugging flags during runtime.
eth Provides several extensions to the standard “eth” JSON-RPC namespace.
les Allows you to manage LES server settings, including client parameters and payment settings for prioritized clients.
miner Allows you to remote control the node’s mining operation and set various mining specific settings.
personal Manages private keys in the key store.
txpool Gives you access to several non-standard RPC methods to inspect the contents of the transaction pool containing all the currently pending transactions as well as the ones queued for future processing.



Parity Ethereum




Hyperledger Besu





Libraries and Tools

Wallet Description Type Remarks
MetaMask A crypto wallet & gateway to blockchain apps Web, Mobile
WalletConnect an open protocol for connecting desktop Dapps to mobile Wallets using end-to-end encryption by scanning a QR code.
Fortmatic allows you to easily integrate your app with the Ethereum blockchain



Command Description Remarks
solc-select versions Prints out all installed solc versions
solc-select use version Change the version of global solc compiler
solc-select install List available solc versions
solc-select install version [version ...] Install solc versions



Package Description Remarks
web3.eth Allows you to interact with an Ethereum blockchain and Ethereum smart contracts.
web3.eth.accounts Contains functions to generate Ethereum accounts and sign transactions and data.
web3.eth.Contract The object makes it easy to interact with smart contracts on the ethereum blockchain.
web3.utils Provides utility functions for Ethereum dapps and other web3.js packages.
web3.eth.abi Let you de- and encode parameters to ABI (Application Binary Interface) for function calls to the EVM.
API Parameters Description Remarks
web3.eth.getNodeInfo Returns the current client version web3_clientVersion
web3.eth.getChainId Returns the chain ID of the current connected node as described in the EIP-695 eth_getChainId
web3.eth.net.getId Gets the current network ID net_version
web3.eth.blockNumber Returns the current block number
web3.eth.getBlock Returns a block matching the block number or block hash
web3.eth.getAccounts Function callback Will return a list of the unlocked accounts in the Web3 wallet or it will return the accounts from the currently connected node
web3.eth.getBalance String address
String|Number defaultBlock
Function callback
Get the balance of an address at a given block
web3.eth.getTransactionReceipt Returns the receipt of a transaction by transaction hash.
web3.eth.call Executes a message call transaction, which is directly executed in the VM of the node, but never mined into the blockchain.
web3.eth.sendTransaction Sends a transaction to the network. transaction object (from, to, value, gas, gasPrice, data, nonce)
web3.eth.sendSignedTransaction String data Sends an already signed transaction
web3.eth.sign String data, String addr Signs data using a specific account. account needs to be unlocked
web3.eth.signTransaction Object tx, String addr Signs a transaction. account needs to be unlocked
web3.eth.accounts.hashMessage String msg Hashes the given message using keccak256 after UTF-8 HEX decoding and envelop ("\x19Ethereum Signed Message:\n" + msg.length + msg)
web3.eth.accounts.sign String data, String prvKey Signs arbitrary data. "\x19Ethereum Signed Message:\n" + msg.length + msg
web3.eth.accounts.signTransaction Object tx, String prvKey Signs an Ethereum transaction with a given private key.
web3.eth.accounts.recover Recovers the Ethereum address which was used to sign the given data.
web3.eth.accounts.recoverTransaction Recovers the Ethereum address which was used to sign the given RLP encoded transaction. The RLP encoded transaction
web3.eth.accounts.privateKeyToAccount String privateKey Creates an account object from a private key. create not an account but an account object
web3.utils.sha3 String string Calculate the sha3 of the input. Alias: keccak256
web3.utils.asciiToHex String string Transform an ASCII string into a valid bytes4, bytes8 etc Alias: fromAscii()
web3.utils.utf8ToHex String string Returns the HEX representation of a given UTF-8 string. Alias : stringToHex(), fromUtf8()
web3.eth.abi.encodeFunctionSignature Encodes the function name to its ABI signature, which are the first 4 bytes of the sha3 hash of the function name including types selector
web3.eth.abi.encodeFunctionCall Object jsonInterfacer
Array parameters
Encodes a function call using its JSON interface object and given parameters.
web3.eth.abi.encodeParameter String|Object type
Mixed parameter
Encodes a parameter based on its type to its ABI representation.
web3.eth.abi.encodeParameters Array<String|Object>|Object types
Array parameters
Encodes a function parameters based on its JSON interface object.
  // safely convert any given value (including BigNumber.js instances) into a BN.js instance, 
  // for handling big numbers in JavaScript.

  // calculate the sha3 of the input.

  // returns the HEX representation of a given ASCII string.
  web3.utils.fromAscii(String); // deprecated
Type Binding
Solidity JavaScript Remarks
uint<n> BN bn.js
bool boolean
string string
bytes<n> string hexadecimal representation of bytes with '0x' prefix


  • Web3 Configuration
    • Setting Authorization header to specify bearer access token is a little bit different between Web3HttpProvider and Web3WsProvider.

Sample Codes

Basic Usage
$ truffle console --network ropsten
Warning: Please rename truffle.js to truffle-config.js to ensure Windows compatibility.
truffle(ropsten)> web3.version
truffle(ropsten)> web3.eth.net.getId()
truffle(ropsten)> web3.eth.getBlockNumber().then(v => v.toLocaleString())
truffle(ropsten)> web3.eth.getProtocolVersion()
truffle(ropsten)> web3.eth.getNodeInfo()
truffle(ropsten)> web3.eth.getCoinbase()
truffle(ropsten)> web3.eth.getCoinbase().then(web3.eth.getBalance).then(v => parseInt(v).toLocaleString())
truffle(ropsten)> web3.eth.net.getPeerCount()
truffle(ropsten)> web3.eth.isMining()
truffle(ropsten)> web3.eth.getAccounts()
[ ... ]
truffle(ropsten)> web3.eth.getAccounts().then(accts => accts.forEach(acct => web3.eth.getBalance(acct).then(amt => console.log(acct, amt))))
truffle(ropsten)> Promise.all(accounts.map(acct => web3.eth.getBalance(acct).then(balance => [acct, balance])))
truffle(ropsten)> web3.eth.getGasPrice().then(v => parseInt(v).toLocaleString())
truffle(ropsten)> web3.eth.getBlock("latest").then(b => parseInt(b.gasLimit).toLocaleString())
truffle(ropsten)> web3.eth.getBlock(0)
{ difficulty: '1048576',
  gasLimit: '0x1000000',
  gasUsed: '0x0',
  miner: '0x0000000000000000000000000000000000000000',
  nonce: '0x0000000000000042',
  number: 0,
  size: 540,
  timestamp: 0,
  totalDifficulty: '1048576',
  transactions: [],
  uncles: [] }
ABI Encoding of Parameters
truffle(development)> web3.eth.abi.encodeParameters(['string','string','bool','bool'], ['Colorspace','RGB',true,true])
truffle(development)> web3.eth.abi.encodeParameter('string', 'Colorspace')
truffle(development)> web3.eth.abi.encodeParameter('string', 'RGB')
truffle(development)> web3.eth.abi.encodeParameter('bool', true)
truffle(development)> web3.eth.abi.encodeParameter('bool', true)
Event Subscription

Sample code inside Truffle console to subscribe event using web3.eth.subscribe() function via web socket. The address 0xa36085F69e2889c224210F603D836748e7dC0088 below is an address of ChainLink's token contract at Kovan network.

$ truffle console --network kovan_ws
truffle(kovan_ws)> let options = { address: '0xa36085F69e2889c224210F603D836748e7dC0088' };
truffle(kovan_ws)> let subscription = web3.eth.subscribe('logs', options, (err, result) => { if(err) console.error(err); });
truffle(kovan_ws)> subscription.on('data', function(log) { console.log(log); });
Using BigInt to formatting BN number
const tx = await web3.eth.getTransaction(rcpt.transactionHash);
const cost = web3.utils.fromWei(web3.utils.toBN(rcpt.gasUsed).mul(web3.utils.toBN(tx.gasPrice)));
measures.push({"fn": title,
  "gas": BigInt(rcpt.gasUsed).toLocaleString(),
  "gas price": BigInt(tx.gasPrice).toLocaleString(),
  "cost (Ether)": cost,
  "time (ms)": (Date.now() - startAt).toLocaleString()
web3.eth.getBalance(accounts[0]).then(b => BigInt(b).toLocaleString())


Package Description Documentation API Remarks
@ethereumjs/common Resources common to all EthereumJS implementations chains, hardforks
ethereumjs-util A collection of utility functions for Ethereum API Address, Account, ECDSASignature, BN, rlp
ethereumjs-wallet A lightweight wallet implementation API Wallet class, EthereumHDKey class
@ethereumjs/tx Implements schema and functions related to Ethereum's transaction API class TransactionFactory

abstract class BaseTransaction
class Transaction (Legacy Transaction)
class FeeMarketEIP1559Transaction
class AccessListEIP2930Transaction




Package Description Documentation Remarks
BIP39 JavaScript implementation of Bitcoin BIP39: Mnemonic code for generating deterministic keys BIP-39



  • API Documentation
Version API
4.5.18 Web3j Core API
Web3j Crypto API
Web3j Utils API
  • Core APIs
                                            +------------ Ethereum
  JsonRpc2_0Web3j ---------------- Web3j ---|
                     implements             +------------ Web3jRx
Class Source API Remark
public class HttpService extends Service HttpService.java HTTP implementation of our services API
org.web3j.protocol.Service Service.java Base service implementation
public class JsonRpc2_0Web3j implements Web3j JsonRpc2_0Web3j.java JSON-RPC 2.0 factory implementation
interface org.web3j.protocol.Web3j Web3j.java extends Ethereum, Web3jRx
interface org.web3j.protocol.core.Ethereum Ethereum.java JSON-RPC methods
interface org.web3j.protocol.rx.Web3jRx Web3jRx.java
interface org.web3j.quorum.Quorum Quorum.java extends Web3j
org.web3j.tx.Contract Contract.java
org.web3j.protocol.core.RemoteCall<T> RemoteCall.java
org.web3j.protocol.core.methods.request.Transaction Transaction.java
abstract org.web3j.abi.TypeReference<T extends org.web3j.abi.datatypes.Type> TypeReference.java
org.web3j.abi.datatypes.Function Function.java
  • ABI Types
  Type<T> ---+--- NumericType implements Type<BigInteger> ---+--- IntType ---+--- Uint ---+--- Uint8
             |                                                |               |            |
             |                                                |               |            +--- Uint16
             |                                                |               |
             |                                                |               +--- Int  ---+--- Int8
             |                                                |                            |
             |                                                |                            +--- Int8
             |                                                |                                      
             |                                                +--- FixedPointType ---+--- Ufixed
             |                                                                       |
             |                                                                       +--- Fixed
             +--- BytesType implements Type<bytes[]> ---+--- Bytes ---+--- Bytes1
             |                                          |             |
             |                                          |             +--- Bytes2
Crypto/Util APIs
Class Method Description Remarks
static ECKeyPair createEcKeyPair(SecureRandom random) Generate Elliptic Curve key pair for a Ethereum account
static ECKeyPair createEcKeyPair() Generate Elliptic Curve key pair for a Ethereum account
static String getAddress(ECKeyPair pair) address in 40-bytes hexadecimal format. Without prefix
static String toChecksumAddress(String address) Checksum address encoding as per EIP-55. EIP-55, With '0x' prefix
Sign Transaction signing logic.
static createTransaction createTransaction(...) create raw transaction object that is not signed transaction object
static byte[] signMessage(RawTransaction rawTx, Credentials cred) sign a raw transaction
static BigInteger toBigInt(String hexValue) Get integer representation from the hexadecimal representation for private key, public key, or so on
static String toHexStringNoPrefixZeroPadded(BigInteger value, int size) Get hexadecimal represenation with prefix `0x` and in the specified length from the integer repesentation for private key, public key, or so on
static String toHexString(byte[] input) Get hexadecimal representation of the specified byte array with prefix '0x'
static String toHexStringNoPrefix(byte[] input) Get hexadecimal representation fo the specified byte array without prefix
byte[] hexStringToByteArray(String input) Convert string in hexdecimal format into byte array after removing prefix `0x` if any
// create Elliptic Curved key pair
ECKeyPair pair = Keys.createEcKeyPair();

// get EIP-55(checksum) address with '0x' prefix from EC key-pair
String addr = Keys.toChecksumAddress(Keys.getAddress(pair));

// or get EIP-55 address with '0x' prefix from public key
add = Keys.toChecksumAddress(Keys.getAddress(pair.getPublicKey());

// get private key in hexadecimal string without any prefix - 64 characters with left zero padding
Numeric.toHexStringNoPrefixZeroPadded(pair.getPrivateKey(), Keys.PRIVATE_KEY_LENGTH_IN_HEX);

// get public key in hexadecimal string without any prefix - 128 characters with left zero padding
Numeric.toHexStringNoPrefixZeroPadded(pair.getPublicKey(), 2 * Keys.PRIVATE_KEY_LENGTH_IN_HEX);

// convert hexadecimal string to integer in 'BigInteger' type
final BigInteger gas = Numeric.toBigInt("0x12e140");


Package Description Sources Remarks
eth-lib Lightweight Ethereum libraries. https://github.com/maiavictor/eth-lib
elliptic Fast elliptic-curve cryptography in a plain javascript implementation. https://github.com/indutny/elliptic
secp256k1 Provides native bindings to bitcoin-core/secp256k1. https://github.com/cryptocoinjs/secp256k1-node


Tips and Tricks

Hexbinary, byte array and string
import jakarta.xml.bind.DatatypeConverter;

  public void testHexStringToString() {

    final String hStr = "0x477265656e";
    final byte[] bytes = DatatypeConverter.parseHexBinary(
        StringUtils.removeStart(hStr, "0x")); // will be {71,114,101,101,110}
    final String str = new String(bytes);
    Assertions.assertEquals("Green", str);

    this.logger.info("Hex Binary Representation: '{}'", hStr);
    this.logger.info("Byte Array: {}", ArrayUtils.toString(bytes));
    this.logger.info("String: '{}'", str);

    final String hStr2 = "0x5768697465000000000000000000000000000000000000000000000000000000";
    final byte[] bytes2 = DatatypeConverter.parseHexBinary(
        StringUtils.removeStart(hStr2, "0x"));	// will be {87,104,105,116,101,0,...,0}

    final String str2 = new String(bytes2);	
    Assertions.assertNotEquals("White", str2);
    Assertions.assertEquals(32, str2.length());
    Assertions.assertEquals("White", str2.trim());

    this.logger.info("Hex Binary Representation: {}", hStr2);
    this.logger.info("Byte Array: {}", ArrayUtils.toString(bytes2));
    this.logger.info("String: {}", str2);


  • https://github.com/ethereum/web3.py
  • Desc. : A Python library for interacting with Ethereum, inspired by web3.js.
  • License : MPL-2.0 (Mozilla Public License 2.0)
  • Written in : Python


Package Description Documentation Sources Remarks
Web3.py A Python library for interacting with Ethereum, inspired by web3.js. stable
eth-account Sign Ethereum transactions and messages with local private keys stable https://github.com/ethereum/eth-account/
eth-keys A common API for Ethereum key operations with pluggable backends. https://github.com/ethereum/eth-keys/
eth-utils Common utility functions for python code that interacts with Ethereum https://github.com/ethereum/eth-utils keccack, ABI utils, Crypto utils, Address utils, ...
eth-typing Common type annotations for ethereum python packages. stable https://github.com/ethereum/eth-typing


Class API Description Remarks
api the current Web3 version
clientVersion the current client version
web3.eth.Eth Exposes the following properties and methods to interact with the RPC APIs under the eth_ namespace.
eth_account.account.Account The primary entry point for working with Ethereum private keys.
eth_keys.KeyAPI the primary API for interacting with the eth-keys libary.

Basic Usage

Using Brownie and Web3.py together.

>>> web3.eth.coinbase
>>> web3.eth.getBalance(web3.eth.coinbase)
>>> for acc in web3.eth.accounts[:10]: print(f'{acc}, {web3.eth.getBalance(acc):,}')
0xb009cd53957c0D991CAbE184e884258a1D7b77D9, 9,995,080,120,300,000,000,000
0x05f9301Be8F3C133fC474F8d538fD732CaCa274c, 10,000,000,000,000,000,000,000
0x3DC9b4063a130535913137E40Bed546Ff93b1131, 10,000,000,000,000,000,000,000
0x770b1A8d293d152B8Cc9fC01531B1baB3469AF05, 10,000,000,000,000,000,000,000
0xAB3ca295454D4A4de79aE32474d2C82f2D0836b1, 10,000,000,000,000,000,000,000
0x876e0cab3dfC5d2EA19f9A9e6029E8C1b90452Ed, 10,000,000,000,000,000,000,000
0xBb9Bb87EfE2Cf5E024f32c5943311FdA471848Ca, 9,999,898,673,800,000,000,000
0x950ea7798112705f487F657E93Fe5D64557CD138, 9,999,950,898,650,000,000,000
0xA797051B95915F31464440A590332e3360bfEDb9, 9,999,696,040,100,000,000,000
0x9Ebe0ec1f5f2c0f6BA7d9f7187d6f5c540F2b5fa, 10,000,000,000,000,000,000,000
>>> web3.eth.blockNumber
>>> web3.eth.getBlock('latest')
AttributeDict({'number': 289, 'hash': HexBytes('0x6e432624d1d6730962cab95e48bf67be818a589f038851d63af3b8c748992633'), 'parentHash': HexBytes('0x8187ad82fc911ffe4658e491dc561ff1526690f4380ea6ff4250b80b865f363e'), 'mixHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'nonce': HexBytes('0x0000000000000000'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'transactionsRoot': HexBytes('0x2ab22b1c6b26e27b38af339fa2680a78801de67d7caba46b8c7a01f9fdca9ec7'), 'stateRoot': HexBytes('0x395bc4b216dfcd92a25124d3233010e5c130dc3f07cfd75a0a4c7670346a3f62'), 'receiptsRoot': HexBytes('0xc216ea002b476d3fcf65c0e0d5412cb69831da68ded61246d306b6060c57d82f'), 'miner': '0x0000000000000000000000000000000000000000', 'difficulty': 0, 'totalDifficulty': 0, 'extraData': HexBytes('0x'), 'size': 1000, 'gasLimit': 400000000, 'gasUsed': 26697, 'timestamp': 1609224132, 'transactions': [HexBytes('0x4ef99b474888675edb0f3aa28c310eeb506fa00390f06723b58cc960c9b1ff48')], 'uncles': []})
>>> web3.eth.getBlock(0)
AttributeDict({'number': 0, 'hash': HexBytes('0x515ff4d96e5ab4131d4cd9443ba4dd51ba92b1402f2a79416372efa9945b5094'), 'parentHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'mixHash': HexBytes('0x0000000000000000000000000000000000000000000000000000000000000000'), 'nonce': HexBytes('0x0000000000000000'), 'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'), 'logsBloom': HexBytes('0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), 'transactionsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'stateRoot': HexBytes('0xb477958b9dd0e44345b14ca1dc539ee49098710340252b3ba9ecb289a93a4b89'), 'receiptsRoot': HexBytes('0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'), 'miner': '0x0000000000000000000000000000000000000000', 'difficulty': 0, 'totalDifficulty': 0, 'extraData': HexBytes('0x'), 'size': 1000, 'gasLimit': 400000000, 'gasUsed': 0, 'timestamp': 1609222192, 'transactions': [], 'uncles': []})



Contract Source Description Remarks
Ownable Ownable.sol
AccessControl AccessControlEnumerable.sol allows children to implement role-based access control mechanisms.
EnumerableSet EnumerableSet.sol Library for managing sets of primitive types. Bytes32Set, AddressSet, UintSet
EnumerableMap EnumerableMap.sol Library for managing an enumerable variant of Solidity’s mapping type. UintToAddressMap]
ERC 20 ERC20 contracts the most widespread token standard for fungible assets
ERC 721 ERC721 contracts the de-facto solution for non-fungible tokens
ERC 777 ERC 777 contracts a richer standard for fungible tokens
Test Helpers
  • Desc. : Assertion library for Ethereum smart contract testing
API Description Remarks
Test Environment
  • Desc. : Blazing fast smart contract testing.




  • Data Structure
network = name, rpc-url, chain-id, [currency-symbol], [block-explorer-url]
  • Connecting
Network Chain ID Currency Symbol RPC URL Block Explorer
Binance Smart Chain Mainnet 56 BNB https://bsc-dataseed.binance.org/ https://bscscan.com
Binance Smart Chain Testnet 97 BNB https://data-seed-prebsc-1-s1.binance.org:8545/ https://testnet.bscscan.com
Klaytn Testnet (Baobab) 1001 KLAY https://api.baobab.klaytn.net:8651/ https://baobab.scope.klaytn.com/


  • NFT tokens in your MetaMask wallet
    • While you can add NFTs as custom tokens in the extension, you will not be able to see them natively in the UI.
    • MetaMask Mobile displays NFTs under Collectibles. ... We pull our NFT data from opensea.io, our 3rd party repository for all NFTs.
    • NFT token 1155 is still in development. Our product team is planning to add it sometime in Quarter 4 2021.


Remix IDE




Command Description Options Remarks
init Initialize new and empty Ethereum project --force
compile Compile contract source files. --all, --quiet, --network, --compiler, --config
compile --list Fetching solc version list from solc-bin. --all solc-bin
migrate, deploy Run migrations to deploy contracts. --reset, --f, --to--compile-none --skip-dry-run, --network, --quiet
test Runs some or all tests within the test/ directory as specified. --compile-none, --migrate-none, --show-events, --network
version Show version number and exit Truffle, Gananche, Solidity, Node, Web3.js
  • Typical commandlines
$ truffle deploy --f 2 --to 2 --compile-none --skip-dry-run --network rinkeby

$ truffle test --compile-none --migrate-none --show-events --network rinkeby test/MyContract.js
  • Truffle Object for Contract
Element Type/Format/Value Description Remarks
contractName string(^[a-zA-Z_][a-zA-Z0-9_]*$) Name used to identify the contract
abi string Interface description returned by compiler for source application/json
bytecode string(^0x0$|^0x([a-fA-F0-9]{2}|__.{38})+$) Bytecode sent as contract-creation transaction data, with unresolved link references
deployedBytecode ^0x([a-fA-F0-9]{2}|__.{38})+$) On-chain deployed contract bytecode, with unresolved link references
source string
sourcePath string
userdoc JSON
devdoc JSON
sourceMap string Source mapping for contract-creation transaction data bytecode
deployedSourceMap string Source mapping for contract bytecode
ast object
legacyAST object
compiler object
compiler.name string
compiler.version string
schemaVersion string([0-9]+\\.[0-9]+\\.[0-9]+)
updatedAt date-time
autoGas boolean
gasMultiplier number default : 1.25
numberFormat string BN
  • Truffle Object for Contract Instance
Entry Type/Format/Value Description Remarks
constructor function
methods object
abi object JSON description of contract ABI What is an ABI?
address string
transactionHash string
contract object web3.eth.Contract type instance for this contract instance
sendTransaction function
send function
allEvents function
getPastEvents function
  • Basic Introspection
    • Object.keys(Artifact)
    • Object.keys(Artifact.toJSON())
    • Artifact.abi
    • artifact = await Artifact.new(...)
    • Object.keys(artifact)
    • Object.keys(artifact.methods)
    • Ojbect.keys(artifact.contract)
truffle(development)> Object.keys(Migrations)
truffle(development)> Object.keys(Migrations.toJSON())
truffle(development)> Migrations.abi
    inputs: [],
    name: 'last_completed_migration',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x445df0ac'
    inputs: [],
    name: 'owner',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function',
    constant: true,
    payable: undefined,
    signature: '0x8da5cb5b'
    inputs: [ [Object] ],
    name: 'setCompleted',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function',
    constant: undefined,
    payable: undefined,
    signature: '0xfdacd576'
truffle(development)> Migrations._properties
  contract_name: { get: [Function: get], set: [Function: set] },
  contractName: { get: [Function: get], set: [Function: set] },
  gasMultiplier: { get: [Function: get], set: [Function: set] },
  timeoutBlocks: { get: [Function: get], set: [Function: set] },
  autoGas: { get: [Function: get], set: [Function: set] },
  numberFormat: { get: [Function: get], set: [Function: set] },
  abi: { get: [Function: get], set: [Function: set] },
  metadata: [Function: metadata],
  network: [Function: network],
  networks: [Function: networks],
  address: { get: [Function: get], set: [Function: set] },
  transactionHash: { get: [Function: get], set: [Function: set] },
  links: [Function: links],
  events: [Function: events],
  binary: [Function: binary],
  deployedBinary: [Function: deployedBinary],
  unlinked_binary: { get: [Function: get], set: [Function: set] },
  bytecode: { get: [Function: get], set: [Function: set] },
  deployedBytecode: { get: [Function: get], set: [Function: set] },
  sourceMap: { get: [Function: get], set: [Function: set] },
  deployedSourceMap: { get: [Function: get], set: [Function: set] },
  source: { get: [Function: get], set: [Function: set] },
  sourcePath: { get: [Function: get], set: [Function: set] },
  legacyAST: { get: [Function: get], set: [Function: set] },
  ast: { get: [Function: get], set: [Function: set] },
  compiler: { get: [Function: get], set: [Function: set] },
  schema_version: [Function: schema_version],
  schemaVersion: [Function: schemaVersion],
  updated_at: [Function: updated_at],
  updatedAt: [Function: updatedAt],
  userdoc: [Function: userdoc],
  devdoc: [Function: devdoc],
  networkType: { get: [Function: get], set: [Function: set] },
  immutableReferences: { get: [Function: get], set: [Function: set] },
  generatedSources: { get: [Function: get], set: [Function: set] },
  deployedGeneratedSources: { get: [Function: get], set: [Function: set] },
  db: { get: [Function: get], set: [Function: set] }
truffle(development)> m = await Migrations.new()
truffle(development)> Object.keys(m)
truffle(development)> Object.keys(m.methods)
[ 'last_completed_migration()', 'owner()', 'setCompleted(uint256)' ]
truffle(development)> Object.keys(m.contract)


  • How to use bignumbers in truffle tests? (Feb 14 '19)
    • Avoid using toNumber() on any value returned from a contract function
    • Keep the returned value in its original type (BigNumber on Truffle 4.x / web3 0.x, and BN on Truffle 5.x / web3 1.x)
    • For printout, you're best off using toFixed() (or toLocaleString() maybe)


Plugin Description Remarks
truffle-contract-size displays the contract size of all or a selection of your smart contracts in kilobytes.
truffle-plugin-verify allows you to automatically verify your smart contracts' source code on Etherscan, straight from the Truffle CLI.
truffle-flattener concats solidity files from Truffle and Buidler projects with all of their dependencies.


Example Description Remarks
example-truffle-library Example project showing how to use Truffle to create javascript libraries
truffle-webpack-demo A demo Webpack + React App using truffle-solidity-loader
truffle-typescript-example Minimal example integration of Truffle + TypeScript + TestRPC run in docker, for writing smart contracts on Ethereum blockchain.
Truffle Box A set of boilerplates to help developers quickly build distributed applications on the Ethereum blockchain with Truffle.

Tips and Tricks

Typical Truffle Configuration
// https://github.com/trufflesuite/truffle/tree/v5.1.5/packages/hdwallet-provider
// https://web3js.readthedocs.io/en/v1.3.0/web3.html#providers
// https://infura.io/docs/ethereum#section/Choose-a-Network
// https://iancoleman.io/bip39/
const HDWalletProvider = require("@truffle/hdwallet-provider");
const Web3HttpProvider = require('web3-providers-http');
const Web3WsProvider = require('web3-providers-ws');

// https://www.npmjs.com/package/web3-providers-http
const httpOptions = {
  keepAlive: true, timeout: 70000

// https://www.npmjs.com/package/web3-providers-ws
const wsOptions = {
  timeout: 600000,

  clientConfig: {
    maxReceivedFrameSize: 100000000,
    maxReceivedMessageSize: 100000000,

    keepalive: true,
    keepaliveInterval: 60000,

  reconnect: { auto: true, delay: 5000, maxAttempts: 5, onTimeout: false }

// http://truffleframework.com/docs/advanced/configuration
// https://infura.io/docs/gettingStarted/chooseaNetwork
// https://ethereum.stackexchange.com/questions/27048/comparison-of-the-different-testnets
module.exports = {
  contracts_build_directory: "./build/truffle",  // default: ./build/contracts

  networks: {
    // https://www.trufflesuite.com/docs/truffle/reference/choosing-an-ethereum-client#truffle-develop
    builtin: {    // truffle built-in client : aka `truffle develop`
      host: '',
      port: 9545,
      network_id: "*"

    development: {  // local Ganache or Ganache CLI
      host: '',
      port: 8545,
      network_id: '31',
      gas: 3E8,
      gasPrice: 0,
      websockets: true

    mainnet: {
      provider: () => new HDWalletProvider(
        "https://mainnet.infura.io/v3/" + process.env.INFURA_PROJECT_ID),
      network_id: '1'      

    //Ropsten : PoW
    //GitHub : https://github.com/ethereum/ropsten/
    //Explorer : https://ropsten.etherscan.io/
    //Faucet : https://faucet.ropsten.be/
    ropsten: {
      provider: () => new HDWalletProvider(
        "https://ropsten.infura.io/v3/" + process.env.INFURA_PROJECT_ID),
      network_id: '3',
      gas: 7E6,
      gasPrice: 1E10

    //Rinkeby : PoA
    //Explorer : https://rinkeby.etherscan.io/
    //Faucet : https://faucet.rinkeby.io/
    //Avg. Block Time : 15s
    rinkeby: {
      provider: () => new HDWalletProvider({
        mnemonic: process.env.BIP39_MNEMONIC, 
        providerOrUrl: new Web3HttpProvider("https://rinkeby.infura.io/v3/" + process.env.INFURA_PROJECT_ID, httpOptions),
        pollingInterval: 10000
      network_id: '4',
    rinkeby_ws: {
      provider: () => {
        // Monkey patch to support `web3.eth.subscribe()` function
        // https://github.com/trufflesuite/truffle/issues/2567
        const wsProvider = new Web3WsProvider("wss://rinkeby.infura.io/ws/v3/" + process.env.INFURA_PROJECT_ID, wsOptions);
        HDWalletProvider.prototype.on = wsProvider.on.bind(wsProvider);
        return new HDWalletProvider({
          mnemonic: process.env.BIP39_MNEMONIC,
          providerOrUrl: wsProvider,
          pollingInterval: 10000
      network_id: '4', //https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version
      websockets: true, 

    //Kovan : PoA
    //GitHub : https://github.com/kovan-testnet/
    //Explorer : https://kovan.etherscan.io/
    //Faucet : https://github.com/kovan-testnet/faucet
    //Avg. Block Time : 4s
    kovan: {
      provider: () => new HDWalletProvider({
        mnemonic: process.env.BIP39_MNEMONIC,
        providerOrUrl: new Web3HttpProvider("https://kovan.infura.io/v3/" + process.env.INFURA_PROJECT_ID, httpOptions),
        pollingInterval: 2000
      network_id: '42', //https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version
      //gas: 7E6,
      //gasPrice: 5E10
    kovan_ws: {
      provider: () => {
        // Monkey patch to support `web3.eth.subscribe()` function
        // https://github.com/trufflesuite/truffle/issues/2567
        const wsProvider = new Web3WsProvider("wss://kovan.infura.io/ws/v3/" + process.env.INFURA_PROJECT_ID, wsOptions);
        HDWalletProvider.prototype.on = wsProvider.on.bind(wsProvider);
        return new HDWalletProvider({
          mnemonic: process.env.BIP39_MNEMONIC,
          providerOrUrl: wsProvider,
          pollingInterval: 2000
      network_id: '42', //https://github.com/ethereum/wiki/wiki/JSON-RPC#net_version
      websockets: true, 
      //gas: 7E6,
      //gasPrice: 5E10

    // Goerli : PoA
    // GitHub : https://github.com/goerli/testnet
    // Explorer : https://goerli.etherscan.io/
    // Faucet : 
    // Avg. Block Time : 15s
    goerli: {
      provider: () => new HDWalletProvider({
        mnemonic: process.env.BIP39_MNEMONIC,
        providerOrUrl: new Web3HttpProvider("https://goerli.infura.io/v3/" + process.env.INFURA_PROJECT_ID, httpOptions),
        pollingInterval: 15000
      network_id: '5'
    // Klaytn Testnet
    baobab: {
      provider: () => new HDWalletProvider({
        mnemonic: process.env.BIP39_MNEMONIC,
        providerOrUrl: new Web3HttpProvider("https://api.baobab.klaytn.net:8651/", httpOptions),
        pollingInterval: 2000
      network_id: '1001'
    // Binance Smart Chain Testnet
    // https://docs.binance.org/smart-chain/developer/deploy/truffle.html
    // GitHub : 
    // Explorer : https://testnet.bscscan.com/
    // Faucet : https://testnet.binance.org/faucet-smart
    // Avg. Block Time : 3s
    bsc_test: {
      provider: () => new HDWalletProvider({
        mnemonic: process.env.BIP39_MNEMONIC,
        providerOrUrl: new Web3HttpProvider("https://data-seed-prebsc-1-s1.binance.org:8545", httpOptions),
        pollingInterval: 3500
      network_id: '97',
      confirmations: 10,
      timeoutBlocks: 200,
      skipDryRun: true

  // https://github.com/mochajs/mocha/blob/v5.2.0/lib/mocha.js#L64
  // https://mochajs.org/#command-line-usage
  mocha: {
    useColors: true,
    enableTimeouts: true,
    timeout: 180000

  // http://truffleframework.com/docs/advanced/configuration
  // https://solidity.readthedocs.io/en/v0.6.6/using-the-compiler.html#target-options
  compilers: {
    solc: {
      version: "pragma",  // https://github.com/trufflesuite/truffle/releases/tag/v5.2.0
      //parser: "solcjs",
      settings: {
        optimizer: {
          enabled: false,
          runs: 200
        evmVersion: "istanbul"  // berlin, istanbul, petersburg, constantinople, byzantium
Typical Truffle Test-case
const Token = artifacts.require("TrustedToken");
const Chance = require('chance');
const toBN = web3.utils.toBN;
const { constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');

//Truffle test in JavaScript : https://www.trufflesuite.com/docs/truffle/testing/writing-tests-in-javascript
//Truffle Contract Guide : https://www.trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts
//Truffle Contract Package : https://github.com/trufflesuite/truffle/tree/master/packages/contract
//Mocha Documentation : https://mochajs.org/#getting-started
//Chai Assert API : https://www.chaijs.com/api/assert/
//Chai Expect/Should API : https://www.chaijs.com/api/bdd/
//OpenZeppelin Test Helpers API : https://docs.openzeppelin.com/test-helpers/0.5/api
//web3 API : https://web3js.readthedocs.io/en/v1.2.11/
//chance.js : https://chancejs.com/
//bn.js : https://github.com/indutny/bn.js/
//JavaScript Reference (MDN) : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
//The Modern JavaScript Tutorial : http://javascript.info/

contract("TrustedToken Test Suite 1", async accounts => {
  'use strict';

  // avoid too many accounts
  if(accounts.length > 8) accounts = accounts.slice(0, 8);

  const EventNames = {
    Transfer: 'Transfer',
    Approval: 'Approval'

  async function createFixtures(){
    const chance = new Chance();
    const admin = chance.pickone(accounts);
    const token = await Token.new('Color Token', 'RGB', {from: admin});
    console.debug(`New token contract deployed - address: ${token.address}`);

    return [chance, admin, token];

  before(async() => {
    const table = [];
    let balance = 0;

    // Before test suite, unlock all accounts and display the balances
    for(const acct of accounts){
        await web3.eth.personal.unlockAccount(acct);
        balance = await web3.eth.getBalance(acct);
        await table.push([acct, balance]);

    console.debug(`The number of accounts : ${accounts.length}`);

  describe("Minting", () => {
    // mint(), totalSupply(), balanceOf()
    it("Minting tokens should increase the owners balance and total supply", async() =>{
      const [chance, admin, token] = await createFixtures();


    // mint(), grantRole()
    it("Only minter can 'mint' a token.", async() => {
      const [chance, admin, token] = await createFixtures();


  describe("Transfer", () => {

    // transfer(), mint()
    it("Transfer should decrease sender's balance and increase recipient's balance as much", async() => {
      const [chance, admin, token] = await createFixtures();

    // mint(), transfer(), totalSupply()
    it("Token transfer should not change total supply.", async() => {
      const [chance, admin, token] = await createFixtures();


    // transfer(), mint()
    it("Transfer to ZERO address is illegal.", async() => {
      const [chance, admin, token] = await createFixtures();



Estimate Gas
truffle(ropsten)> web3.eth.getBalance(accounts[1])
truffle(ropsten)> ExportableERC721.new.estimateGas("Test ERC721", "ABC", true, true, {from: accounts[1]})
truffle(ropsten)> web3.eth.getBalance(accounts[1])
Avoiding "nonce too low" Error
truffle(ropsten)> n = await web3.eth.getTransactionCount(accounts[7])});
truffle(ropsten)> r = await factory.grantRole('0x0', bridge.address, {from: accounts[7], nonce: await web3.eth.getTransactionCount(accounts[7])})
Access web3 contract object from Truffle contract object

Use contract property of Truffle contract instance object

truffle(rinkeby)> bridge = await ERC721Bridge2.at('0x...')
truffle(rinkeby)> bridge.contract.methods.deployTokenContract('Class Paintings', 'P', [accounts[1]], [], [], true, true).estimateGas({from: ...})






Command Description Remarks
brownie init Initialize a new brownie project
brownie compile Compile the contract source file
brownie test Run test cases in the tests/ folder
brownie run Run a script in the scripts/ folder
brownie console Load the console
brownie networks Manage network settings
brownie networks list [verbose=false] List existing networks
Class Description Attributes/Methods Remarks
ContractContainer holds all ProjectContract instances of the same type, and is used to deploy new instances of that contract. abi, signatures, topics, deploy(), at()
Contract used for interaction with already-deployed contracts that exist outside of a project.
ContractCall a non state-changing contract method without broadcasting a transaction, and returns the result.
ContractTx Broadcasts a transaction to a potentially state-changing contract method. Returns a TransactionReceipt.
EventDict used to hold all events that are fired in a transaction.



Mist Browser

Ganache CLI

#! /bin/bash

#   - Check the availability of the TCP port for Linux
#   - Setup 'logrotate' for Linux

readonly verbose=1  # 1: true, 0: false - Hard coded yet
readonly dryrun=0   # 1: true, 0: false - Not Used Yet
readonly uname=`uname -s`  # OS type
readonly script_dir=$(cd `dirname $0` && pwd)

declare data_dir
declare log_dir
case $uname in
Linux)  #Linux
MINGW*)  #Git Bash on Windows
  readonly run_dir=$(mkdir -p "${script_dir}/../run/ganache" && cd "${script_dir}/../run/ganache" && pwd)
Darwin*) #Bash on macOS
  readonly run_dir=$(mkdir -p "${script_dir}/../run/ganache" && cd "${script_dir}/../run/ganache" && pwd)
  echo "The current system is Unknown of which 'uname -s' shows '$uname'."
  exit 600

# check whether GNU getopt is available or not
if [ `getopt --test; echo $?` -ne 4 ]; then
  echo "The avaiable 'getopt' is not GNU getopt which supports long options."
  echo "For MacOS, install 'gnu-getopt' refering 'https://formulae.brew.sh/formula/gnu-getopt'."
  exit 410

options=$(getopt -o rb --long "refresh,background" --name 'ganache-cli-start-options' -- "$@");

if [ $? -ne 0 ]; then
  echo "Unable to parse command line, which expect '$command [-r|--refresh] [-b|--background]'."
  echo ""
  exit 400

eval set -- "$options"

declare refreshes=0   #false
declare backgrounds=0   #false
while true; do
  case "$1" in
    -r | --refresh )
      echo "refresh specified"
      shift ;;
    -b | --background )
      shift ;;
    -- ) shift; break ;;

if [ ! -d "${data_dir}" ]; then
  echo "Creating data directory on '${data_dir}'"
  if [ "$uname" == "Linux" ]; then
    sudo mkdir -p "${data_dir}"
    mkdir -p "${data_dir}"

if [ $refreshes -eq 1 ]; then
  echo "Removing all current data under '${data_dir}'"
  if [ "$uname" == "Linux" ]; then
    sudo rm -Rf "${data_dir}"
    sleep 3
    sudo mkdir -p "${data_dir}"
    rm -Rf "${data_dir}"
    sleep 3
    mkdir -p "${data_dir}"

cd "${script_dir}"

readonly eth_ver=`cat ganache-cli.properties | grep -E "^ethereum\.netVersion=" | sed -E 's/ethereum\.netVersion=//'`
readonly eth_host=`cat ganache-cli.properties | grep -E "^ethereum\.host=" | sed -E 's/ethereum\.host=//'`
readonly eth_port=`cat ganache-cli.properties | grep -E "^ethereum\.port=" | sed -E 's/ethereum\.port=//'`
readonly eth_gas_price=`cat ganache-cli.properties | grep -E "^ethereum\.gasPrice=" | sed -E 's/ethereum\.gasPrice=//'`
readonly eth_gas_limit=`cat ganache-cli.properties | grep -E "^ethereum\.gasLimit=" | sed -E 's/ethereum\.gasLimit=//'`
readonly eth_keys=`cat ganache-cli.properties | grep -E "^ethereum\.keys" | sed -E 's/ethereum\.keys\.[0-9]*=//'`

if [ $verbose -ne 0 ]; then
  echo "Ethereum Network ID : $eth_ver"
  echo "Ethereum Client Host Address: $eth_host"
  echo "Ethereum Client TCP Port: $eth_port"
  echo "Ethereum Gas Limit: $eth_gas_limit"
  echo "Ethereum Gas Price: $eth_gas_price"
  echo "Ethereum Private Keys for Accounts: "
  for key in $eth_keys; do echo "    $key"; done
  echo "uname: $uname"

case $uname in
Linux)  #Linux
  echo "Current system is 'Linux'"
MINGW*)  #Git Bash on Windows
  echo "Curreun system is 'Windows'"
  # check whether the address is alreasy in use or not
  if [ `netstat -anp tcp | awk '$4 == "LISTENING" {print $2}' | grep -E "^($eth_host|$eth_port$" | wc -l` -gt 0 ]; then
    readonly pid=`netstat -anop tcp | awk '$4 == "LISTENING" {print $2 " " $5}' | grep -E "^($eth_host|$eth_port\s" | head -n 1 | awk '{print $2}'`
    echo "The address '$eth_host:$eth_port' is already in use by the process of which PID is $pid."
    echo "Fail to start ganache-cli."
    exit 500
Darwin*) #Bash on macOS
  echo "Current system is 'macOS'"
  echo "Current system is Unknown of which 'uname -s' shows '$uname'."
  exit 600

# Ganache CLI : https://github.com/trufflesuite/ganache-cli#using-ganache-cli
# BIP 32 : https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
# BIP 39 : https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
# Options
#   - gasLimit : The block gas limit (defaults to 0x6691b7)
#   - gasPrice: The price of gas in wei (defaults to 20000000000)

cmd="ganache-cli --networkId $eth_ver \
            --host '$eth_host' \
            --port $eth_port \
            --gasPrice $eth_gas_price \
            --gasLimit $eth_gas_limit"

if [ -n "$eth_keys" ]; then
  echo ""
  echo "Private keys for Ethereum accounts are explicitly specified. They will be used."
  for key in $eth_keys;
    do cmd="${cmd} --account=\"${key},10000000000000000000000\""
  if [ -z "$BIP39_MNEMONIC" ]; then
    echo "'BIP39_MNEMONIC' env. variable is not defined, so implicit default mnemonic will be used."
    echo "If you want to use user defined mnemonic, define it via 'BIP39_MNEMONIC' env. variable and restart this script."
    cmd="${cmd} --deterministic"
    echo "'BIP39_MNEMONIC' env. variable is defined, so it will be used."
    cmd="${cmd} --mnemonic '$BIP39_MNEMONIC'"
  cmd="${cmd} --defaultBalanceEther 10000 --accounts 10 --secure"

cmd="${cmd} --unlock 0 --unlock 1 --unlock 2 --unlock 3 --unlock 4 \
            --hardfork 'petersburg' \
            --blockTime 0 \
            --db '${data_dir}' >> '${log_dir}'/ganache.log 2>&1"

if [ "$uname" == "Linux" ]; then
  cmd="sudo sh -c \"$cmd\""
  # cmd="sudo sh -c -- $cmd"

if [ $dryrun -ne 0 ]; then
  echo $cmd
  echo ""
  echo "This is 'DRY' run."
  echo "The right above command would be executed, if run again without 'dryrun' option."
  exit 700

if [ $backgrounds -eq 0 ]; then
  echo ""
  echo $cmd
  eval $cmd
  cmd=$cmd' &'
  echo ""
  echo $cmd
  eval $cmd

  if [ $? -eq 0 ]; then
    sleep 3
    tail "${log_dir}"/ganache.log -n 50
    echo "The loacal Ganache has started."
    echo "The log file is located at '${log_dir}/ganache.log'."


  • http://www.oraclize.it/
  • Desc. : the leading oracle service for smart contracts and blockchain applications, serving thousands of requests for day every day on Ethereum, Bitcoin and Rootstock.
  • License :


  • https://github.com/blockscout/blockscout
  • Desc. : provides a comprehensive, easy-to-use interface for users to view, confirm, and inspect transactions on EVM (Ethereum Virtual Machine) blockchains.
  • License : GPL-3.0 License





  • Components
    • a dynamically extensible language : a superset of the Solidity language
    • a compiler
    • a virtual machine


Ethereum plugin for Vault






    "exclude_optimization" : true,
    "exclude_informational": true,
    "exclude_low": true,
    "exclude_medium": false,
    "exclude_high": false,
    "solc": "solc",
    "solc_disable_warnings": true,
    "truffle_version": "truffle@5.1.52",
    "truffle_ignore_compile": true
  • Usage
$ slither --help
usage: slither target [flag]

target can be:
	- file.sol // a Solidity file
	- project_directory // a project directory. See https://github.com/crytic/crytic-compile/#crytic-compile for the supported platforms
	- 0x.. // a contract on mainet
	- NETWORK:0x.. // a contract on a different network. Supported networks: mainet,ropsten,kovan,rinkeby,goerli,tobalaba,bsc,testnet.bsc,arbi,testnet.arbi,poly,avax,testnet.avax,ftm

For usage information, see https://github.com/crytic/slither/wiki/Usage

optional arguments:
  -h, --help            show this help message and exit
  --version             displays the current version

Compile options:
  --compile-force-framework COMPILE_FORCE_FRAMEWORK
                        Force the compile to a given framework (solc,truffle,embark,dapp,etherlime,etherscan,vyper,waffle,brownie,solc-
                        Remove the metadata from the bytecodes
  --compile-custom-build COMPILE_CUSTOM_BUILD
                        Replace platform specific build command
  --ignore-compile      Do not run compile of any platform

Solc options:
  --solc SOLC           solc path
  --solc-remaps SOLC_REMAPS
                        Add remapping
  --solc-args SOLC_ARGS
                        Add custom solc arguments. Example: --solc-args "--allow-path /tmp --evm-version byzantium".
                        Disable solc warnings
  --solc-working-dir SOLC_WORKING_DIR
                        Change the default working directory
  --solc-solcs-select SOLC_SOLCS_SELECT
                        Specify different solc version to try (env config). Depends on solc-select
  --solc-solcs-bin SOLC_SOLCS_BIN
                        Specify different solc version to try (path config). Example: --solc-solcs-bin solc-0.4.24,solc-0.5.3
  --solc-standard-json  Compile all specified targets in a single compilation using solc standard json
                        Force the solc compiler to use the legacy json ast format over the compact json ast format

Truffle options:
                        Do not run truffle compile
  --truffle-build-directory TRUFFLE_BUILD_DIRECTORY
                        Use an alternative truffle build directory
  --truffle-version TRUFFLE_VERSION
                        Use a local Truffle version (with npx)
                        Use a simplified version of truffle-config.js for compilation
  --truffle-overwrite-version TRUFFLE_OVERWRITE_VERSION
                        Overwrite solc version in truffle-config.js (only if --truffle-overwrite-config)

Embark options:
                        Do not run embark build
                        Install @trailofbits/embark-contract-export and add it to embark.json

Dapp options:
                        Do not run dapp build

Etherlime options:
                        Do not run etherlime compile
                        Add arbitrary arguments to etherlime compile (note: [dir] is the the directory provided to crytic-compile)

Etherscan options:
                        Only compile if the source code is available.
                        Only looks for bytecode.
  --etherscan-apikey ETHERSCAN_API_KEY
                        Etherscan API key.
  --arbiscan-apikey ARBISCAN_API_KEY
                        Etherscan API key.
  --polygonscan-apikey POLYGONSCAN_API_KEY
                        Etherscan API key.
  --avax-apikey AVAX_API_KEY
                        Etherscan API key.
  --ftmscan-apikey FTMSCAN_API_KEY
                        Etherscan API key.
  --bscan-apikey BSCAN_API_KEY
                        Etherscan API key.
  --etherscan-export-directory ETHERSCAN_EXPORT_DIR
                        Directory in which to save the analyzed contracts.

Waffle options:
                        Do not run waffle compile
  --waffle-config-file WAFFLE_CONFIG_FILE
                        Provide a waffle config file

NPX options:
  --npx-disable         Do not use npx

Buidler options:
                        Do not run buidler compile
  --buidler-cache-directory BUIDLER_CACHE_DIRECTORY
                        Use an alternative buidler cache directory (default ./cache)
                        Disable directory name fix (see https://github.com/crytic/crytic-compile/issues/116)

hardhat options:
                        Do not run hardhat compile
  --hardhat-cache-directory HARDHAT_CACHE_DIRECTORY
                        Use an alternative hardhat cache directory (default ./cache)
  --hardhat-artifacts-directory HARDHAT_ARTIFACTS_DIRECTORY
                        Use an alternative hardhat artifacts directory (default ./artifacts)

                        Comma-separated list of detectors, defaults to all, available detectors: abiencoderv2-array, arbitrary-send, array-by-reference,
                        controlled-array-length, assembly, assert-state-change, backdoor, weak-prng, boolean-cst, boolean-equal, shadowing-builtin, constable-
                        states, constant-function-asm, constant-function-state, pragma, controlled-delegatecall, costly-loop, dead-code, delegatecall-loop,
                        deprecated-standards, divide-before-multiply, enum-conversion, external-function, function-init-state, erc20-interface,
                        erc721-interface, solc-version, incorrect-equality, incorrect-unary, shadowing-local, locked-ether, low-level-calls, mapping-deletion,
                        events-access, events-maths, missing-inheritance, missing-zero-check, incorrect-modifier, msg-value-loop, calls-loop, multiple-
                        constructors, name-reused, naming-convention, variable-scope, protected-vars, public-mappings-nested, redundant-statements,
                        reentrancy-benign, reentrancy-eth, reentrancy-events, reentrancy-unlimited-gas, reentrancy-no-eth, reused-constructor, rtlo,
                        shadowing-abstract, incorrect-shift, similar-names, shadowing-state, storage-array, suicidal, timestamp, too-many-digits, tx-origin,
                        tautology, unchecked-lowlevel, unchecked-send, unchecked-transfer, unimplemented-functions, erc20-indexed, uninitialized-fptr-cst,
                        uninitialized-local, uninitialized-state, uninitialized-storage, unprotected-upgrade, unused-return, unused-state, void-cst, write-
  --list-detectors      List available detectors
                        Comma-separated list of detectors that should be excluded
                        Exclude results that are only related to dependencies
                        Exclude optimization analyses
                        Exclude informational impact analyses
  --exclude-low         Exclude low impact analyses
  --exclude-medium      Exclude medium impact analyses
  --exclude-high        Exclude high impact analyses
                        Show all the findings

                        Comma-separated list fo contract information printers, available printers: cfg, constructor-calls, contract-summary, data-dependency,
                        echidna, function-id, function-summary, modifiers, call-graph, evm, human-summary, inheritance, inheritance-graph, slithir, slithir-
                        ssa, pausable, vars-and-auth, require, variable-order
  --list-printers       List available printers

Additional options:
  --json JSON           Export the results as a JSON file ("--json -" to export to stdout)
  --sarif SARIF         Export the results as a SARIF JSON file ("--sarif -" to export to stdout)
  --json-types JSON_TYPES
                        Comma-separated list of result types to output to JSON, defaults to detectors,printers. Available types:
  --zip ZIP             Export the results as a zipped JSON file
  --zip-type ZIP_TYPE   Zip compression type. One of lzma,stored,deflated,bzip2. Default lzma
  --markdown-root MARKDOWN_ROOT
                        URL for markdown generation
  --disable-color       Disable output colorization
  --filter-paths FILTER_PATHS
                        Comma-separated list of paths for which results will be excluded
  --triage-mode         Run triage mode (save results in slither.db.json)
  --config-file CONFIG_FILE
                        Provide a config file (default: slither.config.json)
  --solc-ast            Provide the contract as a json AST
  --generate-patches    Generate patches (json output only)



Category Rule Description Sample
Security Rules compiler-version "compiler-version": ["off"]



  • myth --help
$ myth --help
usage: myth [-h] [-v LOG_LEVEL] {safe-functions,analyze,a,disassemble,d,list-detectors,read-storage,function-to-hash,hash-to-address,version,help} ...

Security analysis of Ethereum smart contracts

positional arguments:
    safe-functions      Check functions which are completely safe using symbolic execution
    analyze (a)         Triggers the analysis of the smart contract
    disassemble (d)     Disassembles the smart contract
    list-detectors      Lists available detection modules
    read-storage        Retrieves storage slots from a given address through rpc
    function-to-hash    Returns the hash signature of the function
    hash-to-address     converts the hashes in the blockchain to ethereum address
    version             Outputs the version

optional arguments:
  -h, --help            show this help message and exit
  -v LOG_LEVEL          log level (0-5)
  • myth analyze --help
$ myth analyze --help
usage: myth analyze [-h] [--rpc HOST:PORT / ganache / infura-[network_name]] [--rpctls RPCTLS] [--infura-id INFURA_ID] [--solc-json SOLC_JSON] [--solv SOLV] [-c BYTECODE]
                    [-f BYTECODEFILE] [-a CONTRACT_ADDRESS] [--bin-runtime] [-o <text/markdown/json/jsonv2>] [-g GRAPH] [-j OUTPUT_FILE] [-m MODULES] [--max-depth MAX_DEPTH]
                    [--call-depth-limit CALL_DEPTH_LIMIT] [--strategy {dfs,bfs,naive-random,weighted-random}] [--transaction-sequences TRANSACTION_SEQUENCES]
                    [--beam-search BEAM_SEARCH] [-b N] [-t TRANSACTION_COUNT] [--execution-timeout EXECUTION_TIMEOUT] [--solver-timeout SOLVER_TIMEOUT]
                    [--create-timeout CREATE_TIMEOUT] [--parallel-solving] [--solver-log SOLVER_LOG] [--no-onchain-data] [--sparse-pruning] [--unconstrained-storage]
                    [--phrack] [--enable-physics] [-q] [--enable-iprof] [--disable-dependency-pruning] [--enable-coverage-strategy]
                    [--custom-modules-directory CUSTOM_MODULES_DIRECTORY] [--attacker-address ATTACKER_ADDRESS] [--creator-address CREATOR_ADDRESS]
                    [solidity_files [solidity_files ...]]

positional arguments:
  solidity_files        Inputs file name and contract name. 
                        usage: file1.sol:OptionalContractName file2.sol file3.sol:OptionalContractName

optional arguments:
  -h, --help            show this help message and exit
  --rpc HOST:PORT / ganache / infura-[network_name]
                        custom RPC settings
  --rpctls RPCTLS       RPC connection over TLS
  --infura-id INFURA_ID
                        set infura id for onchain analysis
  --solc-json SOLC_JSON
                        Json for the optional 'settings' parameter of solc's standard-json input
  --solv SOLV           specify solidity compiler version. If not present, will try to install it (Experimental)
                        hex-encoded bytecode string ("6060604052...")
                        file containing hex-encoded bytecode string
                        pull contract from the blockchain
  --bin-runtime         Only when -c or -f is used. Consider the input bytecode as binary runtime code, default being the contract creation bytecode.
  -o <text/markdown/json/jsonv2>, --outform <text/markdown/json/jsonv2>
                        report output format

  -g GRAPH, --graph GRAPH
                        generate a control flow graph
  -j OUTPUT_FILE, --statespace-json OUTPUT_FILE
                        dumps the statespace json

  -m MODULES, --modules MODULES
                        Comma-separated list of security analysis modules
  --max-depth MAX_DEPTH
                        Maximum recursion depth for symbolic execution
  --call-depth-limit CALL_DEPTH_LIMIT
                        Maximum call depth limit for symbolic execution
  --strategy {dfs,bfs,naive-random,weighted-random}
                        Symbolic execution strategy
  --transaction-sequences TRANSACTION_SEQUENCES
                        The possible transaction sequences to be executed. Like [[func_hash1, func_hash2], [func_hash2, func_hash3]] where for the first transaction is constrained with func_hash1 and func_hash2, and the second tx is constrained with func_hash2 and func_hash3
  --beam-search BEAM_SEARCH
                        Beam search with with
  -b N, --loop-bound N  Bound loops at n iterations
                        Maximum number of transactions issued by laser
  --execution-timeout EXECUTION_TIMEOUT
                        The amount of seconds to spend on symbolic execution
  --solver-timeout SOLVER_TIMEOUT
                        The maximum amount of time(in milli seconds) the solver spends for queries from analysis modules
  --create-timeout CREATE_TIMEOUT
                        The amount of seconds to spend on the initial contract creation
  --parallel-solving    Enable solving z3 queries in parallel
  --solver-log SOLVER_LOG
                        Path to the directory for solver log
  --no-onchain-data     Don't attempt to retrieve contract code, variables and balances from the blockchain
  --sparse-pruning      Checks for reachability after the end of tx. Recommended for short execution timeouts < 1 min
                        Default storage value is symbolic, turns off the on-chain storage loading
  --phrack              Phrack-style call graph
  --enable-physics      enable graph physics simulation
  -q, --query-signature
                        Lookup function signatures through www.4byte.directory
  --enable-iprof        enable the instruction profiler
                        Deactivate dependency-based pruning
                        enable coverage based search strategy
  --custom-modules-directory CUSTOM_MODULES_DIRECTORY
                        designates a separate directory to search for custom analysis modules
  --attacker-address ATTACKER_ADDRESS
                        Designates a specific attacker address to use during analysis
  --creator-address CREATOR_ADDRESS
                        Designates a specific creator address to use during analysis





uPort Identity Contracts

BitGo Ethereum MultiSig Wallet Contract


  • https://infura.io/
  • Desc. : Our suite of high availability APIs and Developer Tools provide quick, reliable access to the Ethereum and IPFS networks so you can focus on building and scaling next generation software.

Infura Ethereum

Network Protocol Endpoint Remarks
Mainnet HTTPS https://mainnet.infura.io/v3/YOUR-PROJECT-ID
WebSocket wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID

Infura IPFS


  • https://www.kaleido.io/
  • Offers the full stack of services needed for the next generation of Enterprise Decentralized applications
  • Quick Start Ethereum
    1. Create an Account and Login
    2. Create a Business Network (parental resource for blockchain environments and the various runtimes within)
    3. Create Environment (an isolated domain with nodes, services, and security credentials confined solely to it)
    4. Add a Node to your Ethereum Environment
    5. Create a App Cred
                              1    n              1    n
Organization -----> Consortia -----> Environment ---+--> Node
                                                    +--> App Cred



Binance Smart Chain


Network Description Block Explorer Wallet Faucet
Cypress Mainnet https://scope.klaytn.com/ https://wallet.klaytn.com/
Baobab Testnet https://baobab.scope.klaytn.com/ https://baobab.wallet.klaytn.com/ https://baobab.wallet.klaytn.com/faucet