==== This simple name registrar has only one function. When the contract is `unlocked`, it allows anyone to register a name (as a `bytes32` hash) and map that name to an address. The registrar is initially locked, and the `require` on line 25 prevents `register` from adding name records. It seems that the contract is unusable, as there is no way to unlock the registry! There is, however, a vulnerability that allows name registration regardless of the `unlocked` variable. // TODO: Andreas to check if this introduction is required as another section // of the book may be able to be referenced. The language may also need to be // adjusted. To discuss this vulnerability, first we need to understand how storage works in Solidity. As a high-level overview (without any proper technical detail—we suggest reading the Solidity docs for a proper review), state variables are stored sequentially in _slots_ as they appear in the contract (they can be grouped together but aren't in this example, so we won't worry about that). Thus, `unlocked` exists in `slot[0]`, `registeredNameRecord` in `slot[1]`, and `resolve` in `slot[2]`, etc. Each of these slots is 32 bytes in size (there are added complexities with mappings, which we'll ignore for now). The Boolean `unlocked` will look like `0x000...0` (64 ++0++s, excluding the `0x`) for `false` or `0x000...1` (63 ++0++s) for `true`. As you can see, there is a significant waste of storage in this particular example. The next piece of the puzzle is that Solidity by default puts complex data types, such as ++struct++s, in storage when initializing them as local variables. Therefore, pass:[<span class="keep-together"><code>newRecord</code></span>] on line 18 defaults to storage. The vulnerability is caused by the fact that pass:[<span class="keep-together"><code>newRecord</code></span>] is not initialized. Because it defaults to storage, it is mapped to storage +slot[0]+, which currently contains a pointer to `unlocked`. Notice that on lines 19 and 20 we then set `newRecord.name` to `_name` and `newRecord.mappedAddress` to pass:[<span class="keep-together"><code>_mappedAddress</code></span>]; this updates the storage locations of +slot[0]+ and +slot[1]+, which modifies both `unlocked` and the storage slot associated with `registeredNameRecord`. This means that `unlocked` can be directly modified, simply by the `bytes32 _name` parameter of the `register` function. Therefore, if the last byte of `_name` is nonzero, it will modify the last byte of storage `slot[0]` and directly change `unlocked` to `true`. Such `_name` values will cause the `require` call on line 25 to succeed, as we have set `unlocked` to `true`. Try this in Remix. Note the function will pass if you use a `_name` of the form:
0x0000000000000000000000000000000000000000000000000000000000000001
[role="notoc"] ==== Preventative Techniques The Solidity compiler shows a warning for unintialized storage variables; developers should pay careful attention to these warnings when building smart contracts. The current version of Mist (0.10) doesn’t allow these contracts to be compiled. It is often good practice to explicitly use the `memory` or `storage` specifiers when dealing with complex types, to ensure they behave as expected. ==== Real-World Examples: OpenAddressLottery and CryptoRoulette Honey Pots A honey pot named http://bit.ly/2AAVnWD[+OpenAddressLottery+] was deployed that used this uninitialized storage variable quirk to collect ether from some would-be hackers. The contract is rather involved, so we will leave the analysis to the http://bit.ly/2OgxPtG[Reddit thread] where the attack is quite clearly explained. Another honey pot, http://bit.ly/2OfNGJ2[+CryptoRoulette+], also utilized this trick pass:[<span class="keep-together">to try</span>] and collect some ether. If you can’t figure out how the attack works, see http://bit.ly/2OVkSL4[“An Analysis of a Couple Ethereum Honeypot Contracts”] for an overview of this contract and others. === Floating Point and Precision As of this writing (v0.4.24), Solidity does not support fixed-point and floating-point numbers. This means that floating-point representations must be constructed with integer types in Solidity. This can lead to errors and vulnerabilities if not implemented correctly. [NOTE] ==== For further reading, see the http://bit.ly/2Ogp2Ia[Ethereum Contract Security Techniques and Tips wiki]. ==== [role="notoc"] ==== The Vulnerability As there is no fixed-point type in Solidity, developers are required to implement their own using the standard integer data types. There are a number of pitfalls developers can run into during this process. We will try to highlight some of these in this section. Let's begin with a code example (we'll ignore over/underflow issues, discussed earlier in this chapter, for simplicity): [source,solidity,linenums]
contract FunWithNumbers { uint constant public tokensPerEth = 10; uint constant public weiPerEth = 1e18; mapping(address => uint) public balances;
function buyTokens() external payable { uint tokens = msg.value/weiPerEth*tokensPerEth; balances[msg.sender] += tokens; }
function sellTokens(uint tokens) public { require(balances[msg.sender] >= tokens); uint eth = tokens/tokensPerEth; balances[msg.sender] -= tokens; msg.sender.transfer(eth*weiPerEth); } }
This simple token buying/selling contract has some obvious problems. Although the mathematical calculations for buying and selling tokens are correct, the lack of floating-point numbers will give erroneous results. For example, when buying tokens on line 8, if the value is less than `1 ether` the initial division will result in `0`, leaving the result of the final multiplication as `0` (e.g., `200 wei` divided by `1e18` `weiPerEth` equals `0`). Similarly, when selling tokens, any number of tokens less than `10` will also result in `0 ether`. In fact, rounding here is always down, so selling `29 tokens` will result in `2 ether`. The issue with this contract is that the precision is only to the nearest ether (i.e., 1e18 wei). This can get tricky when dealing with decimals in https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md[ERC20] tokens when you need higher precision. [role="notoc"] ==== Preventative Techniques Keeping the right precision in your smart contracts is very important, especially when dealing with ratios and rates that reflect economic decisions. You should ensure that any ratios or rates you are using allow for large numerators in fractions. For example, we used the rate `tokensPerEth` in our example. It would have been better to use `weiPerTokens`, which would be a large number. To calculate the corresponding number of tokens we could do `msg.value/weiPerTokens`. This would give a more precise result. Another tactic to keep in mind is to be mindful of order of operations. In our example, the calculation to purchase tokens was `msg.value/weiPerEth*tokenPerEth`. Notice that the division occurs before the multiplication. (Solidity, unlike some languages, guarantees to perform operations in the order in which they are written.) This example would have achieved a greater precision if the calculation performed the multiplication first and then the division; i.e., `msg.value*tokenPerEth/weiPerEth`. Finally, when defining arbitrary precision for numbers it can be a good idea to convert values to higher precision, perform all mathematical operations, then finally convert back down to the precision required for output. Typically ++uint256++s are used (as they are optimal for gas usage); these give approximately 60 orders of magnitude in their range, some of which can be dedicated to the precision of mathematical operations. It may be the case that it is better to keep all variables in high precision in Solidity and convert back to lower precisions in external apps (this is essentially how the `decimals` variable works in ERC20 token contracts). To see an example of how this can be done, we recommend looking at https://github.com/dapphub/ds-math[DS-Math]. It uses some funky naming (“wads” and “rays”), but the concept is useful. ==== Real-World Example: Ethstick The http://bit.ly/2Qb7PSB[+Ethstick+ contract] does not use extended precision; however, it deals with wei. So, this contract will have issues of rounding, but only at the wei level of precision. It has some more serious flaws, but these relate back to the difficulty in getting entropy on the blockchain (see <<entropyillusion_security>>). For a further discussion of the +Ethstick+ contract, we’ll refer you to another post by Peter Vessenes, http://bit.ly/2SwDnE0[“Ethereum Contracts Are Going to Be Candy for Hackers”]. === Tx.Origin Authentication Solidity has a global variable, `tx.origin`, which traverses the entire call stack and contains the address of the account that originally sent the call (or transaction). Using this variable for authentication in a smart contract leaves the contract vulnerable to a phishing-like attack. [NOTE] ==== For further reading, see dbryson's Ethereum http://bit.ly/2PxU1UM[Stack Exchange question], http://bit.ly/2qm7ocJ[“Tx.Origin and Ethereum Oh My!”] by Peter Vessenes, and http://bit.ly/2P3KVA4[“Solidity: Tx Origin Attacks”] by Chris Coverdale. ==== [role="notoc"] ==== The Vulnerability Contracts that authorize users using the `tx.origin` variable are typically vulnerable to phishing attacks that can trick users into performing authenticated actions on the vulnerable contract. Consider the simple contract in <<phishable_security>>. [[phishable_security]] .Phishable.sol ==== [source,solidity,linenums]
contract Phishable { address public owner;
constructor (address _owner) { owner = _owner; }
function () external payable {} // collect ether
function withdrawAll(address _recipient) public { require(tx.origin == owner); _recipient.transfer(this.balance); } }
==== Notice that on line 11 the contract authorizes the `withdrawAll` function using `tx.origin`. This contract allows for an attacker to create an attacking contract of the form: [source,solidity,linenums]
import "Phishable.sol";
contract AttackContract {
Phishable phishableContract; address attacker; // The attacker's address to receive funds
constructor (Phishable _phishableContract, address _attackerAddress) { phishableContract = _phishableContract; attacker = _attackerAddress; }
function () payable { phishableContract.withdrawAll(attacker); } }
The attacker might disguise this contract as their own private address and socially engineer the victim (the owner of the +Phishable+ contract) to send some form of transaction to the address—perhaps sending this contract some amount of ether. The victim, unless careful, may not notice that there is code at the attacker’s address, or the attacker might pass it off as being a multisignature wallet or some advanced storage wallet (remember that the source code of public contracts is not available by default). In any case, if the victim sends a transaction with enough gas to the `AttackContract` address, it will invoke the fallback function, which in turn calls the `withdrawAll` function of the `Phishable` contract with the parameter `attacker`. This will result in the withdrawal of all funds from the `Phishable` contract to the `attacker` address. This is because the address that first initialized the call was the victim (i.e., the owner of the `Phishable` contract). Therefore, `tx.origin` will be equal to `owner` and the `require` on line 11 of the `Phishable` contract will pass. [role="notoc"] ==== Preventative Techniques `tx.origin` should not be used for authorization in smart contracts. This isn’t to say that the `tx.origin` variable should never be used. It does have some legitimate use cases in smart contracts. For example, if one wanted to deny external contracts from calling the current contract, one could implement a `require` of the form `require(tx.origin == msg.sender)`. This prevents intermediate contracts being used to call the current contract, limiting the contract to regular codeless addresses. [[contract_libraries_sec]] === Contract Libraries There is a lot of existing code available for reuse, both deployed on-chain as callable libraries and off-chain as code template libraries. On-platform libraries, having been deployed, exist as bytecode smart contracts, so great care should be taken before using them in production. However, using well-established existing on-platform libraries comes with many advantages, such as being able to benefit from the latest upgrades, and saves you money and benefits the Ethereum ecosystem by reducing the total number of live contracts in Ethereum. In Ethereum, the most widely used resource is the https://openzeppelin.org/[OpenZeppelin suite], an ample library of contracts ranging from implementations of ERC20 and ERC721 tokens, to many flavors of crowdsale models, to simple behaviors commonly found in contracts, such as `Ownable`, `Pausable`, or `LimitBalance`. The contracts in this repository have been extensively tested and in some cases even function as _de facto_ standard implementations. They are free to use, and are built and maintained by https://zeppelin.solutions[Zeppelin] together with an ever-growing list of external contributors. Also from Zeppelin is https://zeppelinos.org/[ZeppelinOS], an open source platform of services and tools to develop and manage smart contract applications securely. ZeppelinOS provides a layer on top of the EVM that makes it easy for developers to launch upgradeable DApps linked to an on-chain library of well-tested contracts that are themselves upgradeable. Different versions of these libraries can coexist on the Ethereum platform, and a vouching system allows users to propose or push improvements in different directions. A set of off-chain tools to debug, test, deploy, and monitor decentralized applications is also provided by the platform. The project +ethpm+ aims to organize the various resources that are developing in the ecosystem by providing a package management system. As such, their registry provides more examples for you to browse: * Website: https://www.ethpm.com/ * Repository link: https://www.ethpm.com/registry * GitHub link: https://github.com/ethpm * Documentation: https://www.ethpm.com/docs/integration-guide === Conclusions There is a lot for any developer working in the smart contract domain to know and understand. By following best practices in your smart contract design and code writing, you will avoid many severe pitfalls and traps. Perhaps the most fundamental software security principle is to maximize reuse of trusted code. In cryptography, this is so important it has been condensed into an adage: "Don't roll your own crypto." In the case of smart contracts, this amounts to gaining as much as possible from freely available libraries that have been thoroughly vetted by the community.
Tokens
The word "token" derives from the Old English "tācen," meaning a sign or symbol. It is commonly used to refer to privately issued special-purpose coin-like items of insignificant intrinsic value, such as transportation tokens, laundry tokens, and arcade game tokens.
Nowadays, "tokens" administered on blockchains are redefining the word to mean blockchain-based abstractions that can be owned and that represent assets, currency, or access rights.
The association between the word "token" and insignificant value has a lot to do with the limited use of the physical versions of tokens. Often restricted to specific businesses, organizations, or locations, physical tokens are not easily exchangeable and typically have only one function. With blockchain tokens, these restrictions are lifted—or, more accurately, completely redefinable. Many blockchain tokens serve multiple purposes globally and can be traded for each other or for other currencies on global liquid markets. With the restrictions on use and ownership gone, the "insignificant value" expectation is also a thing of the past.
In this chapter, we look at various uses for tokens and how they are created. We also discuss attributes of tokens such as fungibility and intrinsicality. Finally, we examine the standards and technologies that they are based on, and experiment by building our own tokens.
How Tokens Are Used
The most obvious use of tokens is as digital private currencies. However, this is only one possible use. Tokens can be programmed to serve many different functions, often overlapping. For example, a token can simultaneously convey a voting right, an access right, and ownership of a resource. As the following list shows, currency is just the first "app":
- Currency: A token can serve as a form of currency, with a value determined through private trade.
- Resource: A token can represent a resource earned or produced in a sharing economy or resource-sharing environment; for example, a storage or CPU token representing resources that can be shared over a network.
- Asset: A token can represent ownership of an intrinsic or extrinsic, tangible or intangible asset; for example, gold, real estate, a car, oil, energy, MMOG items, etc.
- Access: A token can represent access rights and grant access to a digital or physical property, such as a discussion forum, an exclusive website, a hotel room, or a rental car.
- Equity: A token can represent shareholder equity in a digital organization (e.g., a DAO) or legal entity (e.g., a corporation).
- Voting: A token can represent voting rights in a digital or legal system.
- Collectible: A token can represent a digital collectible (e.g., CryptoPunks) or physical collectible (e.g., a painting).
- Identity: A token can represent a digital identity (e.g., avatar) or legal identity (e.g., national ID).
- Attestation: A token can represent a certification or attestation of fact by some authority or by a decentralized reputation system (e.g., marriage record, birth certificate, college degree).
- Utility: A token can be used to access or pay for a service.
Often, a single token encompasses several of these functions. Sometimes it is hard to discern between them, as the physical equivalents have always been inextricably linked. For example, in the physical world, a driver's license (attestation) is also an identity document (identity) and the two cannot be separated. In the digital realm, previously commingled functions can be separated and developed independently (e.g., an anonymous attestation).
Tokens and Fungibility
Wikipedia says: "In economics, fungibility is the property of a good or a commodity whose individual units are essentially interchangeable."
Tokens are fungible when we can substitute any single unit of the token for another without any difference in its value or function.
Strictly speaking, if a token's historical provenance can be tracked, then it is not entirely fungible. The ability to track provenance can lead to blacklisting and whitelisting, reducing or eliminating fungibility.
Non-fungible tokens are tokens that each represent a unique tangible or intangible item and therefore are not interchangeable. For example, a token that represents ownership of a specific Van Gogh painting is not equivalent to another token that represents a Picasso, even though they might be part of the same "art ownership token" system. Similarly, a token representing a specific digital collectible such as a specific CryptoKitty is not interchangeable with any other CryptoKitty. Each non-fungible token is associated with a unique identifier, such as a serial number.
We will see examples of both fungible and non-fungible tokens later in this chapter.
Note: Note that "fungible" is often used to mean "directly exchangeable for money" (for example, a casino token can be "cashed in," while laundry tokens typically cannot). This is not the sense in which we use the word here.
Counterparty Risk
Counterparty risk is the risk that the other party in a transaction will fail to meet their obligations. Some types of transactions suffer additional counterparty risk because there are more than two parties involved. For example, if you hold a certificate of deposit for a precious metal and you sell that to someone, there are at least three parties in that transaction: the seller, the buyer, and the custodian of the precious metal. Someone holds the physical asset; by necessity they become party to the fulfillment of the transaction and add counterparty risk to any transaction involving that asset. In general, when an asset is traded indirectly through the exchange of a token of ownership, there is additional counterparty risk from the custodian of the asset. Do they have the asset? Will they recognize (or allow) the transfer of ownership based on the transfer of a token (such as a certificate, deed, title, or digital token)? In the world of digital tokens representing assets, as in the nondigital world, it is important to understand who holds the asset that is represented by the token and what rules apply to that underlying asset.
Tokens and Intrinsicality
The word "intrinsic" derives from the Latin "intra," meaning "from within."
Some tokens represent digital items that are intrinsic to the blockchain. Those digital assets are governed by consensus rules, just like the tokens themselves. This has an important implication: tokens that represent intrinsic assets do not carry additional counterparty risk. If you hold the keys for a CryptoKitty, there is no other party holding that CryptoKitty for you—you own it directly. The blockchain consensus rules apply and your ownership (i.e., control) of the private keys is equivalent to ownership of the asset, without any intermediary.
Conversely, many tokens are used to represent extrinsic things, such as real estate, corporate voting shares, trademarks, and gold bars. The ownership of these items, which are not "within" the blockchain, is governed by law, custom, and policy, separate from the consensus rules that govern the token. In other words, token issuers and owners may still depend on real-world non-smart contracts. As a result, these extrinsic assets carry additional counterparty risk because they are held by custodians, recorded in external registries, or controlled by laws and policies outside the blockchain environment.
One of the most important ramifications of blockchain-based tokens is the ability to convert extrinsic assets into intrinsic assets and thereby remove counterparty risk. A good example is moving from equity in a corporation (extrinsic) to an equity or voting token in a DAO or similar (intrinsic) organization.
Using Tokens: Utility or Equity
Almost all projects in Ethereum today launch with some kind of token. But do all these projects really need tokens? Are there any disadvantages to using a token, or will we see the slogan "tokenize all the things" come to fruition? In principle, the use of tokens can be seen as the ultimate management or organization tool. In practice, the integration of blockchain platforms, including Ethereum, into the existing structures of society means that, so far, there are many limitations to their applicability.
Let's start by clarifying the role of a token in a new project. The majority of projects are using tokens in one of two ways: either as "utility tokens" or as "equity tokens." Very often, those two roles are conflated.
Utility tokens are those where the use of the token is required to gain access to a service, application, or resource. Examples of utility tokens include tokens that represent resources such as shared storage, or access to services such as social media networks.
Equity tokens are those that represent shares in the control or ownership of something, such as a startup. Equity tokens can be as limited as nonvoting shares for distribution of dividends and profits, or as expansive as voting shares in a decentralized autonomous organization, where management of the platform is through some complex governance system based on votes by the token holders.
It's a Duck!
Many startups face a difficult problem: tokens are a great fundraising mechanism, but offering securities (equity) to the public is a regulated activity in most jurisdictions. By disguising equity tokens as utility tokens, many startups hope to get around these regulatory restrictions and raise money from a public offering while presenting it as a pre-sale of "service access vouchers" or, as we call them, utility tokens. Whether these thinly disguised equity offerings will be able to skirt the regulators remains to be seen.
As the popular saying goes: "If it walks like a duck and quacks like a duck, it's a duck." Regulators are not likely to be distracted by these semantic contortions; quite the opposite, they are more likely to see such legal sophistry as an attempt to deceive the public.
Utility Tokens: Who Needs Them?
The real problem is that utility tokens introduce significant risks and adoption barriers for startups. Perhaps in a distant future "tokenize all the things" will become reality, but at present the set of people who have an understanding of and desire to use a token is a subset of the already small cryptocurrency market.
For a startup, each innovation represents a risk and a market filter. Innovation is taking the road least traveled, walking away from the path of tradition. It is already a lonely walk. If a startup is trying to innovate in a new area of technology, such as storage sharing over P2P networks, that is a lonely enough path. Adding a utility token to that innovation and requiring users to adopt tokens in order to use the service compounds the risk and increases the barriers to adoption. It's walking off the already lonely trail of P2P storage innovation and into the wilderness.
Think of each innovation as a filter. It limits adoption to the subset of the market that can become early adopters of this innovation. Adding a second filter compounds that effect, further limiting the addressable market. You are asking your early adopters to adopt not one but two completely new technologies: the novel application/platform/service you built, and the token economy.
For a startup, each innovation introduces risks that increase the chance of failure of the startup. If you take your already risky startup idea and add a utility token, you are adding all the risks of the underlying platform (Ethereum), broader economy (exchanges, liquidity), regulatory environment (equity/commodity regulators), and technology (smart contracts, token standards). That's a lot of risk for a startup.
Advocates of "tokenize all the things" will likely counter that by adopting tokens they are also inheriting the market enthusiasm, early adopters, technology, innovation, and liquidity of the entire token economy. That is true too. The question is whether the benefits and enthusiasm outweigh the risks and uncertainties.
Nevertheless, some of the most innovative business ideas are indeed taking place in the crypto realm. If regulators are not quick enough to adopt laws and support new business models, entrepreneurs and associated talent will seek to operate in other jurisdictions that are more crypto-friendly. This is already happening.
Finally, at the beginning of this chapter, when introducing tokens, we discussed the colloquial meaning of "token" as "something of insignificant value." The underlying reason for the insignificant value of most tokens is because they can only be used in a very narrow context: one bus company, one laundromat, one arcade, one hotel, or one company store. Limited liquidity, limited applicability, and high conversion costs reduce the value of tokens until they are only of "token" value. So when you add a utility token to your platform, but the token can only be used on your single platform with a small market, you are recreating the conditions that made physical tokens worthless. This may indeed be the correct way to incorporate tokenization into your project. However, if in order to use your platform a user has to convert something into your utility token, use it, and then convert the remainder back into something more generally useful, you've created a company scrip. The switching costs of a digital token are orders of magnitude lower than for a physical token without a market, but they are not zero. Utility tokens that work across an entire industry sector will be very interesting and probably quite valuable. But if you set up your startup to have to bootstrap an entire industry standard in order to succeed, you may have already failed.
Note: One of the benefits of deploying services on general-purpose platforms like Ethereum is being able to connect smart contracts (and therefore the utility of tokens) across projects, increasing the potential for liquidity and utility of tokens.
Make this decision for the right reasons. Adopt a token because your application cannot work without a token. Adopt it because the token lifts a fundamental market barrier or solves an access problem. Don't introduce a utility token because it is the only way you can raise money fast and you need to pretend it's not a public securities offering.
Tokens on Ethereum
Blockchain tokens existed before Ethereum. In some ways, the first blockchain currency, Bitcoin, is a token itself. Many token platforms were also developed on Bitcoin and other cryptocurrencies before Ethereum. However, the introduction of the first token standard on Ethereum led to an explosion of tokens.
Vitalik Buterin suggested tokens as one of the most obvious and useful applications of a generalized programmable blockchain such as Ethereum. In fact, in the first year of Ethereum, it was common to see Vitalik and others wearing T-shirts emblazoned with the Ethereum logo and a smart contract sample on the back. There were several variations of this T-shirt, but the most common showed an implementation of a token.
Before we delve into the details of creating tokens on Ethereum, it is important to have an overview of how tokens work on Ethereum. Tokens are different from ether because the Ethereum protocol does not know anything about them. Sending ether is an intrinsic action of the Ethereum platform, but sending or even owning tokens is not. The ether balance of Ethereum accounts is handled at the protocol level, whereas the token balance of Ethereum accounts is handled at the smart contract level. In order to create a new token on Ethereum, you must create a new smart contract. Once deployed, the smart contract handles everything, including ownership, transfers, and access rights. You can write your smart contract to perform all the necessary actions any way you want, but it is probably wisest to follow an existing standard. We will look at such standards next. We discuss the pros and cons of the following standards at the end of the chapter.
The ERC20 Token Standard
The first standard was introduced in November 2015 by Fabian Vogelsteller as an Ethereum Request for Comments (ERC). It was automatically assigned GitHub issue number 20, giving rise to the name "ERC20 token." The vast majority of tokens are currently based on the ERC20 standard. The ERC20 request for comments eventually became Ethereum Improvement Proposal 20 (EIP-20), but it is mostly still referred to by the original name, ERC20.
ERC20 is a standard for fungible tokens, meaning that different units of an ERC20 token are interchangeable and have no unique properties.
The ERC20 standard defines a common interface for contracts implementing a token, such that any compatible token can be accessed and used in the same way. The interface consists of a number of functions that must be present in every implementation of the standard, as well as some optional functions and attributes that may be added by developers.
ERC20 required functions and events
An ERC20-compliant token contract must provide at least the following functions and events:
- totalSupply: Returns the total units of this token that currently exist. ERC20 tokens can have a fixed or a variable supply.
- balanceOf: Given an address, returns the token balance of that address.
- transfer: Given an address and amount, transfers that amount of tokens to that address, from the balance of the address that executed the transfer.
- transferFrom: Given a sender, recipient, and amount, transfers tokens from one account to another. Used in combination with approve.
- approve: Given a recipient address and amount, authorizes that address to execute several transfers up to that amount, from the account that issued the approval.
- allowance: Given an owner address and a spender address, returns the remaining amount that the spender is approved to withdraw from the owner.
- Transfer: Event triggered upon a successful transfer (call to transfer or transferFrom) (even for zero-value transfers).
- Approval: Event logged upon a successful call to approve.
ERC20 optional functions
In addition to the required functions listed in the previous section, the following optional functions are also defined by the standard:
- name: Returns the human-readable name (e.g., "US Dollars") of the token.
- symbol: Returns a human-readable symbol (e.g., "USD") for the token.
- decimals: Returns the number of decimals used to divide token amounts. For example, if decimals is 2, then the token amount is divided by 100 to get its user representation.
The ERC20 interface defined in Solidity
Here's what an ERC20 interface specification looks like in Solidity:
contract ERC20 { function totalSupply() constant returns (uint theTotalSupply); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
ERC20 data structures
If you examine any ERC20 implementation you will see that it contains two data structures, one to track balances and one to track allowances. In Solidity, they are implemented with a data mapping.
The first data mapping implements an internal table of token balances, by owner. This allows the token contract to keep track of who owns the tokens. Each transfer is a deduction from one balance and an addition to another balance:
mapping(address => uint256) balances;
The second data structure is a data mapping of allowances. As we will see in the next section, with ERC20 tokens an owner of a token can delegate authority to a spender, allowing them to spend a specific amount (allowance) from the owner's balance. The ERC20 contract keeps track of the allowances with a two-dimensional mapping, with the primary key being the address of the token owner, mapping to a spender address and an allowance amount:
mapping (address => mapping (address => uint256)) public allowed;
ERC20 workflows: "transfer" and "approve & transferFrom"
The ERC20 token standard has two transfer functions. You might be wondering why.
ERC20 allows for two different workflows. The first is a single-transaction, straightforward workflow using the transfer function. This workflow is the one used by wallets to send tokens to other wallets. The vast majority of token transactions happen with the transfer workflow.
Executing the transfer contract is very simple. If Alice wants to send 10 tokens to Bob, her wallet sends a transaction to the token contract's address, calling the transfer function with Bob's address and 10 as the arguments. The token contract adjusts Alice's balance (–10) and Bob's balance (+10) and issues a Transfer event.
The second workflow is a two-transaction workflow that uses approve followed by transferFrom. This workflow allows a token owner to delegate their control to another address. It is most often used to delegate control to a contract for distribution of tokens, but it can also be used by exchanges.
For example, if a company is selling tokens for an ICO, they can approve a crowdsale contract address to distribute a certain amount of tokens. The crowdsale contract can then transferFrom the token contract owner's balance to each buyer of the token, as illustrated in The two-step approve & transferFrom workflow of ERC20 tokens.
Note: An Initial Coin Offering (ICO) is a crowdfunding mechanism used by companies and organizations to raise money by selling tokens. The term is derived from Initial Public Offering (IPO), which is the process by which a public company offers shares for sale to investors on a stock exchange. Unlike the highly regulated IPO markets, ICOs are open, global, and messy. The examples and explanations of ICOs in this book are not an endorsement of this type of fundraising.
For the approve & transferFrom workflow, two transactions are needed. Let's say that Alice wants to allow the AliceICO contract to sell 50% of all the AliceCoin tokens to buyers like Bob and Charlie. First, Alice launches the AliceCoin ERC20 contract, issuing all the AliceCoin to her own address. Then, Alice launches the AliceICO contract that can sell tokens for ether. Next, Alice initiates the approve & transferFrom workflow. She sends a transaction to the AliceCoin contract, calling approve with the address of the AliceICO contract and 50% of the totalSupply as arguments. This will trigger the Approval event. Now, the AliceICO contract can sell AliceCoin.
When the AliceICO contract receives ether from Bob, it needs to send some AliceCoin to Bob in return. Within the AliceICO contract is an exchange rate between AliceCoin and ether. The exchange rate that Alice set when she created the AliceICO contract determines how many tokens Bob will receive for the amount of ether sent to the AliceICO contract. When the AliceICO contract calls the AliceCoin transferFrom function, it sets Alice's address as the sender and Bob's address as the recipient, and uses the exchange rate to determine how many AliceCoin tokens will be transferred to Bob in the value field. The AliceCoin contract transfers the balance from Alice's address to Bob's address and triggers a Transfer event. The AliceICO contract can call transferFrom an unlimited number of times, as long as it doesn't exceed the approval limit Alice set. The AliceICO contract can keep track of how many AliceCoin tokens it can sell by calling the allowance function.
ERC20 implementations
While it is possible to implement an ERC20-compatible token in about 30 lines of Solidity code, most implementations are more complex. This is to account for potential security vulnerabilities. There are two implementations mentioned in the EIP-20 standard:
Consensys EIP20:: A simple and easy-to-read implementation of an ERC20-compatible token.
OpenZeppelin StandardToken:: This implementation is ERC20-compatible, with additional security precautions. It forms the basis of OpenZeppelin libraries implementing more complex ERC20-compatible tokens with fundraising caps, auctions, vesting schedules, and other features.
Launching Our Own ERC20 Token
Let's create and launch our own token. For this example, we will use the Truffle framework. The example assumes you have already installed truffle and configured it, and are familiar with its basic operation (for details, see Truffle).
We will call our token "Mastering Ethereum Token,” with the symbol "MET."
Note: You can find this example in the book's GitHub repository.
First, let's create and initialize a Truffle project directory. Run these four commands and accept the default answers to any questions:
$ mkdir METoken $ cd METoken METoken $ truffle init METoken $ npm init
You should now have the following directory structure:
METoken/ +---- contracts | `---- Migrations.sol +---- migrations | `---- 1_initial_migration.js +---- package.json +---- test `---- truffle-config.js
Edit the truffle-config.js configuration file to set up your Truffle environment, or copy the latter from the repository.
If you use the example truffle-config.js, remember to create a file .env in the METoken folder containing your test private keys for testing and deployment on public Ethereum test networks, such as Ropsten or Kovan. You can export your test network private key from MetaMask.
After that your directory should look like:
METoken/ +---- contracts | `---- Migrations.sol +---- migrations | `---- 1_initial_migration.js +---- package.json +---- test +---- truffle-config.js `---- .env *new file*
Warning: Only use test keys or test mnemonics that are not used to hold funds on the main Ethereum network. Never use keys that hold real money for testing.
For our example, we will import the OpenZeppelin library, which implements some important security checks and is easy to extend:
$ npm install [email protected] + [email protected] added 1 package from 1 contributor and audited 2381 packages in 4.074s
The openzeppelin-solidity package will add about 250 files under the __node_modules__ directory. The OpenZeppelin library includes a lot more than the ERC20 token, but we will only use a small part of it.
Next, let's write our token contract. Create a new file, METoken.sol, and copy the example code from GitHub.
Our contract, shown in METoken.sol: A Solidity contract implementing an ERC20 token, is very simple, as it inherits all its functionality from the OpenZeppelin library.
METoken.sol: A Solidity contract implementing an ERC20 token
include::code/truffle/METoken/contracts/METoken.sol[]
Here, we are defining the optional variables name, symbol, and decimals. We also define an _initial_supply variable, set to 21 million tokens; with two decimals of subdivision that gives 2.1 billion total units. In the contract's initialization (constructor) function we set the totalSupply to be equal to _initial_supply and allocate all of the _initial_supply to the balance of the account (msg.sender) that creates the METoken contract.
We now use truffle to compile the METoken code:
$ truffle compile Compiling ./contracts/METoken.sol... Compiling ./contracts/Migrations.sol... Compiling openzeppelin-solidity/contracts/math/SafeMath.sol... Compiling openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol... Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20.sol... Compiling openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol... Compiling openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol...
As you can see, truffle incorporates necessary dependencies from the OpenZeppelin libraries and compiles those contracts too.
Let's set up a migration script to deploy the METoken contract. Create a new file called __2_deploy_contracts.js__, in the METoken/migrations folder. Copy the contents from the example in the GitHub repository: