Smart contracts occupy a separate niche in software development. They are small, immutable, visible to everyone, run on decentralized nodes and, on top of that, transfer user funds.
The smart contracts ecosystem is evolving rapidly, obtaining new development tools, practices, and vulnerabilities. The latter often costs a lot, as security weaknesses in smart contracts result in immediate financial losses.
In many cases, smart contracts cannot be easily updated after deployment. So, they should be analyzed and checked in every way before they land on the blockchain—to mitigate possible exploits and provide quick response mechanisms for potential threats.
What are smart contracts?
In simple words, a smart contract is a code stored on a blockchain. Let's have a deeper look.
We can think of smart contracts as state machines. A smart contract has storage, or state, which is a collection of some data fields. A user can invoke the contract by providing specific parameters. The contract executes the code and either fails or returns a new state (storage with updated data fields). What exactly is stored and accepted by the contract is determined by its source code.
In Tezos, invocations and parameter passing are performed with transactions or, more generally, operations. To call the contract, a user creates a regular transaction (but with arguments) to the contract's address. Then the transaction goes into the transaction pool.
Bakers (often called “miners” in other blockchains) choose transactions from the pool for creating the next block. If the transaction is a contract invocation, the baker executes the code, obtains new storage, and embeds it into the block. When the block is baked, other nodes execute the same contract with the same parameters and compare obtained storages with the original one to validate the operation.
Interaction with other contracts
Besides the storage, the contract can generate a list of operations that may contain calls to other contracts, which, in turn, can create new operations. In Tezos, these operations are collected into a queue. It drastically differs from what Ethereum has with its stack-based approach. The queue-based design makes it hard to conduct reentrancy attacks, as we will discuss later.
If one of the contracts fails, the whole operation fails. In this way, contract executions are atomic.
Accounts
On Tezos, you can have implicit or originated accounts—both with their own address and balance.
Implicit accounts are created from key pairs and used to transfer and store user assets. To spend assets, an implicit account creates a transaction, signed by its private key.
Originated accounts containing some code are called smart contracts. They can receive Tez (XTZ, a native Tezos cryptocurrency) via transactions from other accounts.
Smart contr