ETHEREUM
Ethereum Virtual Machine
-
The Ethereum Virtual Machine is the runtime environment for smart contracts in Ethereum. It is not only sandboxed but actually completely isolated, which means that code running inside the EVM has no access to network, filesystem or other processes. Smart contracts even have limited access to other smart contracts.
-
Smart contracts are self-executing programs that automatically enforce the terms of an agreement or perform certain actions when predefined conditions are met. The EVM is specifically designed to execute these smart contracts, which are written in high-level programming languages like Solidity. Developers compile their code into bytecode, which is the low-level language that the EVM understands.
-
When a smart contract is deployed on the Ethereum blockchain, it becomes immutable, meaning its code and behavior cannot be changed. The EVM enforces the logic and rules encoded in the smart contract, and its execution is publicly auditable on the blockchain.
Turing Completeness
- The EVM’s Turing completeness means that it can perform any computation that can be expressed algorithmically. The EVM’s Turing completeness means that it can perform any computation that can be expressed algorithmically. Turing completeness, however, comes with challenges. The potential for infinite loops is one such challenge. However, this is mitigated by the gas system.
Gas
-
To ensure efficient and fair resource allocation, the EVM employs a gas system. Gas represents the cost of computational resources required to execute a transaction or smart contract. Each EVM operation consumes a specific amount of gas, and users must pay for gas when submitting transactions. The gas price is determined by the user, and miners often prioritize transactions with higher gas prices.
-
The gas system serves two primary purposes: to prevent spam and abuse of the network by making resource consumption costly, and to incentivize miners and nodes to process transactions by offering them transaction fees in gas.
-
Upon creation, each transaction is charged with a certain amount of gas that has to be paid for by the originator of the transaction. Gas fees are an integral part of the Ethereum blockchain. They are transaction costs that users pay to execute operations on the network. These operations can range from simple transactions, like sending Ether (ETH) from one address to another, to more complex interactions with smart contracts. The concept of gas was introduced as a form of remuneration for validators who maintain and secure the Ethereum blockchain. Validators, who verify and process transactions on the network, receive these fees.
Isolation and Security
- The EVM enforces code execution in a secure and isolated environment. Each smart contract runs in its own “sandbox,” preventing one contract from interfering with the state or behavior of others. This isolation enhances security by containing potential vulnerabilities within individual contracts. Even if one contract has a bug or is compromised, it does not affect the overall integrity of the Ethereum network or other contracts.
Deterministic Execution
- The EVM ensures deterministic execution, which means that given the same input and the same initial state, any node in the Ethereum network will produce the exact same result when executing a transaction or smart contract. Deterministic execution is crucial for achieving consensus across all nodes. It guarantees that all participants on the network will agree on the blockchain’s state, enhancing trust and reliability.
Immutable Code
- Smart contracts deployed on the Ethereum blockchain are immutable. Once a contract is deployed, its code cannot be altered or updated. Immutability is a fundamental property of blockchain-based smart contracts because it ensures that the contract’s behavior remains consistent over time. Users and DApps can trust that the contract’s rules will not change unexpectedly.
Stack-Based Execution
- The EVM uses a stack-based execution model. This means that data and operands are pushed onto a stack, and operations are performed by popping values from the stack. Stack-based execution is efficient and well-suited for the EVM’s resource-constrained environment, allowing for compact and predictable code execution.
Solidity
-
Object-Oriented: Solidity supports object-oriented programming (OOP) principles, including inheritance, encapsulation, and polymorphism. It allows developers to create reusable and modular code structures using contracts and libraries.
-
Static Typing: Solidity employs static typing, which means variables and function parameters must have explicitly defined data types.
-
Contract-oriented Language: Solidity revolves around the concept of contracts, which are the building blocks of smart contracts. Contracts define the state and behavior of entities on the Ethereum blockchain, encapsulating data and functions.
-
Event-driven Programming: Solidity includes an event system that facilitates communication and logging of significant contract events. Events can be emitted during contract execution and provide a way for external applications to react to state changes. Applications can subscribe and listen to these events through the RPC interface of an Ethereum client. Ethereum clients such as web applications can listen for these events emitted on the blockchain without much cost. Once emitted, the event is recorded in Ethereum Logs and Events. These logs can be accessed and analyzed by anyone with access to the blockchain. The logs are stored as part of the blockchain's state, ensuring their permanence. Ethereum Logs and Events provide an open ledger of all activities on the network.
-
Library Support: Solidity allows the creation and usage of libraries
-
Security Considerations: Solidity provides certain features to enhance security, such as visibility modifiers to control access to functions and state variables. Developers can also implement error handling and exception mechanisms to handle unexpected scenarios.
Storage
1. Memory
- This is used to hold temporary values and only exists within the scope of the function call. They are wiped after execution and their lifetime limited while executing this function.
2.Calldata
- Calldata is the input coming from the call of a function. Like memory, this is used to hold temporary values and erased between function calls. However, it is immutable within function call and is slightly cheaper in gas cost as it skipped copying the values into memory. It is read directly from call data.
pragma solidity 0.8.21;
contract MyContract {
function foo(string calldata someInput) external {
// error - cannot assign to calldata variable
someInput = "hello";
}
function foo2(string memory someInput) external pure {
// ok
someInput = "hello";
}
}
3. Persistent storage
-
Each account has a data area called storage, which is persistent between function calls and transactions. Storage is a key-value store that maps 256-bit words to 256-bit words. It is not possible to enumerate storage from within a contract, it is comparatively costly to read, and even more to initialise and modify storage. Because of this cost, we should minimize what we store in persistent storage to what the contract needs to run. Store data like derived calculations, caching, and aggregates outside of the contract. A contract can neither read nor write to any storage apart from its own.
-
Each smart contract maintains its own storage. This persistent storage is basically a key-value mapping with 2 ²⁵⁶ keys mapped to each value of 32 bytes. Smart contract can read or write from any particular slot. These data will be permanently stored on blockchain and retrievable on subsequent operation.
-
State variables are arranged in a compact continuous manner and if possible (within 32 bytes value), they can occupy the same storage slot. For example, if there are continuous bool variables (bool variable only occupies 1 byte), they could all occupy the same slot.
// one slot can slot 32 bytes of value and solidity will try to pack
Contract HelloWorld {
uint256 apple; // in slot 0
address pear; // in slot 1
mapping(address => uint256) banana; // in slot 2
bool xx1; // in slot 3 - 1 byte
bool xx2; // in slot 3 - 1 byte
bool xx3; // in slot 3 - 1 byte
uint8 xx4; // in slot 3 - 1 byte
bytes16 xx5; // in slot 3 - 16 bytes
uint128 xx6; // in slot 4
}
SOLANA
It's a high performance network that is utilized for a range of use cases, including finance, NFTs, payments, and gaming. Solana operates as a single global state machine, and is open, interoperable and decentralized.
Virtual Machine
-
When processing a transaction, the VM converts the smart contract code into a format that can be carried out by the validators' hardware. On Solana, the main languages for writing smart contract are Rust, C, and C++, which are compiled into BPF bytecode by the Solana Virtual Machine (SVM), enabling transactions to be executed efficiently by the nodes of the network (validators).
-
The nodes of the Solana network, known as validators, each run their own isolated environment of the Solana Virtual Machine (SVM) to maintain consensus across the blockchain. When a smart contract is deployed (modifying the network's state), it communicates the required state changes to the runtime. The Solana runtime then forwards these state changes to the SVM instances operating within each validator's system, where all validator nodes receive a copy and translate it, updating the blockchain.
-
Solana can process tens of thousands of contracts in parallel, using as many cores as are available to the Validator. This not only allows for non-overlapping transactions to execute concurrently, but also for transactions that are only reading the same state to execute concurrently as well.
-
The key component of SVM is Sealevel. This engine enables “horizontal” scaling within the Solana execution environment by allowing multiple smart contracts to run simultaneously without impacting each other's performance, a concept known as parallel processing. This is possible due to Solana smart contracts describing which data (state) will be read or written while executing in the runtime. This lets transactions without conflicts to run at the same time, as well as those just reading the same information. Sealevel makes it thus possible for the SVM to handle tens of thousands of transactions simultaneously, as opposed to processing them one by one like the Ethereum Virtual Machine (EVM).
SVM vs EVM (Ethereum Virtual Machine)
-
While both EVM and SVM perform similar functions, the Solana VM is much more efficient and faster. On EVM, when a smart contract transfers a dollar from a user’s balance, this transaction is stored within the specific contract's storage. This design creates potential issues if the Ethereum Virtual Machine attempts to process multiple transactions in parallel. For example, two different smart contracts might simultaneously attempt to spend the user’s balance, or another contract might read this same user’s balance while it is in the process of being updated, leading to inconsistencies and conflicts.
-
In contrast, the Solana account model separates data, such as user’s balance, for better organization and efficiency. Transactions on Solana also require explicit specification of the data they will read and modify before execution in the SVM. This allows programs that do not interact with the same data to run concurrently, which helps to alleviate congestion and reduce high fees.
-
On the other hand, Sealevel optimizes the performance of the Solana runtime by enabling efficient use of the available hardware resources. SVM is a multi-threaded runtime environment, designed to process multiple transactions in parallel by using all the cores available of the validator machine. This makes Solana able to scale more effectively as the hardware of its validators improves over time. The Solana Virtual Machine can also manage transaction fees in a better way thanks to its architecture. This has led to the development of localized fee markets, which enable fees to be assigned per smart contract. In contrast, EVM chains rely on global fee markets, meaning that an NFT mint can affect a swap or DeFi transaction, even though the transactions are unrelated.
Localized fee markets
Solana has a system of "local" fee markets, where demand for blockspace from a particular hotspot of activity like a surge of swap activity can lead to high fees just for that activity without necessarily affecting fees for unrelated transactions.
For example, let’s say there is a new AMM dex product launch on Solana. Many people want to trade tokens on it, so they send transactions to the program managing the dex. This creates a high demand for blockspace from that program.
However, Solana has per-block (48 million) and per-account (12 million) limits on compute units (CUs), which measure the amount of computation required by each transaction. These limits prevent any single program from using up all the blockspace.
So, in above example, the swap transactions quickly reach the CU limit for the accounts associated with that dex. This means that they have to pay higher fees to compete for the limited blockspace available for that program.
However, regular transactions like sending SOL or trading tokens on other DEXs aren't directly competing with the dex. So their fees don't necessarily rise (unless there is high global demand already filling up blocks). They can still pay lower fees as long as there is enough blockspace left for them.
Details of local fee markets:
- Per-block limit of ~48 million compute units (CU). This dynamically adjusts based on network conditions.
- Per-account, per-block limit of 12 million CU. This soft cap can be exceeded by paying higher fees.
- Compute unit cost defined per-program based on transaction complexity. Simple transfers have low CU cost, complex DeFi trades are high.
- Each transaction also has a priority fee that affects ordering. This fee matters more when overall blockspace demand is high.
Details of priority fees:
Many simple transactions like token transfers have low compute unit (CU) costs on Solana. This allows a large number of them to fit within the per-block limit of 48 million CU. For example, a basic SOL transfer may only cost a few thousand CU. Conservative estimates say around 10,000 of these simple transfers could fit in a single block.
However, each transaction on Solana also specifies a priority fee. This fee is proportional to the transaction's CU cost. When overall demand for blockspace is low, the priority fee does not matter much. Most transactions can fit in the block. But when demand is high and blockspace becomes scarce, the priority fee becomes critical. Transactions with higher priority fees per CU get prioritized by the network for inclusion in blocks. So when blocks are near full capacity, users need to specify higher priority fees to incentivize validators to select their transactions over others.
In a congested period, a token transfer with a low priority fee could get deprioritized and wait in the mempool, while trades with high fees jump the queue. This priority fee mechanism allows Solana to maintain consistency in block production even when there is more demand than available blockspace. Transactions that pay the higher priority fees essentially outbid lower-fee transactions for inclusion in scarce blockspace.
Smart contracts
-
In EVM-based chains, contract code/logic and state are merged into a single contract for on-chain deployment. Whereas a Solana smart contract (or program) is read-only or stateless and consists solely of program logic.
-
External accounts can use smart contracts after their implementation. These accounts communicate with the programs to store data related to program interaction. In this way, the logical separation of state (accounts) and contract logic (programs) occurs. Solana makes a clear separation between a program’s code and data it is working on, assigning them to different accounts. Unlike other blockchains, smart contracts can be upgraded after they are deployed to the network. Can be upgraded by the account that is marked as the "Upgrade Authority", which is usually the Solana account/address that deployed the smart contract to begin with.
Storage
-
Rent is a mechanism on the Solana blockchain that ensures efficient usage of the blockchain's resources. It requires accounts to maintain a minimum balance proportional to the amount of data they store on the network. Accounts that fail to maintain this minimum balance will be removed from the ledger to free up storage. You can think of it as similar to a bank account. For many accounts, the bank will charge you a fee if you do not maintain a minimum balance. If your balance falls below the required minimum, the bank may charge you a fee or close your account. Solana rent is like the minimum balance requirement, ensuring that accounts on the network have enough lamports (a lamport is one one-billionth of a SOL) to cover network storage costs. If an account's balance falls below the rent-exempt threshold, the account may be removed from the network. Rent is refundable. If an account is closed (removed from the network), the data is deleted from the chain and the rent is refunded to the account owner (or other defined account).
-
Accounts are held in validator memory and pay rent to stay there. Each validator periodically scans all accounts and collects rent. Any account that drops to zero lamports is purged. Accounts can also be marked rent-exempt if they contain a sufficient number of lamports.
The Solana protocol charges rent to account owners to:
- Encourage efficient use of storage space by removing accounts that are not actively used.
- Compensate validators for the resources they provide in storing account data.
Because rent is necessary to create new accounts, we must know the rent-exempt threshold before creating an account. This is so we can seed the account with enough lamports to cover the minimum.
CARDANO
Small contracts
-
Cardano smart contracts are written in Plutus, a Haskell-based programming language specifically designed for the Cardano blockchain.
-
On the Cardano blockchain, the compiled code of smart contracts is stored on, and distributed across, the decentralised network. It is not possible to modify the rules of an existing smart contract, nor is it possible to decompile the stored smart contract code from its compiled state into the original source code.
-
Cardano is extremely energy-efficient and affordable to use. While legacy networks like Ethereum battle with high gas fees and slow transaction speeds, Cardano’s impressive scalability means it can support thousands of smart contracts without debilitating gas spikes and dropped transactions.
-
Smart contracts are more or less just a piece of code that we write to validate the movement of UTXOs locked in your contract's address. You will lock UTXOs at the address of your script and then the UTXOs can only ever be spent/moved if your script allows the transaction spending it to do so.
Virtual machine
- Bitcoin, Cardano, and other blockchains that use a UTXO-based ledger model are different. Instead of thinking of the blockchain as one big box (as in the previous case), it is better to think of it as a collection, or a set, of many little boxes (a.k.a UTXOs). The whole UTXO set is replicated and constantly changing like any other blockchain, but there are no interdependencies between the UTXOs themselves. Instead, each UTXO contains just enough information it needs to only ever be spent exactly how the creator of the UTXO intended it. There is no notion of a shared "global state", and hence no need for a VM.
AVALANCHE
Avalanche network uses a multi-chain architecture. They use three distinct chains for different purposes:
- Exchange Chain: X-Chain for creating and exchanging assets
- Platform Chain: P-Chain for managing the network and validators
- Contract Chain: C-Chain for smart contracts and working with Ethereum
-
The C-Chain is an implementation of the Ethereum Virtual Machine (EVM). The C-Chain’s API supports the deployment and execution of smart contracts written in Solidity.
-
Avalanche is designed to be scalable and secure from the start. It processes many transactions in parallel. The network claims to have 4,500 transactions per second (TPS). The block time for AVAX is around 3 seconds.
-
Avalanche lets its users use Solidity and run their smart contracts on the same system as Ethereum. It's possible to use other languages like Rust, Go, TypeScript, and C.
-
Avalanche has a simple and fixed system for gas fees. It charges a certain amount of AVAX (its own currency), depending on what kind of transaction is done.
For example, if one wants to send some AVAX to someone else, pays an average fee of $0.08. Creating a new blockchain or a new token, it costs 0.1 AVAX mint fees. The fees don’t change much, so we always know how much we must pay.
One of Avalanche VM's most significant advantages is its speed. The high performance and capacity of Avalanche VM It is designed to handle a large number of transactions per second (TPS).
Pros of Avalanche:
- Fast and scalable blockchain networks
- Cross-chain compatible with other networks, including Ethereum
- Developers can launch their own custom blockchain
- Eco-friendly and energy-efficient with its PoS consensus algorithm
- The high transaction throughput of 4,500 TPS
- Low gas fee
Cons of Avalanche
- It is not fully decentralized due to less number of network validators
- It is not tested in high network congestion environments like Ethereum
- Multi-chain architecture can be complex to implement