Super User

Tezos Blockchain and Smart Contract Overview

In this article, we review the Tezos project, which some experts have already called the “Ethereum killer.” And these aren’t just words; the project was able to raise almost a record amount of money during its ICO in 2017, equal to $232 million. This allows Tezos to occupy second place in the ranking of the most successful ICO deals.

In this article, we explain the main features of the Tezos smart contract platform and provide an example of a Tezos smart contract. This article will be useful for blockchain developers who are considering creating a project on Tezos.

Written by: Mihail Sotnichek, Software Developer, System Programming Team

Contents:

What is Tezos blockchain?

Distinctive features of Tezos

Self-amendment protocol

On-chain governance

Consensus mechanism

Michelson programming language

Tezos smart contracts

Developing an example of Tezos smart contract

Smart contract written in Liquidity

Smart contract written in Michelson

Common guidelines to Tezos smart contract development

Conclusion

What is the Tezos blockchain?

The Tezos blockchain project was founded by a US company, Dynamic Ledger Solutions, as an alternative to Ethereum. Tezos was created as a new-generation decentralized platform with unique network update and smart contract functionality. It’s also a platform for developing decentralized applications (DApps).

The Tezos team introduced on-chain governance where token holders are authorized to govern blockchain development. In addition, the security of smart contracts is ensured with the Michelson programming language, which supports formal verification. Unlike other popular platforms like Bitcoin and Ethereum, which use Proof of Work algorithms, Tezos benefits from Proof of Stake to achieve distributed consensus. All that sounds pretty interesting so far, doesn’t it?

Distinctive features of Tezos

There are many popular smart contract platforms, including Ethereum, EOS, and Lisk. How is Tezos different? Let’s look closer at the unique features of Tezos that attract so many supporters.

Self-amendment protocol

Analyzing the experience of Ethereum, Tezos developers decided to avoid hard forks by introducing a protocol that’s capable of self-amendment. This allows for automatic platform updates while reducing protocol coordination expenses.

Moreover, innovative technologies can easily be implemented in the Tezos blockchain. In addition to all these protocol benefits, self-amendment reduces the risk of the Tezos community splitting over time.

On-chain governance

As for platform users, they not only come to a consensus on the state of the shared ledger; the protocol itself is also shaped by the community. In Tezos, there’s an on-chain form of governance that ensures smooth evolution of the platform. Independent developers can submit proposals for protocol updates.

Tezos token holders consider and approve proposals submitted by developers. An agreement between stakeholders is reached due to implemented election cycles. All approved changes are checked by the Tezos development team and deployed to the test network to pass certain formal tests. There’s an incentive system, so developers receive compensation for their contributions to the platform. Speedy protocol updates and hard-coded procedures make a hard fork unlikely.

Consensus mechanism

For achieving distributed consensus over the network, Tezos uses a Proof of Stake algorithm, which selects the next block creator via various combinations of random selection and wealth (the stake). This allows owners of at least 10,000 XTZ to participate in validating transactions and receive remuneration. There’s also delegation, letting members participate in polls and take part in the development of the project.

The Proof of Stake algorithm allows Tezos developers to introduce so-called baking for signing and publishing a new block to the chain instead of the power-consuming mining used by platforms based on a Proof of Work algorithm.

Instead of miners, Tezos has bakers who have the right to create new token blocks. A baker can be any network member who owns at least 10,000 XTZ (a roll), qualifying the member as a delegate or endorser. Network users give permissions or delegate tokens for baking. Bakers are selected randomly for each baking cycle, which lasts for 4096 blocks (three days on average). Bakers validate all transactions and add them to the block every 60 seconds. The throughput of the Tezos network is currently approximately 40 transactions per second, while Ethereum, in contrast, can handle only 15 transactions per second.

Tezos also has 32 randomly selected endorsers who verify the last generated block. Bakers and endorsers are rewarded for their work, but they’re required to provide a deposit for each generated or confirmed block.

Baking is a revolutionary way to create new blocks. It doesn’t require so much computing power as mining. All that bakers need is a secure and stable internet connection and at least 8GB of RAM.

Michelson programming language

Michelson, a domain-specific language, was created for the Tezos blockchain. This is a low-level language that manipulates the stack and avoids using variables and named functions. It’s statically typed, purely functional, and offers maps, sets, lists, and cryptographic primitives. One of the most distinctive features of Michelson is that it looks like a compilation target rather than a standard programming language.

Michelson is tailored to create common pieces of business logic, such as multi-signature wallets, distribution rules, authority, and crowdfunding. It’s not designed to create general-purpose DApps like Crypto Kitties.

Unlike Ethereum, whose Solidity smart contracts get compiled to EVM bytecode that’s run on the Ethereum virtual machine, Tezos uses Michelson as the environment for smart contracts. So any Michelson code that’s saved to the blockchain is exactly the code that will be executed. Thus, using Michelson, developers can eliminate various errors that can occur in Ethereum-based cryptocurrencies.

However, Michelson is free of many traditional features, so some developers may find it difficult to develop smart contracts in this language — especially those who have previously worked with Solidity.

It may be easier for some developers to use a custom compiler for creating programs in another language and then translating them to Michelson. In fact, there’s already Liquidity that strictly complies with Michelson security restrictions. Liquidity is a high-level language that covers all features of Michelson. This language is itself based on OCaml, but when creating a smart contract, Liquidity code can be converted to Michelson. There’s even an online development environment where it’s possible to write and test for the Tezos smart contract platform in Liquidity.

Tezos smart contracts

Tezos provides users with the ability to create smart contracts. Smart contracts are small programs that are stored and executed on the blockchain. They allow people to cooperate and exchange tokens without requiring them to trust one another. You can find more information about the concept of smart contracts here.

Smart contracts in Tezos are unique, as they’re written in Michelson. In addition, Tezos supports formal verification, which guarantees the correctness of smart contract code with respect to a specification. Smart contract code can be proved mathematically according to certain properties. Using formal verification, the Tezos project makes smart contracts more secure and reliable.

Read also:

Formal Verification of Smart Contracts with the K Framework

If you decide to work with Tezos smart contracts, you’ll get the following advantages:

A specialized set of tools for creating serious business-oriented DApps

The ability to easily analyze smart contract code

No need to rely on any compilers to translate your program into unreadable bytecode

Combining these features with the network’s high performance thanks to its Proof of Stake consensus (in contrast to the more popular Proof of Work approach), we get a solid competitor in the smart contract world.

Developing a sample Tezos smart contract

We’ll provide an example of a smart contract written for the Tezos platform in Michelson and Liquidity (as the main compiler for Michelson).

This contract describes a simple auction. Users send their bids to the contract. If the sent bid is greater than the one in the contract, then the old bid is returned and the new one is saved in the contract. This is repeated until the auction ends. As a result, the winner is the one whose bid remains at the end of the auction.

Related services: Blockchain Development

Smart contract written in Liquidity

Let’s take a look at the smart contract written in Liquidity, which we’ll further compile to Michelson. First, we have to define the global storage of the smart contract. For these purposes, we’ll use several primitive types (including integers and strings) and some more complex types like key-value pairs, timestamps, token amounts (tez), etc. The storage is the output of each execution of the smart contract, which is stored on the blockchain. So we have to store information about the highest bidder and their bid as well as the time when the auction should end:

type storage = { auction_end : timestamp; highest_bid : tez; bidder : key_hash; }

Then we have to define the main function by specifying its name and parameters:

let%entry main (parameter : key_hash)

Here, we’ve specified the main function with a single parameter, namely the address of the bidder. In case there’s only one function, the Liquidity compiler will translate the contract to Michelson with no overhead. However, if there are multiple functions, the compiler will have to add an extra parameter and a bunch of “if” statements in order to figure out which function to execute. The Michelson language has only one code block, which is executed every time you invoke the contract.

Once we have the function defined, we can add our code. The full contract will then look like this:

[%%version 0.4] type storage = { auction_end : timestamp; highest_bid : tez; bidder : key_hash; } let%entry main (parameter : key_hash) (storage : storage) = (* Check if auction has ended *) if Current.time () > storage.auction_end then Current.failwith ("The auction has ended"); let new_bid = Current.amount () in let new_bidder = parameter in (* Check if new bid is higher that the last *) if new_bid <= storage.highest_bid then Current.failwith ("The bid is too low"); let previous_bidder = storage.bidder in let previous_bid = storage.highest_bid in (* Set new highest bid in storage *) let storage = storage.highest_bid <- new_bid in let storage = storage.bidder <- new_bidder in (* refund previous bid to previous bidder *) let refund_to = Account.default previous_bidder in let op = Contract.call refund_to previous_bid () in ([op], storage)

The contract is really simple. We check if the auction is still running and compare the position of a new bid with the previous and update the storage values accordingly.

We could interact with the contract directly from the online IDE or using the Tezos-client command-line application. The process of setting up a Tezos node is somewhat complicated, but it’s well described in the documentation.

Once we have the node set up, we can deploy the contract:

tezos-client originate contract auction_contract for test_account transferring 2.01 from test_account running ./auction.tz

This will deploy the contract with the name auction_contract, owned by the test_account. During contract creation, 2.01 tez will be transferred to the contract as an initial bid.

After deployment, we can perform some actions with the contract — for example, place a bid:

tezos-client transfer 5 from test_account to auction_contract -arg '"tz2efa3BEDroCiF7oJ5jn3Mv2cvevAy73AeU"'

This action will place a bid of 5 tez for a bidder with the specified key hash.

Smart contract written in Michelson

Here’s how this smart contract will look in Michelson:

parameter key_hash ; storage (pair :storage (timestamp %auction_end) (pair (mutez %highest_bid) (key_hash %bidder))) ; code { DUP; DIP{CDR;}; CAR; DUUP @storage; CAR %auction_end; NOW; COMPARE; GT; IF { PUSH string The auction has ended"; FAILWITH; } { UNIT; ; DROP; AMOUNT @new_bid; DUUUP @storage; CDAR %highest_bid; DUUP @new_bid; COMPARE; LE; IF { PUSH string "The bid is too low"; FAILWITH; } { UNIT; }; DROP; DUUUP @storage; CDDR @previous_bidder %bidder; IMPLICIT_ACCOUNT @refund_to; DUUUUP @storage; CDAR @previous_bid %highest_bid; UNIT; TRANSFER_TOKENS @op; DUUUUP @storage; DUP; CAR %auction_end; SWAP; CDR; CDR %bidder; DUUUUP @new_bid; DIIIIP { DROP; }; DIIIIIP { DROP; }; PAIR %highest_bid %bidder; SWAP; PAIR @storage %auction_end; DUP; CAR %auction_end; SWAP; CDR; CAR %highest_bid; DUUUUP ; DIIIIP { DROP; }; SWAP; PAIR %highest_bid %bidder; SWAP; PAIR @storage %auction_end; NIL operation; DUUUP; DIIIP { DROP; }; CONS; PAIR; } ;

As you can see, the smart contract in Michelson is quite hard to understand and thus develop, so we recommend using Liquidity instead.

Common guidelines to Tezos smart contract development

Unfortunately, exploiting smart contracts for fun and profit has been popular lately, as demonstrated by numerous reports of stolen tokens, hacked wallets, and lost funds. Smart contract vulnerabilities have caused a lot of damage to nearly every platform in the past couple of years.

As any new platform, Tezos hasn’t been free of negative press and vulnerabilities. At the start of the project, Tezos had to overcome class action lawsuits, a management crisis, and a delay in receiving funds from ICO contributors.

Not so long ago, a Tezos blockchain vulnerability caused a network slowdown for between one to twenty minutes. A bug was discovered in baker and node communications that used the JSON data exchange format. The JSON serializer incorrectly processed some characters, and as a result, data was not exchanged.

In addition, certain Tezos wallets appeared to be vulnerable to blind signature attacks. These wallets didn’t check the binary code of the server before signing a transaction, so hackers could easily drain users’ funds.

Fortunately, Tezos developers provide strong support for their platform, and all these vulnerabilities were fixed as soon as possible.

The main goal of any professional smart contract developer is to avoid vulnerabilities. Most mature development communities have proven tools and best practices that help ensure smart contracts are secure. Compared to those communities, Liquidity and Michelson are still nascent. However, this doesn’t mean we can’t learn from other’s mistakes.

Here are some common guidelines that can be applied to smart contracts written for the Tezos blockchain:

Avoid batch operations when users can increase the size of the batch.

This can lead to a DoS attack. If a malicious user spams the contract with many small transactions, the contract can become unusable.

Avoid refunding to a list of contracts.

Sending multiple transfers to untrusted destinations can introduce vulnerability to DoS attacks. Therefore, it’s better to make sure that a malicious contract won’t be executed during a transfer. Alternatively, perform transfers one at a time by requiring users to pull funds.

Make sure that a message cannot be valid ever again.

Failing to make some parameters unique may result in repeatable transactions that would allow for a replay attack, such as double-spending funds.

Avoid storing or transferring unprotected private data.

All data on the blockchain is public. Make sure to hash or encrypt any sensitive information.

Don’t store funds for others in spendable contracts.

This one is specific for Tezos projects, whose smart contracts may be explicitly marked as spendable.

Conclusion

Tezos is a young blockchain platform with lots of prospects for smart contract development. The most interesting features of Tezos are its:

Proof-of-Stake consensus

high transaction throughput

powerful language

simplified formal verification for smart contract security.

This platform has a chance of becoming the next Ethereum.

Our team of blockchain developers has extensive experience building blockchain solutions, and we’ll be glad to help you create smart contracts on Tezos. We can also conduct a security audit of your smart contracts.