Ethereum and Ethereum Classic
While the initial split was centered around The DAO, the two networks, Ethereum and Ethereum Classic, are now separate projects, although most development is still done by the Ethereum community and simply ported to Ethereum Classic codebases. Nevertheless, the full set of differences is constantly evolving and too extensive to cover in this appendix. However, it is worth noting that the chains do differ significantly in their core development and community structure. A few of the technical differences are discussed next.
The EVM
For the most part (at the time of writing), the two networks remain highly compatible: contract code produced for one chain runs as expected on the other; but there are some small differences in EVM OPCODES (see EIPs 140, 145, and 214).
Core Network Development
Being open projects, blockchain platforms often have many users and contributors. However, the core network development (i.e., of the code that runs the network) is often done by small groups due to the expertise and knowledge required to develop this type of software. On Ethereum, this work is done by the Ethereum Foundation and volunteers. On Ethereum Classic, it's done by ETCDEV, IOHK, and volunteers.
Other Notable Ethereum Forks
Ellaism is an Ethereum-based network that intends to use PoW exclusively to secure the blockchain. It has no pre-mine and no mandatory developer fees, with all support and development donated freely by the community. Its developers believe this makes theirs “one of the most honest pure Ethereum projects,” and one that is “uniquely interesting as a platform for serious developers, educators, and enthusiasts. Ellaism is a pure smart contract platform. Its goal is to create a smart contract platform that is both fair and trustworthy.” The principles of the platform are as follows:
- All changes and upgrades to the protocol should strive to maintain and reinforce these Principles of Ellaism.
- Monetary Policy: 280 million coins.
- No Censorship: Nobody should be able to prevent valid txs from being confirmed.
- Open-Source: Ellaism source code should always be open for anyone to read, modify, copy, share.
- Permissionless: No arbitrary gatekeepers should ever prevent anybody from being part of the network (user, node, miner, etc).
- Pseudonymous: No ID should be required to own, use Ellaism.
- Fungible: All coins are equal and should be equally spendable.
- Irreversible Transactions: Confirmed blocks should be set in stone. Blockchain History should be immutable.
- No Contentious Hard Forks: Never hard fork without consensus from the whole community. Only break the existing consensus when necessary.
- Many feature upgrades can be carried out without a hard fork, such as improving the performance of the EVM.
Several other forks have occurred on Ethereum as well. Some of these are hard forks, in the sense that they split directly off of the preexisting Ethereum network. Others are software forks: they use Ethereum's client/node software but run entirely separate networks without any history shared with Ethereum. There will likely be more forks over the life of Ethereum.
There are also several other projects that claim to be Ethereum forks but are actually based on ERC20 tokens and run on the Ethereum network. Two examples of these are EtherBTC (ETHB) and Ethereum Modification (EMOD). These are not forks in the traditional sense, and may sometimes be called “airdrops.”
Here's a brief rundown of some of the more notable forks that have occurred:
- Expanse was the first fork of the Ethereum blockchain to gain traction. It was announced via the Bitcoin Talk forum on September 7, 2015. The actual fork occurred a week later on September 14, 2015, at a block height of 800,000. It was originally founded by Christopher Franko and James Clayton. Their stated vision was to create an advanced chain for: "identity, governance, charity, commerce, and equity".
- EthereumFog (ETF) was launched on December 14, 2017, and forked at a block height of 4,730,660. The project's stated aim is to develop "world decentralized fog computing" by focusing on fog computing and decentralized storage. There is still little information on what this will actually entail.
- EtherZero (ETZ) was launched on January 19, 2018, at a block height of 4,936,270. Its notable innovations were the introduction of a masternode architecture and the removal of transaction fees for smart contracts to enable a wider diversity of DApps. There has been some criticism from some prominent members of the Ethereum community, MyEtherWallet, and MetaMask, due to the lack of clarity surrounding development and some accusations of possible phishing.
- EtherInc (ETI) was launched on February 13, 2018, at a block height of 5,078,585, with a focus on building decentralized organizations. Stated goals include the reduction of block times, increased miner rewards, the removal of uncle rewards, and setting a cap on mineable coins. EtherInc uses the same private keys as Ethereum and has implemented replay protection to protect ether on the original non-forked chain.
Ethereum Standards
Ethereum Improvement Proposals (EIPs)
The Ethereum Improvement Proposal repository is located at https://github.com/ethereum/EIPs/. The workflow is illustrated in Ethereum Improvement Proposal workflow.
From EIP-1:
EIP stands for Ethereum Improvement Proposal. An EIP is a design document providing information to the Ethereum community, or describing a new feature for Ethereum or its processes or environment. The EIP should provide a concise technical specification of the feature and a rationale for the feature. The EIP author is responsible for building consensus within the community and documenting dissenting opinions.
Table of Most Important EIPs and ERCs
Important EIPs and ERCs
- EIP/ERC # — Title/Description — Author — Layer — Status — Created — EIP-1 — EIP Purpose and Guidelines — Martin Becze, Hudson Jameson — Meta — Final — EIP-2 — Homestead Hard-fork Changes — Vitalik Buterin — Core — Final
- EIP-5 — Gas Usage for RETURN and CALL* — Christian Reitwiessner — Core — Draft — EIP-6 — Renaming SUICIDE Opcode — Hudson Jameson — Interface — Final — EIP-7 — DELEGATECALL — Vitalik Buterin — Core — Final — EIP-8 — devp2p Forward Compatibility Requirements for Homestead — Felix Lange — Networking — Final — EIP-20 — ERC-20 Token Standard. Describes standard functions a token contract may implement to allow DApps and wallets to handle tokens across multiple interfaces/DApps. Methods include: totalSupply, balanceOf(address), transfer, transferFrom, approve, allowance. Events include: Transfer (triggered when tokens are transferred), Approval (triggered when approve is called). — Fabian Vogelsteller, Vitalik Buterin — ERC — Final — Frontier — EIP-55 — Mixed-case checksum address encoding — Vitalik Buterin — ERC — Final — EIP-86 — Abstraction of transaction origin and signature. Sets the stage for "abstracting out" account security and allowing users to create "account contracts," moving toward a model where in the long term all accounts are contracts that can pay for gas, and users are free to define their own security models that perform any desired signature verification and nonce checks (instead of using the in-protocol mechanism where ECDSA and the default nonce scheme are the only "standard" way to secure an account, which is currently hardcoded into transaction processing). — Vitalik Buterin — Core — Deferred (to be replaced) — Constantinople — EIP-96 — Blockhash and state root changes. Stores blockhashes in the state to reduce protocol complexity and need for complex client implementations to process the BLOCKHASH opcode. Extends range of how far back blockhash checking may go, with the side effect of creating direct links between blocks with very distant block numbers to facilitate much more efficient initial light client syncing. — Vitalik Buterin — Core — Deferred — Constantinople — EIP-100 — Change difficulty adjustment to target mean block time and including uncles. — Vitalik Buterin — Core — Final — Metropolis Byzantinium — EIP-101 — Serenity Currency and Crypto Abstraction. Abstracts ether up a level with the benefit of allowing ether and subtokens to be treated similarly by contracts, reduces the level of indirection required for custom-policy accounts such as multisigs, and purifies the underlying Ethereum protocol by reducing the minimal consensus implementation complexity. — Vitalik Buterin — Active — Serenity feature — Serenity Casper — EIP-105 — Binary sharding plus contract calling semantics. "Sharding scaffolding" EIP to allow Ethereum transactions to be parallelized using a binary tree sharding mechanism, and to set the stage for a later sharding scheme. Research in progress; see https://github.com/ethereum/sharding. — Vitalik Buterin — Active — Serenity feature — Serenity Casper — EIP-137 — Ethereum Domain Name Service - Specification — Nick Johnson — ERC — Final — EIP-140 — New Opcode: REVERT. Adds REVERT opcode instruction, which stops execution and rolls back the EVM execution state changes without consuming all provided gas (instead the contract only has to pay for memory) or losing logs, and returns to the caller a pointer to the memory location with the error code or message. — Alex Beregszaszi, Nikolai Mushegian — Core — Final — Metropolis Byzantinium — EIP-141 — Designated invalid EVM instruction — Alex Beregszaszi — Core — Final — EIP-145 — Bitwise shifting instructions in EVM — Alex Beregszaszi, Paweł Bylica — Core — Deferred — EIP-150 — Gas cost changes for IO-heavy operations — Vitalik Buterin — Core — Final — EIP-155 — Simple replay attack protection. Replay Attack allows any transaction using a pre-EIP-155 Ethereum node or client to become signed so it is valid and executed on both the Ethereum and Ethereum Classic chains. — Vitalik Buterin — Core — Final — Homestead — EIP-158 — State clearing — Vitalik Buterin — Core — Superseded — EIP-160 — EXP cost increase — Vitalik Buterin — Core — Final — EIP-161 — State trie clearing (invariant-preserving alternative) — Gavin Wood — Core — Final — EIP-162 — Initial ENS Hash Registrar — Maurelian, Nick Johnson, Alex Van de Sande — ERC — Final
- EIP-165 — ERC-165 Standard Interface Detection — Christian Reitwiessner et al. — Interface — Draft — EIP-170 — Contract code size limit — Vitalik Buterin — Core — Final — EIP-181 — ENS support for reverse resolution of Ethereum addresses — Nick Johnson — ERC — Final — EIP-190 — Ethereum Smart Contract Packaging Standard — Piper Merriam et al. — ERC — Final — EIP-196 — Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128. Required in order to perform zkSNARK verification within the block gas limit. — Christian Reitwiessner — Core — Final — Metropolis Byzantinium — EIP-197 — Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128. Combined with EIP-196. — Vitalik Buterin, Christian Reitwiessner — Core — Final — Metropolis Byzantinium — EIP-198 — Big integer modular exponentiation. Precompile enabling RSA signature verification and other cryptographic applications. — Vitalik Buterin — Core — Final — Metropolis Byzantinium — EIP-211 — New opcodes: RETURNDATASIZE and RETURNDATACOPY. Adds support for returning variable-length values inside the EVM with simple gas charging and minimal change to calling opcodes using new opcodes RETURNDATASIZE and RETURNDATACOPY. Handles similar to existing calldata, whereby after a call, return data is kept inside a virtual buffer from which the caller can copy it (or parts thereof) into memory, and upon the next call, the buffer is overwritten. — Christian Reitwiessner — Core — Final — Metropolis Byzantinium — EIP-214 — New opcode: STATICCALL. Permits non-state-changing calls to itself or other contracts while disallowing any modifications to state during the call (and its subcalls, if present) to increase smart contract security and assure developers that re-entrancy bugs cannot arise from the call. Calls the child with STATIC flag set to true for execution of child, causing exception to be thrown upon any attempts to make state-changing operations inside an execution instance where STATIC is true, and resets flag once call returns. — Vitalik Buterin, Christian Reitwiessner — Core — Final — Metropolis Byzantinium — EIP-225 — Rinkeby testnet using proof of authority where blocks are only mined by trusted signers. — Péter Szilágyi — Homestead — EIP-234 — Add blockHash to JSON-RPC filter options — Micah Zoltu — Interface — Draft
- EIP-615 — Subroutines and Static Jumps for the EVM — Greg Colvin, Paweł Bylica, Christian Reitwiessner — Core — Draft
- EIP-616 — SIMD Operations for the EVM — Greg Colvin — Core — Draft
- EIP-681 — URL Format for Transaction Requests — Daniel A. Nagy — Interface — Draft
- EIP-649 — Metropolis Difficulty Bomb Delay and Block Reward Reduction. Delayed the Ice Age (aka Difficulty Bomb) by 1 year, and reduced the block reward from 5 to 3 ether. — Afri Schoedon, Vitalik Buterin — Core — Final — Metropolis Byzantinium — EIP-658 — Embedding transaction status code in receipts. Fetches and embeds a status field indicative of success or failure state to transaction receipts for callers, as it's no longer possible to assume the transaction failed if and only if it consumed all gas after the introduction of the REVERT opcode in EIP-140. — Nick Johnson — Core — Final — Metropolis Byzantinium — EIP-706 — DEVp2p snappy compression — Péter Szilágyi — Networking — Final — EIP-721 — ERC-721 Non-Fungible Token Standard. A standard API that allows smart contracts to operate as unique tradable non-fungible tokens (NFTs) that may be tracked in standardized wallets and traded on exchanges as assets of value, similar to ERC20. CryptoKitties was the first popularly adopted implementation of a digital NFT in the Ethereum ecosystem. — William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs — Standard — Draft — EIP-758 — Subscriptions and filters for completed transactions — Jack Peterson — Interface — Draft — EIP-801 — ERC-801 Canary Standard — ligi — Interface — Draft — EIP-827 — ERC827 Token Standard. An extension of the standard interface ERC20 for tokens with methods that allow the execution of calls inside transfer and approvals. This standard provides basic functionality to transfer tokens, as well as allowing tokens to be approved so they can be spent by another on-chain third party. Also, it allows the developer to execute calls on transfers and approvals. — Augusto Lemble — ERC — Draft — EIP-930 — ERC930 Eternal Storage. The ES (Eternal Storage) contract is owned by an address that has write permissions. The storage is public, which means everyone has read permissions. It stores the data in mappings, using one mapping per type of variable. The use of this contract allows the developer to migrate the storage easily to another contract if needed. — Augusto Lemble — ERC — Draft
Ethereum EVM Opcodes and Gas Consumption
This appendix is based on the consolidation work done by the people of https://github.com/trailofbits/evm-opcodes as a reference for Ethereum VM (EVM) opcodes and instruction information licensed under the Apache License 2.0.
EVM opcodes and gas cost
- Opcode — Name — Description — Extra info — Gas — 0x00 — STOP — Halts execution — - — 0
- 0x01 — ADD — Addition operation — - — 3
- 0x02 — MUL — Multiplication operation — - — 5
- 0x03 — SUB — Subtraction operation — - — 3
- 0x04 — DIV — Integer division operation — - — 5
- 0x05 — SDIV — Signed integer division operation (truncated) — - — 5
- 0x06 — MOD — Modulo remainder operation — - — 5
- 0x07 — SMOD — Signed modulo remainder operation — - — 5
- 0x08 — ADDMOD — Modulo addition operation — - — 8
- 0x09 — MULMOD — Modulo multiplication operation — - — 8
- 0x0a — EXP — Exponential operation — - — 10***
- 0x0b — SIGNEXTEND — Extend length of two's complement signed integer — - — 5
- 0x0c - 0x0f — Unused — Unused — -
- 0x10 — LT — Less-than comparison — - — 3
- 0x11 — GT — Greater-than comparison — - — 3
- 0x12 — SLT — Signed less-than comparison — - — 3
- 0x13 — SGT — Signed greater-than comparison — - — 3
- 0x14 — EQ — Equality comparison — - — 3
- 0x15 — ISZERO — Simple NOT operator — - — 3
- 0x16 — AND — Bitwise AND operation — - — 3
- 0x17 — OR — Bitwise OR operation — - — 3
- 0x18 — XOR — Bitwise XOR operation — - — 3
- 0x19 — NOT — Bitwise NOT operation — - — 3
- 0x1a — BYTE — Retrieve single byte from word — - — 3
- 0x1b - 0x1f — Unused — Unused — -
- 0x20 — SHA3 — Compute Keccak-256 hash — - — 30
- 0x21 - 0x2f — Unused — Unused — -
- 0x30 — ADDRESS — Get address of currently executing account — - — 2
- 0x31 — BALANCE — Get balance of the given account — - — 400
- 0x32 — ORIGIN — Get execution origination address — - — 2
- 0x33 — CALLER — Get caller address — - — 2
- 0x34 — CALLVALUE — Get deposited value by the instruction/transaction responsible for this execution — - — 2
- 0x35 — CALLDATALOAD — Get input data of current environment — - — 3
- 0x36 — CALLDATASIZE — Get size of input data in current environment — - — 2
- 0x37 — CALLDATACOPY — Copy input data in current environment to memory — - — 3
- 0x38 — CODESIZE — Get size of code running in current environment — - — 2
- 0x39 — CODECOPY — Copy code running in current environment to memory — - — 3
- 0x3a — GASPRICE — Get price of gas in current environment — - — 2
- 0x3b — EXTCODESIZE — Get size of an account's code — - — 700
- 0x3c — EXTCODECOPY — Copy an account's code to memory — - — 700
- 0x3d — RETURNDATASIZE — Pushes the size of the return data buffer onto the stack — EIP-211 — 2
- 0x3e — RETURNDATACOPY — Copies data from the return data buffer to memory — EIP-211 — 3
- 0x3f — Unused — - — -
- 0x40 — BLOCKHASH — Get the hash of one of the 256 most recent complete blocks — - — 20
- 0x41 — COINBASE — Get the block's beneficiary address — - — 2
- 0x42 — TIMESTAMP — Get the block's timestamp — - — 2
- 0x43 — NUMBER — Get the block's number — - — 2
- 0x44 — DIFFICULTY — Get the block's difficulty — - — 2
- 0x45 — GASLIMIT — Get the block's gas limit — - — 2
- 0x46 - 0x4f — Unused — - — -
- 0x50 — POP — Remove word from stack — - — 2
- 0x51 — MLOAD — Load word from memory — - — 3
- 0x52 — MSTORE — Save word to memory — - — 3*
- 0x53 — MSTORE8 — Save byte to memory — - — 3
- 0x54 — SLOAD — Load word from storage — - — 200
- 0x55 — SSTORE — Save word to storage — - — 0*
- 0x56 — JUMP — Alter the program counter — - — 8
- 0x57 — JUMPI — Conditionally alter the program counter — - — 10
- 0x58 — GETPC — Get the value of the program counter prior to the increment — - — 2
- 0x59 — MSIZE — Get the size of active memory in bytes — - — 2
- 0x5a — GAS — Get the amount of available gas, including the corresponding reduction in the amount of available gas — - — 2
- 0x5b — JUMPDEST — Mark a valid destination for jumps — - — 1
- 0x5c - 0x5f — Unused — - — -
- 0x60 — PUSH1 — Place 1-byte item on stack — - — 3
- 0x61 — PUSH2 — Place 2-byte item on stack — - — 3
- 0x62 — PUSH3 — Place 3-byte item on stack — - — 3
- 0x63 — PUSH4 — Place 4-byte item on stack — - — 3
- 0x64 — PUSH5 — Place 5-byte item on stack — - — 3
- 0x65 — PUSH6 — Place 6-byte item on stack — - — 3
- 0x66 — PUSH7 — Place 7-byte item on stack — - — 3
- 0x67 — PUSH8 — Place 8-byte item on stack — - — 3
- 0x68 — PUSH9 — Place 9-byte item on stack — - — 3
- 0x69 — PUSH10 — Place 10-byte item on stack — - — 3
- 0x6a — PUSH11 — Place 11-byte item on stack — - — 3
- 0x6b — PUSH12 — Place 12-byte item on stack — - — 3
- 0x6c — PUSH13 — Place 13-byte item on stack — - — 3
- 0x6d — PUSH14 — Place 14-byte item on stack — - — 3
- 0x6e — PUSH15 — Place 15-byte item on stack — - — 3
- 0x6f — PUSH16 — Place 16-byte item on stack — - — 3
- 0x70 — PUSH17 — Place 17-byte item on stack — - — 3
- 0x71 — PUSH18 — Place 18-byte item on stack — - — 3
- 0x72 — PUSH19 — Place 19-byte item on stack — - — 3
- 0x73 — PUSH20 — Place 20-byte item on stack — - — 3
- 0x74 — PUSH21 — Place 21-byte item on stack — - — 3
- 0x75 — PUSH22 — Place 22-byte item on stack — - — 3
- 0x76 — PUSH23 — Place 23-byte item on stack — - — 3
- 0x77 — PUSH24 — Place 24-byte item on stack — - — 3
- 0x78 — PUSH25 — Place 25-byte item on stack — - — 3
- 0x79 — PUSH26 — Place 26-byte item on stack — - — 3
- 0x7a — PUSH27 — Place 27-byte item on stack — - — 3
- 0x7b — PUSH28 — Place 28-byte item on stack — - — 3
- 0x7c — PUSH29 — Place 29-byte item on stack — - — 3
- 0x7d — PUSH30 — Place 30-byte item on stack — - — 3
- 0x7e — PUSH31 — Place 31-byte item on stack — - — 3
- 0x7f — PUSH32 — Place 32-byte (full word) item on stack — - — 3
- 0x80 — DUP1 — Duplicate 1st stack item — - — 3
- 0x81 — DUP2 — Duplicate 2nd stack item — - — 3
- 0x82 — DUP3 — Duplicate 3rd stack item — - — 3
- 0x83 — DUP4 — Duplicate 4th stack item — - — 3
- 0x84 — DUP5 — Duplicate 5th stack item — - — 3
- 0x85 — DUP6 — Duplicate 6th stack item — - — 3
- 0x86 — DUP7 — Duplicate 7th stack item — - — 3
- 0x87 — DUP8 — Duplicate 8th stack item — - — 3
- 0x88 — DUP9 — Duplicate 9th stack item — - — 3
- 0x89 — DUP10 — Duplicate 10th stack item — - — 3
- 0x8a — DUP11 — Duplicate 11th stack item — - — 3
- 0x8b — DUP12 — Duplicate 12th stack item — - — 3
- 0x8c — DUP13 — Duplicate 13th stack item — - — 3
- 0x8d — DUP14 — Duplicate 14th stack item — - — 3
- 0x8e — DUP15 — Duplicate 15th stack item — - — 3
- 0x8f — DUP16 — Duplicate 16th stack item — - — 3
- 0x90 — SWAP1 — Exchange 1st and 2nd stack items — - — 3
- 0x91 — SWAP2 — Exchange 1st and 3rd stack items — - — 3
- 0x92 — SWAP3 — Exchange 1st and 4th stack items — - — 3
- 0x93 — SWAP4 — Exchange 1st and 5th stack items — - — 3
- 0x94 — SWAP5 — Exchange 1st and 6th stack items — - — 3
- 0x95 — SWAP6 — Exchange 1st and 7th stack items — - — 3
- 0x96 — SWAP7 — Exchange 1st and 8th stack items — - — 3
- 0x97 — SWAP8 — Exchange 1st and 9th stack items — - — 3
- 0x98 — SWAP9 — Exchange 1st and 10th stack items — - — 3
- 0x99 — SWAP10 — Exchange 1st and 11th stack items — - — 3
- 0x9a — SWAP11 — Exchange 1st and 12th stack items — - — 3
- 0x9b — SWAP12 — Exchange 1st and 13th stack items — - — 3
- 0x9c — SWAP13 — Exchange 1st and 14th stack items — - — 3
- 0x9d — SWAP14 — Exchange 1st and 15th stack items — - — 3
- 0x9e — SWAP15 — Exchange 1st and 16th stack items — - — 3
- 0x9f — SWAP16 — Exchange 1st and 17th stack items — - — 3
- 0xa0 — LOG0 — Append log record with no topics — - — 375
- 0xa1 — LOG1 — Append log record with one topic — - — 750
- 0xa2 — LOG2 — Append log record with two topics — - — 1125
- 0xa3 — LOG3 — Append log record with three topics — - — 1500
- 0xa4 — LOG4 — Append log record with four topics — - — 1875
- 0xa5 - 0xaf — Unused — - — -
- 0xb0 — JUMPTO — Tentative libevmasm has different numbers — EIP 615
- 0xb1 — JUMPIF — Tentative — EIP-615
- 0xb2 — JUMPSUB — Tentative — EIP-615
- 0xb4 — JUMPSUBV — Tentative — EIP-615
- 0xb5 — BEGINSUB — Tentative — EIP-615
- 0xb6 — BEGINDATA — Tentative — EIP-615
- 0xb8 — RETURNSUB — Tentative — EIP-615
- 0xb9 — PUTLOCAL — Tentative — EIP-615
- 0xba — GETLOCA — Tentative — EIP-615
- 0xbb - 0xe0 — Unused — - — -
- 0xe1 — SLOADBYTES — Only referenced in pyethereum — - — -
- 0xe2 — SSTOREBYTES — Only referenced in pyethereum — - — -
- 0xe3 — SSIZE — Only referenced in pyethereum — - — -
- 0xe4 - 0xef — Unused — - — -
- 0xf0 — CREATE — Create a new account with associated code — - — 32000
- 0xf1 — CALL — Message-call into an account — - — Complicated
- 0xf2 — CALLCODE — Message-call into this account with alternative account's code — - — Complicated
- 0xf3 — RETURN — Halt execution returning output data — - — 0
- 0xf4 — DELEGATECALL — Message-call into this account with an alternative account's code, but persisting into this account with an alternative account's code — - — Complicated
- 0xf5 — CALLBLACKBOX — - — - — 40
- 0xf6 - 0xf9 — Unused — - — -
- 0xfa — STATICCALL — Similar to CALL, but does not modify state — - — 40
- 0xfb — CREATE2 — Create a new account and set creation address to sha3(sender + sha3(init code)) % 2**160 — -
- 0xfc — TXEXECGAS — Not in yellow paper FIXME — - — -
- 0xfd — REVERT — Stop execution and revert state changes, without consuming all provided gas and providing a reason — - — 0
- 0xfe — INVALID — Designated invalid instruction — - — 0
- 0xff — SELFDESTRUCT — Halt execution and register account for later deletion — - — 5000*
Development Tools, Frameworks, and Libraries
Frameworks
Frameworks can be used to ease Ethereum smart contract development. By doing everything yourself you get a better understanding of how everything fits together, but it's a lot of tedious, repetitive work. The frameworks described in this section can automate certain tasks and make development easier.
Truffle
GitHub: https://github.com/trufflesuite/truffle
Website: https://trufflesuite.com
Documentation: https://trufflesuite.com/docs
Truffle Boxes: http://trufflesuite.com/boxes/
npm package repository: https://www.npmjs.com/package/truffle
Installing the Truffle framework
The Truffle framework comprises several Node.js packages. Before you install Truffle, you need to have an up-to-date and working installation of Node.js and the Node Package Manager (npm).
The recommended way to install Node.js and npm is to use the Node Version Manager (nvm). Once you install nvm, it will handle all the dependencies and updates for you. Follow the instructions found at http://nvm.sh.
Once nvm is installed on your operating system, installing Node.js is simple. Use the --lts flag to tell nvm that you want the most recent “long-term support” (LTS) version of Node.js:
$ nvm install --lts
Confirm you have node and npm installed:
$ node -v v12.16.1 $ npm -v 6.13.4
Next, create a hidden file, .nvmrc, that contains the Node.js version supported by your DApp so developers just need to run nvm install in the root of the project directory and it will automatically install and switch to using that version:
$ node -v > .nvmrc $ nvm install
Looking good. Now to install Truffle:
$ npm -g install truffle + [email protected] added 26 packages from 438 contributors and updated 1 package in 24.229s
Integrating a prebuilt Truffle project (Truffle Box)
If you want to use or create a DApp that builds upon prebuilt boilerplate, go to the Truffle Boxes website, choose an existing Truffle project, and then run the following command to download and extract it:
$ truffle unbox BOX_NAME
Creating a Truffle project directory
For each project where you will use Truffle, create a project directory and initialize Truffle within that directory. Truffle will create the necessary directory structure inside your project directory. It's customary to give the project directory a name that describes the project. For this example, we will use Truffle to deploy our Faucet contract from A Simple Contract: A Test Ether Faucet, and therefore we will name the project folder Faucet:
$ mkdir Faucet $ cd Faucet Faucet $
Once inside the Faucet directory, we initialize Truffle:
Faucet $ truffle init
Truffle creates a directory structure and some default files:
Faucet +---- contracts | `---- Migrations.sol +---- migrations | `---- 1_initial_migration.js +---- test `---- truffle-config.js
We will also use a number of JavaScript (Node.js) support packages, in addition to Truffle itself. We can install these with npm. We initialize the npm directory structure and accept the defaults suggested by npm:
$ npm init package name: (faucet) version: (1.0.0) description: entry point: (truffle-config.js) test command: git repository: keywords: author: license: (ISC) About to write to Faucet/package.json: { "name": "faucet", "version": "1.0.0", "description": "", "main": "truffle-config.js", "directories": { "test": "test" }, "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this ok? (yes)
Now, we can install the dependencies that we will use to make working with Truffle easier:
$ npm install dotenv truffle-wallet-provider ethereumjs-wallet
We now have a __node_modules__ directory with several thousand files inside our Faucet directory.
Prior to deploying a DApp to a cloud production or continuous integration environment, it is important to specify the engines field so that your DApp is built with the correct Node.js version and its associated dependencies are installed. For details on configuring this field, see the documentation.
Configuring Truffle
Truffle creates an empty configuration file, truffle-config.js. Now we edit truffle-config.js and replace the contents with the sample configuation shown here:
module.exports = { networks: { localnode: { // Whatever network our local node connects to network_id: "*", // Match any network ID host: "localhost", port: 8545, } } };
This configuration is a good starting point. It sets up one default Ethereum network (named localnode), which assumes we are running an Ethereum client such as Parity, either as a full node or as a light client. This configuration will instruct Truffle to communicate with the local node over RPC, on port 8545. Truffle will use whatever Ethereum network the local node is connected to, such as the Ethereum main network, or a test network like Ropsten. The local node will also be providing the wallet functionality.
In following sections, we will configure additional networks for Truffle to use, such as the ganache local test blockchain and Infura, a hosted network provider. As we add more networks, the configuration file will get more complex, but it will also give us more options for our testing and development workflow.
Using Truffle to deploy a contract
We now have a basic working directory for our Faucet project, and we have Truffle and its dependencies configured. Contracts go in the contracts subdirectory of our project. The directory already contains a "helper" contract, Migrations.sol, which manages contract upgrades for us. We'll examine the use of Migrations.sol in the next section.
Let's copy the Faucet.sol contract (from Faucet.sol: A Solidity contract implementing a faucet) into the contracts subdirectory, so that the project directory looks like this:
Faucet +---- contracts | +---- Faucet.sol | `---- Migrations.sol ...
We can now ask Truffle to compile the contract for us:
$ truffle compile Compiling ./contracts/Faucet.sol... Compiling ./contracts/Migrations.sol... Writing artifacts to ./build/contracts
Truffle migrations—understanding deployment scripts
Truffle offers a deployment system called a migration. If you have worked in other frameworks, you may have seen something similar: Ruby on Rails, Python Django, and many other languages and frameworks have a migrate command.
In all those frameworks, the purpose of a migration is to handle changes in the data schema between different versions of the software. The purpose of migrations in Ethereum is slightly different. Because Ethereum contracts are immutable and cost gas to deploy, Truffle offers a migration mechanism to keep track of which contracts (and which versions) have already been deployed. In a complex project with dozens of contracts and complex dependencies, you would not want to have to pay to redeploy contracts that haven't changed. You would also not want to manually track which versions of which contracts have been deployed already. The Truffle migration mechanism does all that by deploying the smart contract Migrations.sol, which then keeps track of all other contract deployments.
We have only one contract, Faucet.sol, which means that the migration system is overkill, to say the least. Unfortunately, we have to use it. But, by learning how to use it for one contract, we can start practicing some good habits for our development workflow. The effort will pay off as things get more complicated.
Truffle's migrations directory is where the migration scripts are found. Right now there's only one script, __1_initial_migration.js__, which deploys the Migrations.sol contract itself:
include::code/truffle/Faucet/migrations/1_initial_migration.js[]
We need a second migration script, to deploy Faucet.sol. Let's call it __2_deploy_contracts.js__. It is very simple, just like __1_initial_migration.js__, with only a few small changes. In fact, you can copy the contents of __1_initial_migration.j__ and simply replace all instances of Migrations with Faucet:
include::code/truffle/Faucet/migrations/2_deploy_contracts.js[]
The script initializes a variable Faucet, identifying the Faucet.sol Solidity source code as the artifact that defines Faucet. Then it calls the deploy function to deploy this contract.
We're all set. Let's use truffle migrate to deploy it on. We have to specify which network to deploy the contract, using the --network argument. We only have one network specified in the configuration file, which we named localnode. Make sure your local Ethereum client is running and then type:
Faucet $ truffle migrate --network localnode
Because we are using a local node to connect to the Ethereum network and manage our wallet, we have to authorize the transaction that Truffle creates. We're running parity connected to the Ropsten test blockchain, so during the migration we'll see a pop-up like the one in Parity asking for confirmation to deploy Faucet on Parity's web console.
There are four transactions in total: one to deploy Migrations, one to update the deployments counter to 1, one to deploy Faucet, and one to update the deployments counter to 2.
Truffle will show the migrations completing, show each of the transactions, and show the contract addresses:
$ truffle migrate --network localnode Using network 'localnode'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0xfa090db179d023d2abae543b4a21a1479e70ca7d35a469a5d1a98bfc6bd80fe8 Migrations: 0x8861c27715550bed8362c0345add158489df6db0 Saving successful migration to network... ... 0x985c4a32716826ddbe4eae284104bef8bc69e959899f62246a1b27c9dfcd6c03 Saving artifacts... Running migration: 2_deploy_contracts.js Deploying Faucet... ... 0xecdbeef77f0558edc689440e34b7bba0a3ba7a45e4b680b071b47c30a930e9d6 Faucet: 0xd01cd8e7bd29e4bff8c1693f59eee46137a9f300 Saving successful migration to network... ... 0x11f376bd7307edddfd40dc4a14c3f7cb84b6c921ac2465602060b67d08f9fd8a Saving artifacts...
Using the Truffle console
Truffle offers a JavaScript console that we can use to interact with the Ethereum network (via the local node), interact with deployed contracts, and interact with the wallet provider. In our current configuration (localnode), the node and wallet provider is our local Parity client.
Let's start the Truffle console and try some commands:
$ truffle console --network localnode truffle(localnode)>
Truffle presents a prompt, showing the selected network configuration (localnode).
Tip: It's important to remember and be aware of which network you are using. You wouldn't want to accidentally deploy a test contract or make a transaction on the Ethereum main network. That could be an expensive mistake!
The Truffle console offers an autocomplete function that makes it easy for us to explore the environment. If we press Tab after a partially completed command, Truffle will complete the command for us. Pressing Tab twice will show all possible completions if more than one command matches our input. In fact, if we press Tab twice on an empty prompt, Truffle lists all the available commands:
truffle(localnode)> Array Boolean Date Error EvalError Function Infinity JSON Math NaN Number Object RangeError ReferenceError RegExp String SyntaxError TypeError URIError decodeURI decodeURIComponent encodeURI encodeURIComponent eval isFinite isNaN parseFloat parseInt undefined ArrayBuffer Buffer DataView Faucet Float32Array Float64Array GLOBAL Int16Array Int32Array Int8Array Intl Map Migrations Promise Proxy Reflect Set StateManager Symbol Uint16Array Uint32Array Uint8Array Uint8ClampedArray WeakMap WeakSet WebAssembly XMLHttpRequest _ assert async_hooks buffer child_process clearImmediate clearInterval clearTimeout cluster console crypto dgram dns domain escape events fs global http http2 https module net os path perf_hooks process punycode querystring readline repl require root setImmediate setInterval setTimeout stream string_decoder tls tty unescape url util v8 vm web3 zlib __defineGetter__ __defineSetter__ __lookupGetter__ __lookupSetter__ __proto__ constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf
The vast majority of the wallet- and node-related functions are provided by the web3 object, which is an instance of the web3.js library. The web3 object abstracts the RPC interface to our Parity node. You will also notice two objects with familiar names: Migrations and Faucet. Those represent the contracts we just deployed. We will use the Truffle console to interact with a contract. First, let's check our wallet via the web3 object:
truffle(localnode)> web3.eth.accounts [ '0x9e713963a92c02317a681b9bb3065a8249de124f', '0xdb5dc1a13e3a55cf3b4587cd8d1e5fdeb6738145' ]
Our Parity client has two wallets, with some test ether on Ropsten. The web3.eth.accounts attribute contains a list of all the accounts. We can check the balance of the first account using the getBalance function:
truffle(localnode)> web3.eth.getBalance(web3.eth.accounts[0]).toNumber() 191198572800000000 truffle(localnode)>
web3.js is a large JavaScript library that offers a comprehensive interface to the Ethereum system, via a provider such as a local client. We will examine web3.js in more detail in web3.js Tutorial. Now let's try to interact with our contracts:
truffle(localnode)> Faucet.address '0xd01cd8e7bd29e4bff8c1693f59eee46137a9f300' truffle(localnode)> web3.eth.getBalance(Faucet.address).toNumber() 0 truffle(localnode)>
Next, we'll use sendTransaction to send some test ether to fund the Faucet contract. Note the use of web3.utils.toWei to convert ether units for us. Typing 18 zeros without making a mistake is both difficult and dangerous, so it's always better to use a unit converter for values. Here's how we send the transaction:
truffle(localnode)> web3.eth.sendTransaction({from:web3.eth.accounts[0], to:Faucet.address, value:web3.utils.toWei(0.5, 'ether')}); '0xf134c75b985dc0e0c27c2f0412251e0860eb530a5055e660f21e7483ab336808'
If we switch to the Parity web interface, we'll see a pop-up asking us to confirm this transaction. Once the transaction is mined, we'll be able to see the balance of our Faucet contract:
truffle(localnode)> web3.eth.getBalance(Faucet.address).toNumber() 500000000000000000
Let's call the withdraw function now, to withdraw some test ether from the contract:
truffle(localnode)> Faucet.deployed().then(instance => {instance.withdraw(web3.utils.toWei(0.1, 'ether'))}).then(console.log)
Again, we'll need to approve the transaction in the Parity web interface. If we check again we'll see that the balance of the Faucet contract has decreased, and our test wallet has received 0.1 ether:
truffle(localnode)> web3.eth.getBalance(Faucet.address).toNumber() 400000000000000000 truffle(localnode)> Faucet.deployed().then(instance => {instance.withdraw(web3.utils.toWei(1, 'ether'))}) StatusError: Transaction: 0xe147ae9e3610334...8612b92d3f9c exited with an error (status 0).
Embark
GitHub: https://github.com/embark-framework/embark/
Documentation: https://embark.status.im/docs/
npm package repository: https://www.npmjs.com/package/embark
Embark is a framework built to allow developers to easily develop and deploy decentralized applications. Embark integrates with Ethereum, IPFS, Whisper, and Swarm to offer the following features:
- Automatically deploy contracts and make them available in JS code.
- Watch for changes and update contracts to redeploy if needed.
- Manage and interact with different chains (e.g., testnet, local, mainnet).
- Manage complex systems of interdependent contracts.
- Store and retrieve data, including uploading and retrieving files hosted in IPFS.
- Ease the process of deploying the full application to IPFS or Swarm.
- Send and receive messages through Whisper.
You can install it with npm:
$ npm -g install embark
OpenZeppelin
GitHub: https://github.com/OpenZeppelin/openzeppelin-solidity
Website: https://openzeppelin.org/
Documentation: https://openzeppelin.org/api/docs/open-zeppelin.html
OpenZeppelin is an open framework of reusable and secure smart contracts in the Solidity language.
It is community-driven, led by the Zeppelin team, with over a hundred external contributors. The main focus of the framework is security, achieved by applying industry-standard contract security patterns and best practices, drawing on all the experience the Zeppelin devs have gained from auditing a huge number of contracts, and through constant testing and auditing from the community that uses the framework as a base for their real-world applications.
The OpenZeppelin framework is the most widely used solution for Ethereum smart contracts. The framework currently has an ample library of contracts including implementations of ERC20 and ERC721 tokens, many flavors of crowdsale models, and simple behaviors commonly found in contracts such as Ownable, Pausable, or LimitBalance. The contracts in this repository in some cases function as de facto standard implementations.
The framework is licensed under an MIT license, and all the contracts have been designed with a modular approach to guarantee ease of reuse and extension. These are clean and basic building blocks, ready to be used in your next Ethereum project. Let's set up the framework and build a simple crowdsale using the OpenZeppelin contracts, to demonstrate how easy it is to use. This example also stresses the importance of reusing secure components instead of writing them by yourself.
First, we will need to install the openzeppelin-solidity library into our workspace. The latest release as of the time of this writing is v1.9.0, so we will use that one:
$ mkdir sample-crowdsale $ cd sample-crowdsale $ npm install [email protected] $ mkdir contracts
At the time of writing, OpenZeppelin includes multiple basic token contracts that follow the ERC20, ERC721, and ERC827 standards, with different characteristics for emission, limits, vesting, life cycle, etc.
Let's make an ERC20 token that's mintable, meaning that the initial supply starts at 0 and new tokens can be created by the token owner (in our case, the crowdsale contract) and sold to buyers. In order to do this, we'll create a contracts/SampleToken.sol file with the following contents:
include::code/OpenZeppelin/contracts/SampleToken.sol[]
OpenZeppelin already provides a MintableToken contract that we can use as a base for our token, so we only define the details that are specific to our case. Next, let's make the crowdsale contract. Just like with tokens, OpenZeppelin already provides a wide variety of crowdsale flavors. Currently, you will find contracts for various scenarios involving distribution, emission, price, and validation. So, let’s say that you want to set a goal for your crowdsale and if it’s not met by the time the sale finishes, you want to refund all your investors. For that, you can use the RefundableCrowdsale contract. Or maybe you want to define a crowdsale with an increasing price to incentivize early buyers; there is an IncreasingPriceCrowdsale contract just for that. You can also end the crowdsale when a specified amount of ether has been received by the contract (CappedCrowdsale), or set a finishing time with the TimedCrowdsale contract, or create a whitelist of buyers with the WhitelistedCrowdsale contract.
As we said before, the OpenZeppelin contracts are basic building blocks. These crowdsale contracts have been designed to be combined; just read the source code of the base Crowdsale contract for directions on how to extend it. For the crowdsale of our token, we need to mint tokens when ether is received by the crowdsale contract, so let's use MintedCrowdsale as a base. And to make it more interesting, let's also make it a PostDeliveryCrowdsale so the tokens can only be withdrawn after the crowdsale ends. To do this, we'll write the following into contracts/SampleCrowdsale.sol:
include::code/OpenZeppelin/contracts/SampleCrowdsale.sol[]
Again, we barely had to write any code; we just reused the battle-tested code that the OpenZeppelin community made available. However, it is important to note that this case is different than that of our SampleToken contract. If you go to the Crowdsale automated tests you will see that they are tested in isolation. When you integrate different units of code into a bigger component, it's not enough to test all the units separately, because the interactions between them might cause behaviors that you didn't expect. In particular, you will see that here we introduced multiple inheritance, which can surprise the developer if they don't understand the details of Solidity. Our SampleCrowdsale contract is simple, and it will work just as we expect because the framework was designed to make cases like these straightforward; but do not relax your vigilance because of the simplicity that this framework introduces. Every time you integrate parts of the OpenZeppelin framework to build a more complex solution, you must fully test every aspect of your solution to ensure that all the interactions of the units work as you intend.
Finally, when we are happy with our solution and have tested it thoroughly, we need to deploy it. OpenZeppelin integrates well with Truffle, so we can just write a migrations file like the following (_migrations/2_deploy_contracts.js_), as explained in Truffle migrations—understanding deployment scripts:
include::code/OpenZeppelin/migrations/2_deploy_contracts.js[]
Note: This was just a quick overview of a few of the contracts that are part of the OpenZeppelin framework. You are welcome to join the OpenZeppelin development community to learn and contribute.