Chapter 4. The Evolution to Ethereum
In its early days, Bitcoin was considered an all-encompassing technological marvel. Over time, however, developers began to realize that blockchain technology could support additional features. This led to the introduction of new concepts built on top of Bitcoin, and then an entirely new blockchain known as Ethereum.
Improving Bitcoin’s Limited Functionality
Bitcoin was the first decentralized consensus protocol to apply the concept of scripted money—that is, the idea that cryptocurrency transactions could transmit funds depending on the true/false status of running a limited program. Initially, many saw bitcoin as “programmable money,” but scripted money is a better analogy due to its limited functionality. Similarly, in the early days bitcoin was typically viewed as a currency, but along the way it began to be looked at as more of a store of value and sparked many debates on the difference between the two.
The evolution of Bitcoin led an influential and ardent group of followers in the developer community to advocate for a cautious and limited approach to protocol changes, for security and safety reasons. Protocol changes like block size increases were viewed with skepticism. These advocates wanted to maintain the core goals of remaining decentralized and being inclusive, to the extent that anyone could run a full node on cheap hardware with a low-throughput internet connection.
As we touched on in the previous chapter, however, some Bitcoin developers prompted a movement toward scaling solutions. Bitcoin became the foundation for what would become programmable money as developers began to devise ways to build on top of it, then later build entirely new blockchains.
Colored Coins and Tokens
Colored coins enable real-world assets such as equities (e.g., stocks) or commodities (e.g., gold) to be represented and managed on the Bitcoin blockchain. Bitcoin’s scripting language is intentionally designed as Turing incomplete, meaning the available built-in commands are limited to reduce complexity in the network. Because of this, colored coins are built on top of, rather than directly on, the Bitcoin blockchain.
Bitcoin is limited in scope. However, its blockchain enables the storage of small amounts of data or metadata. The representation of some other asset can be attributed to the value of some amount of bitcoin via an address (for example, 17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem). The concept of colored coins introduced the idea of tokens, which are units of value built by programming a unique ledger on top of an existing blockchain. Tokens often look and act like other cryptocurrencies, with the exception that they are powered by another blockchain network. Tokens were foundational to the development of Ethereum’s ecosystem, and the advent of colored coins on Bitcoin led to tokens on other blockchains.
Mastercoin and Smart Contracts
The evolution of Bitcoin’s scaling solutions advanced in 2013 with the development of Mastercoin. Mastercoin was built on top of Bitcoin to add features not originally included in Bitcoin’s core protocol. This allowed for more sophisticated programmable money concepts beyond Bitcoin’s simple functionality. One of these was the concept of smart contracts, which are complex programs that run on blockchains.
Mastercoin introduced the notion of additional cryptocurrencies, or tokens. Before Mastercoin, it was not easy to create new cryptocurrencies outside of software forks. The ability to allow money sent to a wallet to be rerouted to another wallet via smart contracts was not a feature of Bitcoin. In essence, Mastercoin, though now considered primitive, became a study of the capabilities of Bitcoin and exploring new functionality.
Mastercoin (and its inventor, J.R. Willett) is also credited with providing the first initial coin offering (ICO), a blockchain-based fundraising mechanism created to fund the initial protocol development.
Understanding Omni Layer
Omni Layer is an open source, decentralized asset infrastructure built on Bitcoin. It is the successor of the work produced by the Mastercoin Foundation with the funding from its ICO in 2013. Omni Layer is an ongoing project, with its reference implementation known as Omni Core.
Omni Core essentially enhances elements of Bitcoin with additional features. It also provides smart contract capabilities, enabling developers to automate currency functions in a decentralized and transparent way. Smart contracts let transactions and agreements execute on the blockchain, performing functions beyond currency operations. These functions include the ability to use tokens to create new cryptocurrencies built on top of other blockchain protocols (among other properties explained in Chapter 5). Figure 4-1 illustrates the basic structure of how Omni works.
Tokens created on Omni include MaidSafe, a decentralized autonomous data network first proposed by engineer David Irvine in 2006. MaidSafe later implemented Omni Layer by using smart contract technology to enable an ICO, creating the MAID token, which is used within the network.
Tether
The most well-known project built on Omni is Tether. It encompasses a use case that is incredibly important in the cryptocurrency world: how to represent a stable asset class in an ecosystem of volatile tokens. Tether is a digital blockchain cryptocurrency, and its aim is to provide a stable reserve currency pegged to the US dollar. According to the Tether whitepaper, one Tether token is pegged to one US dollar.
Real-world assets do present a problem when represented on a blockchain. That is, how do you actually peg the value of that asset in tokenized form? Tether claims to be backed by the US dollar, but unfortunately other than its website listing balances, there is little evidence that there really is one US dollar in a bank account for every tether in circulation. The company behind Tether promised to do a full audit of its one-to-one peg to the US dollar, but in 2018 it dissolved its relationship with its accounting firm without explanation. The total outstanding tether on the market arbitrarily fluctuates, and tether has even lost its one USD to one tether peg in the markets only to recover without much explanation.
While Tether is an interesting early use case for tokenization and implementation of Mastercoin’s successor Omni Layer, it is still very experimental. It shows that backing a digital blockchain cryptocurrency such as tether with real-world assets such as the US dollar is still highly speculative and a work in progress.
How Omni Layer works
The Omni Layer team set out to build all the features that J.R. Willett promised in his “Second Bitcoin Whitepaper”. These features included the following:
- Custom currencies
- Anyone can create currencies where the ledger is managed by the Omni Layer network.
- Decentralized exchange
- Instead of using a centralized exchange to facilitate the exchange of two currencies between parties, the Omni Layer code executes this trade.
When launching a proof-of-work–based blockchain, it is important to build a strong network of miners to dedicate hash power (computer infrastructure) to processing transactions. The larger the network, the more decentralized, trustworthy, and secure it becomes.
Omni wanted to focus its efforts on making tokenization and other smart contract features work on a decentralized blockchain without the burden of building that network effect. By building a second-layer protocol on top of Bitcoin, Omni benefited from the large network effect Bitcoin already had.
Adding custom logic
Bitcoin performs logical operations—rules that maintain the blockchain, proving that the fundamental concept of achieving consensus works. Omni adds custom logical operations to the Bitcoin blockchain.
After March 2014, Bitcoin added the OP_RETURN
field, which enables the attachment of additional data to a bitcoin transaction. Once the OP_RETURN
field was added to Bitcoin, every Omni transaction began storing a record within the OP_RETURN
field of a bitcoin transaction.
Figure 4-2 shows an example Tether transaction recorded on the Bitcoin blockchain. This is a small transaction of five tether, also known as USDT. The transaction ID on the Bitcoin blockchain is:
c082fad4ee07a86c3ff9f31fb840d878c66082ad76ca81f0cafc866dee8aa9fc
This is a Bitcoin transaction that contains Omni Layer metadata. The only difference in an Omni transaction is the OP_RETURN
field. Omni uses OP_RETURN
because it provides enough space and is simple to use. The metadata in the OP_RETURN
field translates to five USDT being sent. Figure 4-3 shows the same transaction in Omniexplorer. Notice that the transaction ID is the same.
The value of the OP_RETURN
field, 6f6d6e69000000000000001f000000001dcd6500
, is the Omni Layer metadata that records the UDST transaction. The metadata is encoded in hex format, and Table 4-1 converts it into ASCII or decimal format.
Value stored in OP_RETURN (hex) | As ASCII or decimal | Description |
---|---|---|
6f6d6e69 |
omni | Omni flag to identify that it’s an Omni transaction. |
00000000 |
Simple send | Transaction type. |
0000001f |
31 | Property type is 31, which is USDT. You can view all of the Omni Layer properties on the Omniexplorer site. |
000000001dcd6500 |
5.00000000 | Amount to send is 5.00000000. Omni Layer transactions all contain eight decimal places. |
Ethereum: Taking Mastercoin to the Next Level
Ethereum represents an evolution in the design of and thinking about cryptocurrency networks. It’s a more functional and general computation protocol that draws upon concepts from Bitcoin and Mastercoin, among other projects.
The Ethereum concept was first proposed by Vitalik Buterin in 2013. After lobbying the Mastercoin Foundation to make changes to its protocol and add more functionality, and noting their reluctance to do so, Buterin began working with Gavin Wood and subsequently other founders to create the Ethereum protocol.
The aim of Ethereum was to take Mastercoin to the next level—that is, to create a decentralized, open computer system secured with consensus. Although Buterin envisioned Ethereum having an alternative to Bitcoin’s proof-of-work mechanism, which he deemed wasteful, it currently uses a similar proof-of-work algorithm to Bitcoin called Ethash. Ethereum is expected to move to a proof-of-stake security model in the future—an ambitious project that changes the mining paradigm within the protocol, which is discussed more in Chapter 10.
Ether and Gas
The unit of account in Ethereum is ether. This cryptocurrency behaves in a similar fashion to bitcoin, with similar transaction address nomenclature. Ethereum addresses start with the sequence 0x. The blockchain has much faster confirmation times, save for periodic network congestion, and Ethereum is known to be a much faster transfer mechanism than Bitcoin.
As described in Chapter 2, Bitcoin uses an unspent transaction output (UTXO) structure to track the balances in accounts. Ethereum tracks the balances in the account state. UTXO is like having physical cash—bills and coins. Ethereum’s approach is like having all your funds in a bank account. With UTXO, it’s a lot more complex to make payments and calculate an account’s balance.
For example, let’s say you’re at a coffee shop. You have three $1 bills in your pocket, and you want to buy a coffee for $1.50. You can’t give the cashier $1.50; you have to give them two of the $1 bills and receive $0.50 back in change. Afterward, if you want to know how much money you have to spend, you have to calculate the value of all the bills and coins in your pocket.
It’s the same thing with Bitcoin. Suppose your Bitcoin address has received three separate 1 BTC transactions, and you want to send 1.5 BTC to a friend. Like with physical cash, you can’t send 1.5 BTC; you have to send 2 BTC. This is because each of those 1 BTC transactions you received in the past must be spent as a whole amount. So, you send two of the previous 1 BTC transactions, and in return you get 0.5 BTC change. This process occurs in a single bitcoin transaction.
Ethereum transactions are a lot simpler, similar to sending and receiving funds stored in a bank account. If your Ethereum address receives three separate 1 ETH transactions, your balance showing on the network will be 3 ETH. There is no need to calculate your account balance by adding up the different transactions yourself. And if you want to send 1.5 ETH, you can just send 1.5 ETH; there’s no need to send more and receive change.
Ethereum also offers additional functionality. It takes elements from Bitcoin and Mastercoin to create application-based blockchain transactions, meaning it provides more functions than just account-based sending and receiving. Ethereum has another unit of account called gas. Gas enables developers to run applications on the Ethereum platform—these applications are known as decentralized applications, or dapps (discussed in detail later in this chapter).
Gas also solves one of the dangers of operating a programming language in a blockchain. Developers can run dapps on Ethereum without encountering what is known as the halting problem, or the inability to prevent code that runs indefinitely or in infinite loops. Ethereum requires gas to be used for computations of executed code within a smart contract, so that a dapp is as efficient as is possible. With every Ethereum transaction, developers specify a gas limit so if there’s an infinite loop, the transaction will eventually run out of gas, and the miner will still earn the fees for running the transaction.
Use Cases: ICOs
There are a number of applications for a computerized transaction protocol using smart contracts. The concept of Ricardian contracts as proposed by Ian Grigg in 1996 provides insight into the realm of use cases for this technology. Innovations include using a cryptographic hash function for identification and defining legal elements as machine-readable by a computer. By being able to execute a set of instructions (via a smart contract) and associate it with an accounting system (via a blockchain), the Ethereum platform can be used to run a number of different dapps.
During the early years after Ethereum’s release, it took time for a developer ecosystem to grow. But developers realized that one of its most powerful capabilities was the possibility of raising cryptocurrency funds in an automated and secure fashion, utilizing smart contracts—the already-mentioned ICO. For example, a project needing to raise money to launch a concept could set up a smart contract to take in ether. In return, it could give the donors a redeemable cryptocurrency built on top of Ethereum.
Note
The legality of ICOs is questionable, and many projects have been ended prematurely because of legal problems they have caused. This issue is discussed in more detail in Chapter 9.
The idea of raising cryptocurrency funds to launch a project didn’t begin with Ethereum. Entrepreneur Erik Voorhees raised money using the rudimentary mechanism of accepting bitcoin in return for digital “shares” in order to fund the blockchain-based gambling site Satoshi Dice in 2012. Mastercoin also used this concept, albeit in a much more organized fashion.
The ICO for MaidSafe was so oversold that donors eventually had to redeem incoming bitcoin with mastercoin instead of safecoin. Technical glitches such as this highlighted the need for a more reliable platform for crypto fundraising. Over time, as Ethereum matured, its smart contract platform coupled with the ability to create tokens on top of the Ethereum blockchain made it an ideal automated fundraising apparatus for jump-starting various cryptocurrency projects.
Decentralized Autonomous Organizations
In an effort to further the ethos of decentralization in the Ethereum ecosystem, the concept of a decentralized autonomous organization (DAO) was proposed as a way to utilize smart contracts to replace the governance of centralized authorities. Much like how the ICO concept replaces the centralized functions of an initial public offering (IPO), DAOs use cryptocurrency fundraising projects to create a distributed governance system whereby ICO investors have voting rights commensurate with ownership of tokens purchased in an ICO.
This concept was put to the ultimate test in a project known as The DAO. Launched in April 2016, The DAO was a smart contract–based ICO project built on Ethereum that was designed to run autonomously. Decisions made on the investment of raised funds into technology projects were to be based on the voting rights of token holders. The DAO was able to raise over $154 million via Ethereum-based tokens from eleven thousand investors.
Forking Ethereum and the creation of Ethereum Classic
After its launch, a number of vulnerabilities were discovered in The DAO’s smart contract code. One of these issues included a recursive call vulnerability. The programmers had identified a flaw in the code: when funds were withdrawn from a wallet, the balance was only updated at the end of the function call. If the same function could be called again before the initial call completed, it would be possible to keep withdrawing the same funds over and over—a problem known as infinite recursion.
They immediately announced that the bug had been identified and would be fixed, but before they were able to roll out their update, on June 17, 2016, this vulnerability was exploited by an attacker who was able to steal over $50 million in ether from The DAO. There was no recourse for The DAO’s developers to update the deployed contract code itself, because it was stored immutably on the blockchain. The only way to rectify the situation was to deploy a new contract and move the remaining funds over—a cumbersome and painful process.
This event led to the Ethereum Foundation forking the Ethereum blockchain, in order to undo the damage. It created two distinct versions of Ethereum: the original blockchain with the stolen funds still credited to the attacker, known as Ethereum Classic, and a forked version that retracted said funds, which continued to be known as Ethereum. This hard fork moved the stolen funds to a recovery address so their rightful owners could reclaim them.
The fork meant changing the Ethereum blockchain so that The DAO hack had effectively never happened, violating the principle of immutability. This was a controversial decision that was resisted by some members of the community, who chose to continue with the unaltered version of the blockchain. Ethereum Classic is a smart contract blockchain that still exists today, but its developer community is small and not as robust as Ethereum’s.
Other Ethereum forks
The DAO hack warmed up the cryptocurrency community to the idea of forks. In addition to creating Ethereum Classic, the Ethereum blockchain has been forked several other times to compensate for vulnerabilities and other changes in code. The Ethereum project understands the need to experiment, and when upgrades that are deemed important for the entire community become apparent, forking is seen as a better alternative than maintaining the concept of immutability. The Ethereum ecosystem has no qualms about forking its blockchain and gathering enough momentum for such changes to be successful. This attitude stands in stark contrast to other chains, like Bitcoin, where immutability is sacrosanct.
Key Organizations in the Ethereum Ecosystem
In the Ethereum ecosystem, multiple stakeholders and organizations support the vision that Ethereum is building, and each organization supports it from its own angle.
The Ethereum Foundation
As a leader in developing the roadmap and implementing further changes to the Ethereum platform, the Ethereum Foundation wields significant influence in the community. It also funds scalability projects related to the platform, including Plasma, a solution that aims to increase the number of transactions on the platform without sacrificing the security of the network.
The Ethereum Foundation’s predecessor was formed as a Swiss nonprofit entity, and initiated Ethereum’s ICO. After raising over $18 million from the community in bitcoin, the Swiss entity transferred those funds to the Ethereum Foundation, which has been the key provider of funding for the aforementioned development efforts.
The Enterprise Ethereum Alliance
Announced in early 2017, the Enterprise Ethereum Alliance (EEA) aims to band together corporate entities interested in deployment of Ethereum blockchain solutions. Members of the EEA include IBM and Microsoft, which supports running Ethereum blockchain services on top of Azure.
One of the main goals of the EEA is finding blockchain-specific use cases in corporate business environments. Many large organizations are wary of the cryptocurrency aspect of blockchains because of compliance and other regulatory concerns. A good deal of the Ethereum-related work being done on the corporate side involves forking it to create a private blockchain that separates the token from public cryptocurrency markets. Chapter 9 discusses private and permissioned blockchains further.
Parity
Parity, a London-based software solutions company, was formed by Gavin Wood, one of the original founders of Ethereum who contributed code very early on in the formation of Ethereum’s protocol concepts. Parity has deployed several developer tools to make Ethereum easier to deploy, including reference frameworks.
The company is known for falling victim to the “Parity hack” in 2017, where $30 million worth of ether was stolen by an unknown attacker. This was the second-largest Ethereum hack (after The DAO); it exploited a vulnerability in Parity’s multi-signature wallets that enabled the attacker to send two transactions, one of which included abstracting logic to change a wallet address in the code.
ConsenSys
Founded by Ethereum cofounder Joseph Lubin, ConsenSys is an organization that develops enterprise applications, invests in startups, builds developer tools, and offers blockchain education for the Ethereum network. The organization focuses on the development of dapps. Its offerings include the Truffle Suite, a framework that makes Ethereum development easier, and Gitcoin, a GitHub-inspired bug bounty tool for the Ethereum blockchain.
ConsenSys also has a mission to create consumer-friendly tools within the Ethereum ecosystem. One of the most well-known of these is MetaMask, a browser-based Ethereum wallet that makes using decentralized applications easier. ConsenSys also funds projects that create dapps and other useful applications.
Decentralized Applications (Dapps)
We’ve mentioned already that applications that run via a smart contract on a blockchain are known as decentralized apps, or dapps. Dapps are typically architected with a backend using a smart contract running on a blockchain and a thin frontend UI that interacts with it. It’s similar to a client/server architecture, where the server is the smart contract. These types of applications make the blockchain more programmable and more functional.
A dapp is basically any computer program that runs on a smart contract platform, and the largest platform for this today is Ethereum. As we discussed in Chapter 1, in computer science, a distributed system is one in which the components are located on disparate computing resources, and a system is in place for communications to occur between these resources. Examples of distributed systems include many telecommunication networks and the web.
There are other platforms that provide the capability for dapps, but Ethereum is by far the largest platform for developers to execute distributed code.
Use Cases
A key feature of a dapp is immutability, meaning no centralized authority can change the code after it has been published to the blockchain. For this reason, use cases for dapps are generally found where there is a bottleneck in centralized systems. Many centralized applications, for example, are not censorship-resistant. In many centralized apps, a third party decides what users can and cannot see. Often these decisions are subjective, seemingly arbitrary, and made without input from users. With the use of a backend platform such as Ethereum and the web, developers can deploy applications that are permissionless, which greatly differ from their centralized counterparts.
Another feature of dapps is that they enable efficient and secure transfer of digital assets through the use of blockchains. For example, today many applications offer censorship resistance (think BitTorrent) and privacy (through encryption). However, what dapps enable beyond these two properties is that transfer of value can be executed quickly and programmatically.
Note
Dapp platforms are relatively new. There’s still lots to learn about how best to create them, and the infrastructure for doing so is still in its growth stages. Dapps are not yet widely used. In fact, there’s some question about their traction and staying power, and the purposes of some dapps today seem nefarious. Many of them are designed to avoid regulatory scrutiny, and there are numerous gambling, gaming, and decentralized exchange dapps in use.
Challenges in Developing Dapps
There are several design challenges inherent to creating dapps today, including concerns about deployment, user experience, speed, and scalability. These issues currently exist across all dapp platforms, including Ethereum.
When a developer deploys a smart contract for a dapp, they need to be sure that its code does not contain critical flaws. It is not easy to update contracts. Most smart contract platforms, including Ethereum, do not permit redeploying to the same address. In addition, upgrading usually entails difficult data migration of the state that the smart contract manages.
Developers can test their dapps on one of four Ethereum testnets. Responsible dapp developers will spend months getting their contracts audited by professional security auditors (Quantstamp, OpenZeppelin), who then publish their reports to the public. During this time, they will also invite people in the community to audit their smart contracts through GitHub.
Unlike with centralized apps, where a user’s experience is continuous, deploying new smart contract code could cause a break in the user experience. Also, the speed of dapps relies on the speed of the blockchain and its confirmation times. This issue was brought to the fore on Ethereum in late 2017 with the dapp CryptoKitties, whose popularity led to an enormous number of transactions congesting the Ethereum network. This made the dapp virtually unusable until enthusiasm died down.
Now that you have some background, let’s dive a bit more deeply into authoring, deploying, and working with Ethereum smart contracts.
Deploying and Executing Smart Contracts in Ethereum
Smart contracts have come a long way since the concept was first proposed in the 1990s. Omni Layer proved that running a dapp on top of a blockchain was possible, but it had many limitations, the biggest of which was who was given permission to author and deploy the dapp. If someone wanted to deploy a dapp, they had to convince the platform’s developers to add it to the Omni Core code. In effect, Omni Core was the dapp where all code was deployed. The development of code was centralized, and only Omni Core developers could update it. Developers who wanted to deploy dapps on their own had to explore other options, such as forking Omni Core and making their own client that ran on top of Bitcoin—not an easy endeavor.
Other limitations of Omni Core included the following:
- Blockchain scaling and speed depended on Bitcoin and its core developers
- Omni Core still has limited influence over the future of the blockchain it runs on.
- The Bitcoin blockchain is not designed for program execution
- It’s optimized for store of value, and its limited scripting language means that it will never be suitable for sophisticated smart contracts built directly on top of the blockchain. For example, the
OP_RETURN
field has a storage limit of 80 bytes, which limits the types of programs you can run in Omni Layer.
The Ethereum Virtual Machine
The Ethereum Virtual Machine (EVM) makes it easy for developers to create dapps and for the network to execute them. The purpose of the EVM is twofold:
-
Allow developers to deploy smart contracts to the blockchain
-
Instruct miners on how to execute EVM smart contract code embedded in the software that they run
Authoring a smart contract
Developers can use a few different languages to author a smart contract. The most common language is Solidity.
Tip
ConsenSys has released a suite of tools to make it easy for developers to author, debug, and deploy smart contracts with Solidity, called the Truffle Suite.
To interact with a smart contract, you need an Ethereum wallet. The most popular wallet is MetaMask, which is a browser extension. This wallet stores a copy of your seed and private keys locally on your machine.
Note
The seed and private key are not stored centrally. It’s important to make a physical copy of the mnemonic seed (e.g., on paper) and store it in a safe place for redundancy. In addition, using a hardware wallet rather than relying on private keys being held locally by the wallet software can help increase security. For more on wallet choices, see Chapter 2.
Before deploying your smart contract to the main Ethereum network, it is wise to test it on one of the most common testnets:
Smart contract developers need to spend ether in the form of gas to deploy and change the state of a contract. All Ethereum testnets have faucets where you can get testnet ETH (tETH) for free. These testnets make for an ideal staging environment for smart contracts.
Deploying a smart contract
After a developer has written a smart contract, they can publish it to the mainnet or production environment, or any of the testnets. Publishing is done by sending a smart contract transaction to the Ethereum network. The easiest way to generate this transaction is by using the Ethereum Remix tool.
Remix is a cloud-based integrated development environment (IDE) for smart contract development. It supports the Solidity and Vyper languages, and since it’s a website there is no need to install software. It lets developers write, debug, compile, and distribute smart contract code to the Ethereum network, including the mainnet and testnet environments.
Figure 4-4 shows what deploying the Mastering_Blockchain_Guestbook.sol smart contract on Remix looks like. In this case, it’s being deployed to the Ropsten network.
To deploy the smart contract, you must click the Deploy button. Remix then sends the transaction data to MetaMask, which asks for your authorization to complete the transaction.
After the transaction is authorized, MetaMask pushes a smart contract creation transaction to the network. Figure 4-5 shows what this looks like.
Note the following in this transaction:
-
The value of the transaction is 0 ether, indicating that no ether were transferred.
-
The transaction is being recorded in block #5357662.
-
The miner who discovered this block receives a transaction fee of 0.00137715 Testnet ETH (tETH).
After the Ethereum network processes a transaction, it stores the smart contract on the Ethereum network in bytecode format, which takes up less space, as illustrated in Figure 4-6.
Since the smart contract code is on the Ethereum testnet, it is viewable by the public (see Figure 4-7).
When a smart contract is created, it is given an Ethereum address. This Ethereum address can hold an ETH balance and send/receive ETH just like a normal Ethereum address can.
Interacting with a smart contract
Now that the Guestbook smart contract has been deployed to the Ethereum testnet, it’s possible to begin reading data from it and writing data to it. To read data from the contract you just ping the network directly, like making a call to a public API. However, to write data to the contract, you must send a transaction to the contract address.
All read/write interactions with a smart contract require a reference to the contract’s application binary interface (ABI). The ABI is like an API for a smart contract. ABIs are machine-readable, meaning they are easy to parse by client software to understand how to interact with the contract code. An ABI documents all the functions and their attributes.
Here is the ABI for the Guestbook smart contract:
[{"constant":true,"inputs":[{"name":"_bookentrynumber","type":"uint256"}], "name":"getmessagefromreader","outputs":[{"name":"_messagefromreader", "type":"string"}],"payable":false,"stateMutability":"view","type":"function"}, {"constant":true,"inputs":[],"name":"getnumberofmessagesfromreaders", "outputs":[{"name":"_numberofmessages","type":"uint256"}],"payable":false, "stateMutability":"view","type":"function"}, {"constant":true,"inputs":[],"name":"getmessagefromauthors", "outputs":[{"name":"_name","type":"string"}],"payable":false, "stateMutability":"view","type":"function"}, {"constant":false,"inputs":[{"name":"_messagefromreader","type":"string"}], "name":"setmessagefromreader","outputs":[],"payable":false, "stateMutability":"nonpayable","type":"function"}, {"constant":false,"inputs":[{"name":"_messagefromauthors","type":"string"}], "name":"setmessagefromauthors","outputs":[],"payable":false, "stateMutability":"nonpayable","type":"function"}, {"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]
Reading a smart contract
Let’s read the data in the Guestbook smart contract. You should see something like Figure 4-8.
This figure shows the three read functions that the Guestbook smart contract has. The first function requires an input to return data, and the other two don’t.
Writing a smart contract
Let’s now write some data to the Guestbook smart contract. This will look something like Figure 4-9.
The MetaMask browser extension will provide you with the choice to connect to the website or not. After connecting to the website, you can start writing data to the contract. Notice that two things happen when you click Confirm:
-
Etherscan generates a new transaction, populating it with the correct data, and pushes it to your MetaMask wallet.
-
MetaMask then asks for authorization to send that transaction.
After you click Confirm, your transaction gets pushed to the Ethereum network.
Executing a smart contract
As part of block discovery, Ethereum miners add transactions to blocks in much the same fashion as Bitcoin miners. There are two main actions a transaction can trigger:
- Payment
- Send ETH value from address A to address B.
- Execution
- Execute the smart contract.
If the following are true, then the miner will execute the smart contract code through the EVM:
-
The receiving address is a smart contract.
-
The data payload contains data.
The earlier test message example created a transaction where the receiving address is the Mastering_Blockchain_Guestbook smart contract, and the data payload contains the following data:
Function: setmessagefromreader(string_messagefromreader) MethodID: 0xe4cb814b [0]: 0000000000000000000000000000000000000000000000000000000000000020 [1]: 0000000000000000000000000000000000000000000000000000000000000020 [2]: 5468697320697320612074657374206d6573736167652c206279204c6f726e65
Gas and Pricing
As we’ve discussed, gas is a unit of account used in the Ethereum ecosystem to calculate how much ether miners are paid to process transactions. When a miner executes a smart contract transaction through the EVM, the miner executes opcodes—instructions at the machine level—that are written in the smart contract. Each opcode that it runs has a gas price associated with it.
Figure 4-10 shows examples of opcodes and gas prices.
Gas is necessary because it rewards miners for processing a transaction through a smart contract. It also defends the network against spam and denial-of-service attacks. Gas is paid in ETH. The miner receives the usual fixed block reward for discovering the block, plus the ETH received from gas for processing all the smart contract code.
When structuring a transaction, there are two gas-related fields you need to input:
- Gas price
- The amount of ETH paid for each unit of gas. If a user wants their transaction to be processed immediately, they can pay a higher gas price to incentivize the miner to choose their transaction over other transactions waiting to be processed.
- Gas limit
- The maximum amount of gas you are willing to pay the miner to process your transaction. The amount of gas specified here should be sufficient to run all the opcodes the contract function is expected to perform.
Note
Wei is the smallest unit of ether (ETH), which is 10e-18 ETH. The US dollar is divisible by two decimal places. ETH is divisible by 18 decimal places. Just as the US dollar has the penny as its smallest unit of value, a wei is the smallest unit of value in Ethereum. A satoshi is the smallest unit of value for Bitcoin.
Here are a few more of the denominations:
-
1 wei = 1 wei
-
1 kwei = 1,000 wei
-
1 mwei = 1,000,000 wei
-
1 gwei = 1,000,000,000 wei
Tip
ETH Gas Station is a very useful site for calculating what gas price you should pay based on the current network usage.
In the earlier Guestbook smart contract example, where we wrote a test message, the amounts were as follows:
-
Gas limit: 128,050
-
Gas used by transaction: 85,367 (66.67%)
-
Gas price: 0.000000001 ether (1 gwei)
Interacting with Code
Here are a couple of popular methods for programmatically interacting with the Ethereum network:
- Web3.js
- The most common way developers make their websites interact with MetaMask and smart contracts is through Web3.js, a Node.js library.
- Infura
- Another popular option is Infura, which provides a REST API to the Ethereum network. This API is structured in a way that is familiar to developers. The advantage of using Infura is that the learning curve to deploying is much lower because it handles access to Ethereum. The disadvantage is that developers must trust Infura to secure and pass along data properly.
Summary
The Ethereum ecosystem developed quickly from an idea publicly proposed in 2014 to the full-fledged network it is today. Thanks to its smart contract properties and the vast number of resources and tools being created in the ecosystem, many developers now choose to build on Ethereum rather than Bitcoin. Ethereum and Bitcoin do share some technology, but their advancement is certainly going in separate ways.
Get Mastering Blockchain now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.