
Smart contracts are self-executing contracts with the terms of the agreement written directly into lines of code. They use blockchain technology to facilitate, verify, and enforce the negotiation or execution of a contract.
Smart contracts can automate various processes, such as the transfer of assets or the execution of business logic, without the need for intermediaries like lawyers or banks.
The code is stored on a decentralized network, making it transparent and tamper-proof. This ensures that all parties involved can see the terms of the contract and the outcome of the execution.
In a smart contract, the rules of the contract are written in a programming language and are executed automatically when certain conditions are met.
What is a Smart Contract?
A smart contract is a self-executing program that automates the actions required in a blockchain transaction. It's like a vending machine - when you insert the correct amount of money and push an item's button, the program activates the machine to dispense your chosen item.
Smart contracts permit trusted transactions and agreements to be carried out among disparate, anonymous parties without the need for a central authority, legal system, or external enforcement mechanism.
They're not just limited to blockchain technology, but have evolved beyond underpinning a virtual currency like Bitcoin.
Here's a breakdown of what smart contracts typically consist of:
- State variables (data)
- Functions (what can be done)
- Events (messages in and out)
- Modifiers (special rules for specific users)
Note that some smart contracts may have additional elements depending on what they are designed to do.
What Is a Contract?
A contract is a legally binding agreement between two or more parties. It outlines the terms and conditions of a transaction, and is typically enforced by a central authority or legal system.
Think of a contract like a vending machine – when you insert the correct amount of money and push an item's button, the machine dispenses your chosen item. This is similar to how a smart contract works, but with more complex rules and conditions.
A contract is typically enforced by a trusted third party, such as a lawyer or a judge. However, with smart contracts, the need for a trusted third party is removed. This is because smart contracts are self-executing and can be carried out among disparate, anonymous parties.
Here are some key characteristics of a contract:
- Legally binding agreement between two or more parties
- Outlines terms and conditions of a transaction
- Typically enforced by a central authority or legal system
In the context of smart contracts, the purpose is to further remove the need for a trusted third party to conduct actions between parties that do not trust each other. This is a key benefit of smart contracts, and is one of the reasons why they are becoming increasingly popular.
What You Need to Know
Smart contracts are scripts that automate the actions between two parties. They don't contain legal language, terms, or agreements – only code that executes actions when specified conditions are met.
Nick Szabo, an American computer scientist, conceptualized a virtual currency called "Bit Gold" in 1998, and he defined smart contracts as computerized transaction protocols that execute the terms of a contract.
The term "smart contract" is somewhat of a misnomer – these programs are neither smart nor a contract. They're simply a way to automate transactions and agreements using code.
Here's a quick rundown of what smart contracts are:
- Automate actions between two parties
- Don't contain legal language or agreements
- Are defined as computerized transaction protocols
- Are not actually "smart" or a "contract"
What Are the Key Parts of a Contract?
A smart contract's key parts can be broken down into four main components: state variables, functions, events, and modifiers.
State variables store data that's used to make decisions within the contract. This data can be changed as the contract executes.
Functions are essentially the actions a smart contract can perform, like sending or receiving tokens.
Events are messages that are sent out when specific actions occur within the contract. These events can be used to trigger other contracts or external systems.
Modifiers are special rules that apply to specific users or groups, adding an extra layer of security and control to the contract.
The History of
Smart contracts have been around for a while, and their concept was first proposed by Nick Szabo in 1994. He's an American computer scientist who also conceptualized a virtual currency called "Bit Gold" in 1998, 10 years before Bitcoin was introduced.
Szabo's idea of smart contracts was to create computerized transaction protocols that execute the terms of a contract. He wanted to extend the functionality of electronic transaction methods to the digital realm.
In 1994, Nick Szabo came up with the idea of recording contracts in the form of computer code. This contract would be activated automatically when certain conditions are met.
Szabo worked on this idea for many years and even wrote a book called “Smart Contracts: Building Blocks for Digital Free Markets”. The problem was that back in 1994, blockchain technology didn’t exist.
Here's a brief timeline of the history of smart contracts:
- 1994: Nick Szabo proposes the concept of smart contracts.
- 1998: Szabo conceptualizes a virtual currency called "Bit Gold".
- 2009: Bitcoin introduces the first use of blockchain technology.
- 2015: Ethereum is founded by Vitalik Buterin and introduces the first working smart contracts.
Ethereum and Smart Contracts
Ethereum is the second-largest cryptocurrency with a huge market cap of over $225 billion, making it a well-known name in the crypto world. It's a platform that allows other blockchain applications to be built on it.
The native currency of the Ethereum blockchain is Ether, which works more like fuel than a normal cryptocurrency. You need Ether to run the smart contracts and applications on the Ethereum blockchain, just like you need gasoline or diesel for your car.
Ethereum introduced the concept of smart contracts to the crypto world, and its blockchain works like the Bitcoin blockchain, as a network of computers (or nodes) that run software that confirms transactions on the network.
Ethereum Virtual Machine
The Ethereum Virtual Machine is the backbone of the Ethereum blockchain, responsible for executing smart contracts. It's a decentralized platform that allows for the creation and execution of smart contracts.
The Ethereum Virtual Machine runs smart contracts automatically once the conditions of the agreement are met, eliminating the need for a third party. This is a game-changer for transactions like buying a house, where John can feel safe to pay Mike 300 Ether for the house once the smart contract agreement is in place.
The Ethereum Virtual Machine is decentralized, meaning it's not controlled by one central party. This is made possible by the blockchain, a shared database run by many computers belonging to different people.
Decentralization makes it nearly impossible to hack the blockchain or the smart contracts that run on it, as a hacker would need to hack more than half of the nodes to be successful. This ensures that smart contracts can run safely and automatically without anyone being able to change them.
Ethereum – Its Origins
Ethereum is the second-largest cryptocurrency with a huge market cap of over $225 billion. It was the one that introduced smart contracts to the crypto world.
Ethereum is not just a currency; it's also a platform that allows other blockchain applications to be built on it. The Ethereum blockchain works like the Bitcoin blockchain, a network of computers (or nodes) that run software that confirms transactions on the network.
The native currency of the Ethereum blockchain is Ether, which works more like fuel than a normal cryptocurrency. You need Ether to run the smart contracts and applications on the Ethereum blockchain.
If you happen to have huge amounts of ETH coins, it's recommended to keep them in secure cryptocurrency wallets.
Creating and Managing Smart Contracts
Smart contracts can even create other contracts using a special opcode, allowing for complex agreements to be formed on the Ethereum blockchain.
This feature enables the creation of new contracts that can be executed automatically, without the need for intermediaries. Smart contracts can store code and execute it, creating a new contract with a unique address.
In the simplest terms, a smart contract can be thought of as a self-executing agreement that contains the rules for a specific transaction. Once this agreement has been put into place, it cannot be changed, ensuring the integrity of the contract.
Create
Creating a smart contract is a powerful tool that can be used to create new contracts. Contracts can even create other contracts using a special opcode.
This opcode allows the new contract to be executed and the result stored as code, and the caller/creator receives the address of the new contract on the stack. The process is similar to a normal message call, but with the added benefit of creating a new contract.
In the simplest terms, creating a contract can be seen as a transaction between two parties, where one party creates a new contract and the other party receives the address of the new contract. This process can be repeated to create a chain of contracts, each one building on the previous one.
Delegatecall and Libraries
Delegatecall is a special variant of a message call that lets contracts load code from a different address at runtime. This means the code at the target address is executed in the context of the calling contract.
The calling contract's storage, address, and balance remain unchanged, but the code is taken from the called address. This makes it possible to implement reusable library code that can be applied to a contract's storage.
Delegatecall is useful for implementing complex data structures, and it's a key feature of Solidity that enables the "library" feature. A contract can dynamically load code from a different address, making it a powerful tool for smart contract development.
Message Calls
Message calls are a powerful feature of smart contracts, allowing them to interact with other contracts or non-contract accounts. They're similar to transactions, with a source, target, data payload, Ether, gas, and return data.
A contract can decide how much gas to send with a message call and how much to retain, which is useful for complex operations. This helps prevent gas exhaustion and ensures that exceptions don't propagate too far up the call stack.
Message calls can create further message calls, making them a key component of smart contract functionality. In fact, every transaction consists of a top-level message call.
Calls are fully synchronous, meaning they don't return until the called contract has finished execution. This can be beneficial for certain use cases, but it also means that message calls can be slow for complex operations.
Calls are limited to a depth of 1024, which can cause issues for recursive calls. To avoid this, loops should be preferred over recursive calls whenever possible.
Logic Hacks
Logic hacks are a serious concern in the world of smart contracts. Hackers are targeting the computational logic used in blockchain technology to move data between nodes. This is often seen in cryptocurrency, but it's a threat that can also affect smart contracts.
A poorly coded smart contract can expose an entire enterprise blockchain to threats, making it essential to prioritize security. One way to mitigate this risk is to authenticate users via smart contracts, which can augment or replace conventional identity management procedures.
Delegatecall, a special variant of a message call, can be used to dynamically load code from a different address at runtime. This makes it possible to implement reusable library code, such as complex data structures, in a contract's storage.
However, using delegatecall also means that a contract can execute code from another address, potentially bypassing security measures. This highlights the need for careful coding and testing to prevent logic hacks.
Smart Contract Storage and Data
A contract in the sense of Solidity is a collection of code and data that resides at a specific address on the Ethereum blockchain.
Storage is a key-value store that maps 256-bit words to 256-bit words and is persistent between function calls and transactions. It's not possible to enumerate storage from within a contract, and reading and modifying storage is costly, so you should minimize what you store in persistent storage to what the contract needs to run.
You can store data like derived calculations, caching, and aggregates outside of the contract to reduce costs.
Storage Example
In a Solidity contract, you can specify the compiler version to ensure the contract is not compilable with a new, breaking compiler version.
The next line specifies that the source code is written for Solidity version 0.4.16, or a newer version of the language up to, but not including version 0.9.0.
A contract in Solidity is a collection of code and data that resides at a specific address on the Ethereum blockchain.
The line `uint storedData;` declares a state variable called `storedData` of type `uint` (unsigned integer of 256 bits).
You can think of it as a single slot in a database that you can query and alter by calling functions of the code that manages the database.
To access a member of the current contract, you don't typically add the `this.` prefix, you just access it directly via its name.
This contract allows anyone to store a single number that is accessible by anyone in the world without a feasible way to prevent you from publishing this number.
Anyone could call `set` again with a different value and overwrite your number, but the number is still stored in the history of the blockchain.
Be careful with using Unicode text, as similar looking characters can have different code points and are encoded as a different byte array.
All identifiers (contract names, function names and variable names) are restricted to the ASCII character set.
Calldata, Return Data, Code
Calldata is the data sent to a transaction as part of a smart contract transaction, such as the constructor code of a new contract. This data is always initially stored in calldata in an ABI-encoded form.
The parameters of external functions are stored in calldata, and they're only decoded into the location specified in their declaration when accessed. If a function is declared as memory, the compiler will eagerly decode the parameters into memory at the beginning of the function.
Value types and storage pointers are decoded directly onto the stack. Calldata is a key area to consider when designing smart contracts, as it can impact the performance and efficiency of your code.
Returndata is the way a smart contract can return a value after a call, and external Solidity functions use the return keyword to ABI-encode values into the returndata area. This makes it an essential component of smart contract development.
The code region is where the EVM instructions of a smart contract are stored, and it's the bytes read, interpreted, and executed by the EVM during smart contract execution. Instruction data stored in the code is persistent as part of a contract account state field.
Immutable and constant variables are stored in the code region, and all references to immutables are replaced with the values assigned to them. A similar process is performed for constants, which have their expressions inlined in the places where they are referenced in the smart contract code.
Smart Contract Transactions and Gas
Transactions on a blockchain are essentially modifications to the database, which must be accepted by all participants. Each transaction is cryptographically signed by the sender, ensuring that only authorized individuals can make changes to specific accounts.
If a transaction fails, the entire modification is reverted, and no partial changes are made. This is because transactions are atomic, meaning they are either completely applied or not applied at all.
Transactions are also charged with a certain amount of gas, which must be paid for by the originator. The gas is gradually depleted during execution, and if it's used up, an out-of-gas exception is triggered, reverting all modifications made.
The gas price is set by the originator, and they must pay gas_price*gas upfront to the EVM executor. If some gas is left after execution, it's refunded to the transaction originator.
Transactions
A blockchain is a globally shared, transactional database where everyone can read entries just by participating in the network.
Transactions in a blockchain are always cryptographically signed by the sender, making it straightforward to guard access to specific modifications of the database.
If you want to change something in the database, you have to create a so-called transaction which has to be accepted by all others.
The transactional nature of the database ensures that if the amount is subtracted from one account, it is always added to the other account.
A transaction is either not done at all or completely applied, which means that while your transaction is being applied to the database, no other transaction can alter it.
Smart contracts can execute transactions between parties, like a consumer and a business, where a sale is made, and the customer's payment is initiated along with the business's shipment process.
Decentralized finance (DeFi) smart contracts can reduce the time and cost of settling peer-to-peer transactions using cryptocurrencies like bitcoin and Ethereum's Ether.
Gas
Gas is a crucial component of smart contract transactions, and it's essential to understand how it works. Each transaction is charged with a certain amount of gas that has to be paid for by the originator of the transaction.
The EVM (Ethereum Virtual Machine) executes transactions, gradually depleting gas according to specific rules. If the gas is used up at any point, an out-of-gas exception is triggered, ending execution and reverting all modifications made to the state.
This mechanism incentivizes economical use of EVM execution time, and it also compensates EVM executors for their work. Each block has a maximum amount of gas, which limits the amount of work needed to validate a block.
The gas price is a value set by the originator of the transaction, who has to pay gas_price*gas up front to the EVM executor. If some gas is left after execution, it is refunded to the transaction originator.
EVM executors can choose to include a transaction or not, which prevents transaction senders from abusing the system by setting a low gas price.
Smart Contract Security and Compliance
Smart contracts have the potential to revolutionize the way we conduct transactions, but they also come with their own set of risks and challenges. One of the biggest concerns is security, as poorly coded or inadequately maintained smart contracts can be vulnerable to attacks.
The blockchain technology behind smart contracts is constantly improving, but it's not foolproof. A single mistake in coding can lead to significant losses. In fact, some of the risks include blockchain network attacks, cryptojacking, and human incompetence.
To mitigate these risks, companies need to establish a governance model to stay ahead of security challenges. This will help ensure that smart contracts are properly maintained and updated to prevent potential threats. By taking proactive steps, organizations can minimize the risk of losses due to internal and external threats.
Deactivate and Self-Destruct
The self-destruct operation in smart contracts is a complex topic. The only way to remove code from the blockchain is when a contract at that address performs the selfdestruct operation.
Removing a contract sounds like a good idea, but it's potentially dangerous. If someone sends Ether to a removed contract, the Ether is forever lost.
From EVM version Cancun onwards, selfdestruct will only send all Ether in the account to the given recipient and not destroy the contract. However, when selfdestruct is called in the same transaction that creates the contract calling it, the older behavior of destroying the contract is preserved.
The new behavior is a result of a network-wide change that affects all contracts present on the Ethereum mainnet and testnets. This change is dependent on the EVM version of the chain on which the contract is deployed.
Note that the selfdestruct opcode has been deprecated in Solidity version 0.8.18. Any use of selfdestruct in newly deployed contracts is strongly discouraged.
Even if a contract is removed by selfdestruct, it's still part of the history of the blockchain and probably retained by most Ethereum nodes. Using selfdestruct is not the same as deleting data from a hard disk.
If you want to deactivate your contracts, you should instead disable them by changing some internal state which causes all functions to revert. This makes it impossible to use the contract, as it returns Ether immediately.
Security
Smart contracts can improve security by authenticating users via smart contracts, which could augment or replace conventional identity management procedures. This is especially important in a digitally dependent world where threats like data breaches are persistent.
The blockchain technology behind smart contracts is constantly improving as more companies add them to their ecosystems. However, there are security risks if the smart contracts are poorly coded or inadequately maintained.
Establishing a governance model is an essential step to help organizations stay ahead of these challenges. This is crucial for preventing security risks associated with poorly coded or inadequately maintained smart contracts.
Smart contracts can be hacked if more than half of the nodes in the blockchain are compromised. This is because the blockchain is a shared database run by many computers belonging to different people.
Here are some key security risks associated with smart contracts:
To maintain the integrity of smart contracts, it's essential to prevent errors caused by faulty data input. This can be achieved by ensuring that the incoming data is accurate and valid.
Smart contracts are practically immutable, meaning that any changes require the creation of a new contract. This can be a challenge when implementing smart contracts, especially for companies that are new to this technology.
Compliance
Compliance is a crucial aspect of smart contract security. Government regulation of blockchain technology is minimal, but more companies are adopting blockchain projects, which means more scrutiny.
Creating corporate compliance policies can help mitigate losses due to internal and external threats. Some of the risks include blockchain network attacks and human incompetence.
Blockchain network attacks can compromise the integrity of smart contracts, putting sensitive information at risk. Cryptojacking is another risk, where hackers exploit blockchain networks for cryptocurrency mining.
Human incompetence can also lead to security breaches. This can happen when employees or developers make mistakes while working with smart contracts.
Frequently Asked Questions
What are the four major parts of a smart contract?
A smart contract consists of four key components: participants, state, functions, and rules, which work together to enable secure and automated interactions. Understanding these components is essential to creating and utilizing effective smart contracts
Are crypto smart contracts legal?
Smart contracts are not automatically legal, but can be legally binding if they meet all the necessary contract requirements and comply with local laws
What are the top 10 smart contracts?
The top 10 smart contract platforms in 2024 include Ethereum, Binance Smart Chain, TRON, Arbitrum, Cardano, Solana, Polygon, Algorand, Avalanche, and Tezos. These platforms offer a range of features and benefits for building and deploying smart contracts.
Sources
- https://docs.soliditylang.org/en/latest/introduction-to-smart-contracts.html
- https://www.investopedia.com/terms/s/smart-contracts.asp
- https://www.techtarget.com/searchcio/feature/Examples-of-smart-contracts-on-blockchain
- https://www.bitdegree.org/crypto/tutorials/what-is-a-smart-contract
- https://www.geeksforgeeks.org/smart-contracts-in-blockchain/
Featured Images: pexels.com