Consensus Algorithm

Style Description Remarks
PoW Deters denial of service attacks and other service abuses such as spam on a network by requiring some work from the service requester, usually meaning processing time by a computer.


BFT (Byzantine Fault Tolerance)




  • Paxos : a family of protocols for solving consensus in a network of unreliable processors
Fault Type Cryptography Replica Requirement
Non Byzantine Failures Non Cryptographic 2F + 1
Non-malicious Byzantine Failures Non Cryptographic 2F + 1
Malicious Byzantine Failures Non Cryptographic 3F + 1
Malicious Byzantine Failures Cryptographic 2F + 1

Blockchian Networks

Network Symbol Consensus Style Description Remarks
BitCoin BTC PoW
Ethereum ETH PoW

Smart Contract

Key and Wallet

  • Shamir's Secret Sharing
    • a form of secret sharing, where a secret is divided into parts, giving each participant its own unique part.

Financial Business

Concept Description Remark
Leverage any technique involving the use of debt (borrowed funds) rather than fresh equity in the purchase of an asset, with the expectation that the after-tax profit to equity holders from the transaction will exceed the borrowing cost, frequently by several multiples⁠.
Margin collateral that the holder of a financial instrument has to deposit with a counterparty (most often their broker or an exchange) to cover some or all of the credit risk the holder poses for the counterparty.
Fungibility the property of a good or a commodity whose individual units are essentially interchangeable, and each of its parts is indistinguishable from another part. company shares, bonds, precious metals, currencies
Entry Meaning Position Korean
Debit a transfer of value to that account right side 차변
Credit a transfer of value from the account left side 대변
  • What Is Margin Trading? (13.01.2020)
    • This ability to expand trading results makes margin trading especially popular in low-volatility markets, particularly the international Forex market. Still, margin trading is also used in stock, commodity, and cryptocurrency markets.
  • Margin (Jun 25, 2019)

Financial Instrument

  • Financial instrument
    • monetary contracts between parties which can be created, traded, modified and settled.
Instrument Description Remark
Bond an instrument of indebtedness of the bond issuer to the holders. debt security
Loan the lending of money by one or more individuals, organizations, or other entities to other individuals, organizations etc.
Deposit any other type of bank account that allows money to be deposited and withdrawn by the account holder.

Credit Card





BIP Title Description Type Status Remarks Related
BIP 32 Hierarchical Deterministic Wallets describes hierarchical deterministic wallets (or "HD Wallets") Informational Final
BIP 39 Mnemonic code for generating deterministic keys describes the implementation of a mnemonic code or mnemonic sentence -- a group of easy to remember words -- for the generation of deterministic wallets. Standards Track Proposed
BIP 43 Purpose Field for Deterministic Wallets introduces a "Purpose Field" for use in deterministic wallets based on algorithm described in BIP-0032 Informational Draft m/purpose'/* BIP 32
BIP 44 Multi-Account Hierarchy for Deterministic Wallets defines a logical hierarchy for deterministic wallets based on an algorithm described in BIP-0032 Standards Track Proposed m/44'/*'/*'/*/* BIP 32, BIP 43

HD Wallet

Format Purpose Description Remarks
m/0'/* Default Account
m/44'/coin_type'/*'/*/* Multi-Account m/44'/0': BTC, m/44'/60': ETH, m/44'/61': ETC

BIP 32

private parent key → private child key : possible
public parent key → public child key : possible
private parent key → public child key : possible
public parent key → private child key : impossible
  • Each leaf node in the tree corresponds to an actual key, while the internal nodes correspond to the collections of keys that descend from them.
  • The chain codes of the leaf nodes are ignored, and only their embedded private or public key is relevant.
  • Knowing an extended private key allows reconstruction of all descendant private keys and public keys.
  • Knowing an extended public keys allows reconstruction of all descendant non-hardened public keys.
256 bit entropy
private key
public key
extended private key
extended public key
private child key derivation(CKD) function
public child key derivation(CKD) function
computes extended public key
private key node m : master extended private key
public key node M : master extended public key
Serialization Format
Position Value Remarks
4 bytes version bytes
  • mainnet/public: 0x0488B21E
  • mainnet/private: 0x0488ADE4
  • testnet/public: 0x043587CF
  • testnet/private: 0x04358394
1 bytes depth
  • master node: 0x00
  • level-1 derived: 0x01
4 bytes the fingerprint of the parent's key master key: 0x00000000
4 bytes child number
32 bytes chain code 256 bit
33 bytes the public key or private key data




  • 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, ...
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 165 Standard Interface Detection Creates a standard method to publish and detect what interfaces a smart contract implements. ERC Final ERC-1820
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
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 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 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


  • ERC : Application-level standards and conventions
ERC Title Description Remarks
ERC 734 Key Manager A contract for key management of a blockchain proxy account. ERC 725
ERC 735 Claim Holder Describes standard functions for adding, removing and holding of claims. ERC 725, ERC 734
ERC 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 735
ERC 1155 Multi Token Standard A standard interface for contracts that manage multiple token types.
ERC 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 1400 Security Token Standard Represents a library of standards for security tokens on Ethereum. EIPs/issues/1411
ERC 1404 Simple Restricted Token Standard An open source standard for security tokens
                            +--- Transferrable ---------- EIP 20
       +--- Fungible -------+
       |                    |
       |                    +--- Non Transferrable ----- 
       |                    +--- Transferable ---------- EIP 721
       |                    |
       +--- Non Fungible ---+
                            +--- Non Transferrable ----- ERC 1238, ERC 735
  • 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.


  • 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 Gas?
  • 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 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
Public Key 512 64 128
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

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 signature

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

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

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


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.

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.


  • JavaScript code snippet to calculate target in hexa with given difficulty
    • > (2n**256n / 24091770185844n).toString(16).padStart(64, '0') // difficulty: 24091770185844


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

Hard Forks

Fork Date Block # Description Remarks
Olympic 2015-05-09 N/A The final PoC testnet
Frontier 2015-06-30 0 The 1st official public mainnet Block Reward, Gas
Homestead 2016-03-14 1,150,000 The 1st planned hard fork Solidity, Mist wallet
DAO Fork 2016-06-20 1,192,000 To restore $50M stolen in DAO hack Ethereum Classic
Spurious Dragon 2016-11-22 2,675,000 EIP 155, EIP 160, EIP 161, EIP 170
Metropolis: Byzantium 2017-10-16 4,370,000 Add REVERT and STATICCALL opcode
Metropolis: Constantinople 2019-02-28 7,280,000 Smart Contract Verification
State Channel
Block Reward Reduction(3ETH -> 2ETH)
Istanbul 2019-12-07 9,069,000 Zcash interoperability enhancement
SNARK and STARK performance enhancement
EIP 1344, EIP 152, EIP 1108, EIP 2028, EIP 2200
Muir Glacier 2020-01-02 9,200,000 Delays the “difficulty bomb” by 4M blocks.

Ethereum 2.0




Method Description Remarks
eth_getTransactionByHash Returns the information about a transaction requested by transaction hash.
eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash.
eth_sendTransaction Creates new message call transaction or a contract creation, if the data field contains code. transaction object
eth_call Executes a new message call immediately without creating a transaction on the block chain. transaction object
Object Description Properties Remarks
transaction from, to, gas, gasPrice, value, data, nonce
transaction receipt
  • Looking around the local client using JSON RPC API
$ # Get the client coinbase address. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_coinbase","params":[],"id":11}'

$ # Get the client version. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":21}'

$ # Get the Ethereum protocol version. (
$ # For more on Ethereum protocol version, refer
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_protocolVersion","params":[],"id":31}'

$ # Get the number of peers currently connected to the client. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_peerCount","params":[],"id":41}'

$ # Check whether the client is mining or not. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_mining","params":[],"id":51}'

$ # Get a list of addresses owned by client (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":61}'

$ # Get the network ID. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"net_version","params":[],"id":71}'

$ # Get the current price per gas in wei. (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_gasPrice","params":[],"id":81}'

$ # Get the number of most recent block. (
$ 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. (
$ 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) (
$ 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 (
$ curl -sSX POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionByHash","params":["0x10f612a42b04ace427b0057caf76d7c7446840f419d4b424f117ecb1bd2cb0e8"],"id":211}'

Smart Contract

ERC Reference Description Remarks
ERC-725 ERC 725 Alliance Reference Implementation
uPort Identity Contracts




Test Network, Private Network

Network ID Consensus Avg. Block Time Faucet Explorer GitHub Remark
Ropsten 3 PoW 30 sec.
Rinkeby 4 PoA 15 sec.
Kovan 42 PoA 4 sec.
Görli 5 PoA 15 sec.





Ethereum Network Statistics

Topic Charts and Tables Remarks
Time 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

Ethereum 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




  • 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.


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.
  • 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.


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() not for string
pop() not for string
  • 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)
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.

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 current block miner’s address
block.number current block number
block.timestamp current block timestamp as seconds since unix epoch
msg.sender sender of the message
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.
Contract this the current contract address(this)


  • 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.


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)






Ether Transfer








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


Best Practices

Category Title Description Remarks
ERC-1400 Security Token Standard Contracts
ERC-1400 ConsenSys Codefi Universal Token a hybrid token standard precisely designed for the use case of tokenized financial assets
DeFi MakerDao Multi Collateral Dai Contracts
Wallet Authereum Contracts
Oracle Chainlink's Solidity Contracts



Ethereum Clients

Go Ethereum




Parity Ethereum




Hyperledger Besu





Ethereum Libraries and Tools

  • Wallets
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



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.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. 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.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
Number length
Transform an ASCII string into a valid bytes4, bytes8 etc Alias: fromAscii
web3.eth.abi.encodeFunctionCall Object jsonInterfacer
Array parameters
Encodes a function call using its JSON interface object and given parameters.
  // 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

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.getCoinbase()
truffle(ropsten)> web3.eth.getCoinbase().then(web3.eth.getBalance).then(v => parseInt(v).toLocaleString())
truffle(ropsten)> web3.eth.getNodeInfo()
truffle(ropsten)> web3.eth.getProtocolVersion()
truffle(ropsten)> web3.eth.isMining()
truffle(ropsten)> web3.eth.getAccounts()
[ ... ]
truffle(ropsten)> web3.eth.getAccounts().then(accts => accts.forEach(acct => web3.eth.getBalance(acct.toString()).then(console.log)))
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.getBlockNumber().then(v => v.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: [] }



  • 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 HTTP implementation of our services API
org.web3j.protocol.Service Base service implementation
public class JsonRpc2_0Web3j implements Web3j JSON-RPC 2.0 factory implementation
interface org.web3j.protocol.Web3j extends Ethereum, Web3jRx
interface org.web3j.protocol.core.Ethereum JSON-RPC methods
interface org.web3j.protocol.rx.Web3jRx
interface org.web3j.quorum.Quorum extends Web3j
abstract org.web3j.abi.TypeReference<T extends org.web3j.abi.datatypes.Type>
  • 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
Keys 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
RawTransaction static createTransaction createTransaction(...) create raw transaction object that is not signed transaction object
TransactionEncoder static byte[] signMessage(RawTransaction rawTx, Credentials cred) sign a raw transaction
Numeric 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");


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

Basic Usage

Using Brownie and 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
Roles Roles.sol
ERC 20 ERC20 Sources the most widespread token standard for fungible assets
ERC 721 ERC721 Sources the de-facto solution for non-fungible tokens
ERC 777 ERC 777 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.



Remix IDE

  • Desc. : a browser-based compiler and IDE that enables users to build Ethereum contracts with Solidity language and to debug transactions
  • License : MIT License




Command Description Options Remarks
init Initialize new and empty Ethereum project --force
compile Compile contract source files. --list, --all, --network, --quiet
migrate Run migrations to deploy contracts. --reset, --f, --to, --dry-run
test Runs some or all tests within the test/ directory as specified. --show-events


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


  • 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
 * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
 * public/private key pairs. If you're publishing your code to GitHub make sure you load this
 * phrase from a file you've .gitignored so it doesn't accidentally become public.

const HDWalletProvider = require('@truffle/hdwallet-provider');
// const infuraKey = "fj4jll3k.....";
// const fs = require('fs');
// const mnemonic = fs.readFileSync(".secret").toString().trim();

module.exports = {

  networks: {
    development: {
      host: '',
      port: 8545,
      network_id: '31',
      gas: 4E8,
      gasPrice: 2.5E10,
      websockets: true

    //GitHub :
    //Explorer :
    //Faucet :
    ropsten: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC,"" + process.env.INFURA_PROJECT_ID),
      network_id: '3',
      gas: 7E6,
      gasPrice: 1E10

    //Explorer :
    //Faucet :
    rinkeby: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC, "" + process.env.INFURA_PROJECT_ID),
      network_id: '4',

    //GitHub :
    //Explorer :
    //Faucet :
    kovan: {
      provider: () => new HDWalletProvider(process.env.BIP39_MNEMONIC, "" + process.env.INFURA_PROJECT_ID),
      network_id: '42', //
      gas: 7E6,
      gasPrice: 5E10

  mocha: {
    useColors: true,
    enableTimeouts: true,
    timeout: 180000

  compilers: {
    solc: {
      version: "^0.5.0",
      // version: "^0.6.0",
      settings: {
        optimizer: {
          enabled: false,
          runs: 200
        evmVersion: "petersburg"
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 :
//Truffle Contract Guide :
//Truffle Contract Package :
//Mocha Documentation :
//Chai Assert API :
//Chai Expect/Should API :
//OpenZeppelin Test Helpers API :
//web3 API :
//chance.js :
//bn.js :
//JavaScript Reference (MDN) :
//The Modern JavaScript Tutorial :

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









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 ''."
  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 | grep -E "^ethereum\.netVersion=" | sed -E 's/ethereum\.netVersion=//'`
readonly eth_host=`cat | grep -E "^ethereum\.host=" | sed -E 's/ethereum\.host=//'`
readonly eth_port=`cat | grep -E "^ethereum\.port=" | sed -E 's/ethereum\.port=//'`
readonly eth_gas_price=`cat | grep -E "^ethereum\.gasPrice=" | sed -E 's/ethereum\.gasPrice=//'`
readonly eth_gas_limit=`cat | grep -E "^ethereum\.gasLimit=" | sed -E 's/ethereum\.gasLimit=//'`
readonly eth_keys=`cat | 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 :
# BIP 32 :
# BIP 39 :
# 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'."


  • 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 :




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


Ethereum plugin for Vault









  • Desc. : detects security vulnerabilities in smart contracts built for Ethereum, Hedera, Quorum, Vechain, Roostock, Tron and other EVM-compatible blockchains.
  • License : MIT





uPort Identity Contracts




rippled API

Category API Methods Description Remarks
Public subscribe WebSocket requests periodic notifications from the server when certain events happen Ledger Stream, Validations Stream, Transaction Streams, Peer Status Stream, Order Book Streams
Admin ledger_request WebSocket, Commandline tells server to fetch a specific ledger version from its connected peers


   Round Start --------------- Close -------------------- Consensus -------------------- Round End
                 Open phase            Establish phase                  Accept phase
  • The XRP Ledger Consensus Process
  • Consensus
    • Concensus
      • Through the consensus process, validating nodes agree on a specific subset of the candidate transactions to be considered for the next ledger
      • Consensus is an iterative process in which nodes relay proposals, or sets of candidate transactions.
      • Nodes communicate and update proposals until a supermajority 5 of peers agree on the same set of candidate transactions.
    • Validation
      • The validating nodes calculate a new version of the ledger and relay their results to the network, each sending a signed hash of the ledger it calculated based on the candidate transactions proposed during consensus.
      • In cases where a node is in the minority, having computed a ledger that differs from its peers, the node disregards the ledger it computed 9. It recomputes the correct ledger, or retrieves the correct ledger as needed.
  • rippled Server States
                                                            +--> full
   disconnected ---> connected ---> syncing ---> tracking --| 
                                                            +--> validating <-----> proposing


  • Reliable Transaction Submission
    • Best Practices
    • Your rippled server should automatically acquire the missing ledger versions when it has spare resources (CPU/RAM/disk IO) to do so, unless the ledgers are older than its configured amount of history to store. Depending on the size of the gap and the resource usage of your server, acquiring missing ledgers should take a few minutes. You can also manually request your server to acquire historical ledger versions using the ledger_request method.
    • Use the LastLedgerSequence parameter to prevent undesirable cases where a transaction is not confirmed promptly but could be included in a future ledger. You should specify the LastLedgerSequence parameter on every transaction. Automated processes should use a value of 4 greater than the last validated ledger index to make sure that a transaction is validated or rejected in a predictable and prompt way.


  • Ledgers
    • Ledger = Header + Transaction Tree + State Tree (Ledger Objects)
    • At any given time, a rippled instance has an in-progress "current" open ledger, plus some number of closed ledgers that have not yet been approved by consensus, and any number of historical ledgers that have been validated by consensus.
    • Only the validated ledgers are certain to be correct and immutable.
  • Ledger Header
    • Two ledgers with the same hash are always the same.
    • For validated ledgers, hash values and sequence numbers are equally valid and correlate 1:1.
    • Two different rippled servers may have different contents for a current ledger with the same ledger index, due to latency in propagating transactions throughout the network.
    • There may be multiple closed ledger versions competing to be validated by consensus. These ledger versions have the same sequence number but different contents (and different hashes). Only one of these closed ledgers can become validated.
    • A current ledger's contents change over time, which would cause its hash to change, even though its ledger index number stays the same. The hash of a ledger is not calculated until the ledger is closed.





Component Type Description Remarks
SHAMapStoreImp.h, SHAMapStoreImp.cpp class
Setup struct deleteInterval, advisoryDelete, ledgerHistory, databasePath, deleteBatch, backOff, ageThreshold
Config.h class



Hyperledger Fabric


  • Concepts
    • Channels
      • Channel = Organizations + Ordering Service + Anchor Peers + Chaincodes + Ledger
      • At least one anchor peer per organization




  • fabric/core/ledger/ledgerconfig/ledger_config.go


Docker Images


Config which is printed by "docker inspect --format='{{json .Config}}' ..." is

 "Config": {
   "Hostname": "e7eddde82bec",
   "Domainname": "",
   "User": "",
   "AttachStdin": false,
   "AttachStdout": false,
   "AttachStderr": false,
   "Tty": false,
   "OpenStdin": false,
   "StdinOnce": false,
   "Env": [
   "Cmd": [
   "ArgsEscaped": true,
   "Image": "sha256:793719e9dd193f580f32c5984ac47a8c0f986819e4795c039703b26bb6ad15ce",
   "Volumes": null,
   "WorkingDir": "",
   "Entrypoint": null,
   "OnBuild": [],
   "Labels": {
     "org.hyperledger.fabric.base.version": "0.3.0",
     "org.hyperledger.fabric.version": "1.0.0-alpha"

Fabric CA

Fabric SDK for Node.js

Performance Tuning

  • LVM (Logical Volume Manager)



R3 Corda


Concept Description Remarks
State Object a digital document which records the existence, content and current state of an agreement between two or more parties
Ledger a set of immutable state objects
Consensus pure function whose responsibility is either to accept or reject a proposed transaction and which can be composed from simpler, reusable functions
Transaction Consume existing state objects and produce new state objects Transaction Validity, Transaction Uniqueness
Smart Contract
Uniqueness and Timestamping Services
Flow Framework
          State Object ----+----> Contract Code
                           +----> Legal Prose



  • End-State Principles
Principle Description Remarks
Inclusion Parties are able to discover each other freely, and transact directly, in a single, open network
Assured identity Parties will have assurance over the identity of participants in the network
Privacy The only parties who have access to the details of a transaction are those who participate in the transaction and those who need to assure themselves of transaction provenance.
Shared logic The behavior of agreements managed by the system will be described in computer code that is shared to ensure onsistency and validity of agreements
Legal footing Deals recorded by the ledger are, by contract, accepted as admissible evidence and legally binding by all parties in any dispute
Authoritative Facts recorded by the ledger are regarded as authoritative rather than “shadows” of authoritative data held elsewhere
Immutability Facts recorded on the ledger are final and immutable; errors and unwinds must be processed through a subsequent transaction
Open The system is open: open source, participation, development, governance and standards to ensure the platform balances the needs of its diverse user-base in a transparent fashion





Tendermint Core



  • Desc. : A peer-to-peer hypermedia protocol to make the web faster, safer, and more open





  • Desc. : an advanced institutional technology platform for issuing and exchanging tokenized financial assets, powered by the Ethereum blockchain.


  • DeFi Pulse : a site where you can find the latest analytics and rankings of DeFi protocols.



  • DAI
    • Decentralized Stable Coin
    • Backed by Ether



Community content is available under CC-BY-SA unless otherwise noted.