Skip to main content

4 posts tagged with "ethereum"

View All Tags

Introduction

When interacting on Ethereum, one is often troubled by various contract addresses that seem to have no pattern, but in reality, these addresses are a predetermined matter before the smart contract is created.

There are two types of accounts on Ethereum, one is the External Owned Account (EOA), and the other is the Contract Account (CA). External accounts are determined by private keys, so on different Ethereum-equivalent chains, the same private key can control the same address. For CAs, however, there is a specific rule for the generation of their addresses. In production practice, when deploying contracts across multiple chains, there is always a desire for them to have the same address. This article will summarize the method of contract address generation on Ethereum and some existing tools, and explain possible application scenarios.

CREATE: The Foundation of Contract Creation

CREATE is an Ethereum opcode used for contract creation. It is part of the original Ethereum implementation and is used to deploy a new smart contract on the blockchain. By default, when we deploy a contract, the address we get is related to our current address and the nonce value of the current transaction. Numerically, it is equal to:

bytes20(sha3(rlp.encode(address,nonce)))

Deploying a Contract through EOA

Deploying a contract through an External Owned Account (EOA) is a very common practice. First, calculate the contract address to be generated using the formula mentioned above, use this as the to parameter of the transaction, and then use the compiled bytecode as the data parameter of the transaction. Sign and broadcast it, and that becomes a transaction for deploying a contract.

{
"to": <calculatedContractAddress>,
"data": <bytecode>,
"gasPrice": ...,
"gasLimit": ...
}

Deploying Contracts Through Other Contracts

Deploying contracts through other contracts is often seen in a factory pattern. It only requires 'new'ing an imported contract within the contract code, and the creation is automatically completed when this method is called.

After EIP-161, the nonce for smart contracts starts from 1 and is incremented only when a contract is created.

function deployContract() external {
Contract addr = new Contract();
}

Alternatively, the CREATE opcode can be directly called through inline assembly to create a contract:

function deployContract() external {
bytes memory bytecode = type(Contract).creationCode;
address addr;
assembly {
addr := create(0, add(bytecode, 32), mload(bytecode))
}
}

A drawback of the above two methods is that the factory contract itself can be very large, as it contains all the bytecode of the child contracts. Deploying the factory contract can consume a lot of gas. A better alternative might be using ERC1167.

CREATE2: Predictable Addresses

CREATE2 was introduced in EIP-1014 to overcome some limitations of CREATE. The method of using the address + nonce is indeed useful, nearly eliminating the possibility of duplication. However, it introduces a problem: it's difficult to maintain consistent contract addresses across multiple chains because keeping the nonce consistent is challenging unless a dedicated address is used for deployment. Hence, CREATE2 was introduced, an EVM opcode that generates a contract address independent of the sender's nonce.

The contract address obtained with CREATE2 can be expressed as:

bytes20(sha3(rlp.encode(address,bytecode,salt)))

Since CREATE2 is an opcode, it can only be implemented through the method of deploying contracts through other contracts. A simple example is:

function deployContractByCreate2() external {
bytes32 salt = bytes32(uint256(1));
Contract addr = new Contract{ salt: salt }();
}

Alternatively, the CREATE2 opcode can be directly invoked using assembly:

function deployContractByCreate2Assembly() external {
address addr;
bytes memory bytecode = type(Contract).creationCode;
bytes32 salt = bytes32(uint256(1));
assembly {
addr := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
}

The above two examples require the bytecode of the child contract to be within the factory, which greatly limits the variety of deployable contracts. Therefore, it's worth considering passing the bytecode of the contract to be deployed as a parameter, creating a relatively universal create2factory.

Public CREATE2 Factory

This type of universal create2 factory can easily become a common infrastructure. As long as this factory has the same address on different chains, using the same bytecode and salt will ensure the deployment of contracts with the same address on different chains. A classic example is the Deterministic Deployment Proxy, which uses pure Yul to write an efficient deployer contract.

object "Proxy" {
// deployment code
code {
let size := datasize("runtime")
datacopy(0, dataoffset("runtime"), size)
return(0, size)
}
object "runtime" {
// deployed code
code {
calldatacopy(0, 32, sub(calldatasize(), 32))
let result := create2(callvalue(), 0, sub(calldatasize(), 32), calldataload(0))
if iszero(result) { revert(0, 0) }
mstore(0, result)
return(12, 20)
}
}
}

In practical application, a key issue arises: ensuring that the factory's address is the same on different chains. What if there is no factory address deployed on a certain chain?

Since the Deterministic Deployment Proxy predates EIP-155, it's possible to use a unified, keyless transaction to send the exact same transaction on different chains, thereby deploying the same factory address.

Nowadays, it is more common for a centralized individual or organization to control a specific private key, thus deploying the same factory on different chains, such as the Safe’s safe-singleton-factory.

Deploying Contracts with Access Control

Often, the contracts we deploy include some form of access control. OpenZeppelin's Ownable, by default, sets the msg.sender as the owner (which will be optimized in version 5.0). Directly inheriting OpenZeppelin's Ownable contract would assign the owner to the factory. Therefore, it is necessary to pass the owner as a constructor parameter, for example:

Default OZ Ownable

/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/

constructor() {
_transferOwnership(_msgSender());
}

Adding owner to the constructor

/**
* @dev Initializes the contract with a manual owner.
*/
constructor(address owner_) {
_transferOwnership(owner_);
}

Integration with Hardhat-deploy

hardhat-deploy directly supports deterministic deployment. You can configure the specific chain's factory address in hardhat.config.ts, possibly using an address from the safe-singleton-factory. Then, specify the deterministicDeployment's salt in xxx_deploy_xxx.ts.

await deploy('MyContract', {
from: deployer,
log: true,
deterministicDeployment: keccak256(formatBytes32String('A salt')),
})

Sample Usage - Counterfactual Instantiation in State Channels

A gaming platform plans to use state channels for fast, off-chain game interactions. It requires the ability to predict the address of a game contract before it is actually deployed on-chain.

contract GameFactory {
function deployGame(bytes32 salt, bytes memory gameContractCode) public {
address predictedAddress = address(uint160(uint256(keccak256(abi.encodePacked(
byte(0xff),
address(this),
salt,
keccak256(gameContractCode)
)))));

// Use the predictedAddress for off-chain interactions

// Deploy the contract when needed
address newGame = address(new Contract{salt: salt}(gameContractCode));
require(newGame == predictedAddress, "Address mismatch");
}
}

Here, GameFactory uses CREATE2 to deploy a game contract with a predictable address. The address is calculated off-chain and used in the state channel. When needed, the contract is deployed on-chain at the predetermined address.

CREATE2 & Layer-2 Solutions

CREATE2 has been hailed as the foundation of Layer-2 solutions due to its predictable and deterministic nature in contract address generation. This predictability is vital for several reasons:

  1. Counterfactual Instantiation: Layer-2 solutions often use state channels, where transactions are conducted off-chain and only the final state is recorded on-chain. CREATE2 enables counterfactual instantiation, allowing the interaction with contracts that haven't yet been deployed on-chain. This capability reduces initial deployment costs, as contracts are only deployed when absolutely necessary.

  2. State Channel Optimization: In state channels, participants need assurance that a certain contract will exist with a specific address, even if it's not yet deployed. CREATE2 provides this assurance, as the address can be precomputed and agreed upon by all parties.

  3. Upgradeable Contracts: Layer-2 solutions require flexibility, including the ability to upgrade contracts without changing their address. CREATE2's deterministic address generation means that even if a contract is destroyed and redeployed, its address remains the same, preserving the integrity and continuity of the contract's role within the Layer-2 framework.

CREATE3: Expanding the Horizon

CREATE3 is a new concept proposed in EIP-3171, mainly considering that bytecode, as a variable influencing the address, is too large and costly to compute directly on the blockchain. CREATE3 aims to ensure that the address of the contract created is solely related to the sender and salt. However, since this goal can be achieved through the combination of CREATE and CREATE2, it is not an essential opcode, and thus the EIP was ultimately not adopted.

Sequence's implementation of CREATE3 is likely one of the earliest. It requires two steps:

  1. Inside the factory, use the CREATE2 method to create a proxy contract whose sole function is to deploy another contract:
address proxy;
assembly {
proxy := create2(0, add(creationCode, 32), mload(creationCode), _salt)
}
  1. Call the newly deployed proxy contract to deploy the actual contract we want:
(bool success,) = proxy.call(_creationCode);

The proxy is deployed via CREATE2, so its address is only related to the factory's address and the salt. The actual contract is deployed via CREATE, so its address is only related to the proxy's address and the proxy's nonce. Since the proxy is newly deployed, its nonce is definitively 1. Therefore, the address of the contract we want to deploy is only related to the factory's address and the salt we input. This can be expressed as:

bytes20(sha3(rlp.encode(bytes20(sha3(rlp.encode(address,proxy_bytecode,salt))),1)))

Steps

  1. Assuming a CREATE3 Factory already exists on multiple chains and the addresses on each chain are the same.
  2. Developers send a deployment transaction to the CREATE3 Factory, which includes a salt and the init_code/creationCode/bytecode of the new contract.
  3. In the CREATE3 Factory, a contract with fixed_init_code (bytecode of Proxy contract) is first deployed using CREATE2, referred to as the CREATE2 Proxy. Since the sender_address (CREATE3 Factory), salt, and fixed_init_code are the same, the addresses of the CREATE2 Proxy on each chain are also the same.
  4. The CREATE3 Factory then calls the newly deployed CREATE2 Proxy, whose deployed_code contains the CREATE opcode to deploy the new contract. Since the sender_address (CREATE2 Proxy) and sender_nonce (starting from 1) are the same, the addresses of the new contract on each chain are also the same. It is important to note that this CREATE2 Proxy is only used for this deployment transaction, meaning a different salt will be used next time to deploy another CREATE2 Proxy for other new contracts.

The above steps are illustrated in the following diagram. Since the parameters obtained by CREATE and CREATE2 are already determined before the deployment transaction is sent, the address of the new contract can also be predetermined.

From the above diagram, the calculation of the new contract address is as follows. Therefore, from the user's perspective, the factors that affect the new address are the salt provided by themselves and the create3_factory_address they interact with.

create2_proxy_address = keccak256(0xff + create3_factory_address + salt + keccak256(fixed_init_code))[12:]

new_address = keccak256(rlp([create2_proxy_address, 1]))[12:]

fixed_init_code

An interesting part is the fixed_init_code of the CREATE2 Proxy set in Step 3:

67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3

//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 0 size //
// 0x37 | 0x37 | CALLDATACOPY | //
// 0x36 | 0x36 | CALLDATASIZE | size //
// 0x3d | 0x3d | RETURNDATASIZE | 0 size //
// 0x34 | 0x34 | CALLVALUE | value 0 size //
// 0xf0 | 0xf0 | CREATE | newContract //
//--------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//--------------------------------------------------------------------------------//
// 0x67 | 0x67XXXXXXXXXXXXXXXX | PUSH8 bytecode | bytecode //
// 0x3d | 0x3d | RETURNDATASIZE | 0 bytecode //
// 0x52 | 0x52 | MSTORE | //
// 0x60 | 0x6008 | PUSH1 08 | 8 //
// 0x60 | 0x6018 | PUSH1 18 | 24 8 //
// 0xf3 | 0xf3 | RETURN | //
//--------------------------------------------------------------------------------//

In the above code snippet, the 8 italic opcodes from 36 to f0 represent the deployed_code stored on the chain, which is the content of the CREATE2 Proxy contract. It's evident that the operation from 36 to f0 simply copies the new contract's init_code from calldata to memory and then calls CREATE with msg.value to deploy the new contract.

The sequence from 67 to f3 in the code snippet is used to place the deployed_code in the return data region to complete the deployment of the CREATE2 Proxy.

  • Tip 1: Using RETURNDATASIZE (0x3d) to push 0 onto the stack is slightly more gas-efficient than PUSH1 0.
  • Tip 2: CREATE (0xf0) puts the new contract's address back on the stack, but the next step does not return this new address. Instead, the new address is calculated in the CREATE3 Factory and checked by verifying that code.length > 0. Returning the new address would increase the deployed_code from 8 to 15 opcodes, thus decreasing the size of the CREATE2 Proxy and lowering the gas cost for deploying the contract. The method for calculating the new address starts by determining the CREATE2 Proxy's address, then performing RLP encoding with nonce (1), as shown in the code snippet below:
address proxy = keccak256(
abi.encodePacked(
// Prefix:
bytes1(0xFF),
// Creator:
creator,
// Salt:
salt,
// Bytecode hash:
PROXY_BYTECODE_HASH
)
).fromLast20Bytes();

return
keccak256(
abi.encodePacked(
// 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01)
// 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)
hex"d6_94",
proxy,
hex"01" // Nonce of the proxy contract (1)
)
).fromLast20Bytes();

CREATE3 Factory

In step 1, there's an assumption that a CREATE3 Factory with the same address already exists on each chain.

One approach is to use a new EOA and acquire native tokens on each chain to pay for gas. Then, the first transaction (nonce = 0) is sent on each chain to deploy the CREATE3 Factory, ensuring that the CREATE3 Factory addresses are the same across all chains.

Another method is to use someone else's already deployed CREATE3 Factory on each chain, such as the one found at https://github.com/ZeframLou/create3-factory. SKYBITDEV3 also listed some CREATE3 factory choices you can refer to. some This factory uses msg.sender and salt for an additional keccak256 calculation, ensuring that different users won't generate the same new addresses. The downside is that if you want to deploy on a new chain without a CREATE3 Factory, you'll have to rely on the original deployer.

If the new contract deployed uses msg.sender in its constructor, be aware that msg.sender will be the CREATE2 Proxy! A common example is OpenZeppelin's Ownable. Necessary modifications must be made, such as executing transferOwnership at the end of the constructor.

Conclusion

CREATE, CREATE2, and CREATE3 each serve distinct purposes in the Solidity ecosystem. While CREATE offers a basic, reliable method for contract creation, CREATE2 adds a layer of predictability and flexibility, essential for advanced development patterns such as upgradeable contracts and layer 2 solutions. CREATE3, though not an official opcode, pushes the boundaries further, enabling sophisticated contract deployment strategies to ensure that the address of the contract created is solely related to the sender and salt.

Resource

blockchainethereumevm9 min read

Ethereum Improvement Proposals (EIPs) define standards for the Ethereum blockchain, including core protocol specifications, client APIs, and contract standards. EIPs can also propose changes to the Ethereum ecosystem that are not directly related to the technical specifications.

EIP-1: EIP Purpose and Guidelines

EIP Structure

Preamble

The preamble includes the EIP number, title, author, and contributors. It also includes a summary of the proposal and the motivation behind it.

https://eips.ethereum.org/EIPS/eip-1#eip-header-preamble

EIP Preamble

Abstract

A technical description of the proposal, including the problem it solves and the benefits it provides. It should be clear and concise.

Motivation

A detailed explanation of the problem the proposal solves and why it is important to solve it. It should provide context and background information. This section should explain why the existing protocol specification is inadequate to address the problem that the EIP solves. If the motivation is evident, this section may be omitted.

Specification

The technical specification should describe the syntax and semantics of any new feature. It should include any necessary changes to the Ethereum protocol, API, or contract standards. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Ethereum platforms (besu, erigon, ethereumjs, go-ethereum, nethermind, or others).

Rationale

The rationale explains the reasoning behind the proposal and discusses the benefits and drawbacks of the proposed changes. It should also address any potential issues and provide reasoning for the proposed changes. Additionally, the rationale should discuss any alternate designs that were considered and related work, such as how the feature is supported in other languages. This section should also address any important objections or concerns raised during discussion around the EIP.

For example, we can use the following format to explain design choices,

ERC-6220

EIP Ratinoale

Backwards Compatibility

A discussion of how the proposal affects backwards compatibility. It should explain any changes that may break existing contracts or applications.

Test Cases

Examples of how the proposal can be implemented and tested. It should include test scenarios and expected outcomes.

Reference Implementation

An optional section that contains a reference or example implementation that people can use to assist in understanding or implementing this specification. This section should include any code or links to code repositories that implement the proposal. It should also provide clear instructions on how to use the implementation and any dependencies that it has. If there are multiple reference implementations, they should be listed separately.

Security Considerations

A discussion of any security risks associated with the proposal and how they can be mitigated.

All EIPs must be in the public domain. The copyright waiver MUST link to the license file and use the following wording: Copyright and related rights waived via CC0.

EIPs are an important part of the Ethereum ecosystem and provide a standardized way to propose, discuss, and implement changes. By following this structure, EIP authors can ensure their proposals are clear, concise, and well-documented.


EIP Process

The EIP process is designed to provide a standardized way to propose, discuss, and implement changes to the Ethereum ecosystem.

Idea - An idea that is pre-draft. This is not tracked within the EIP Repository.

Draft - The first formally tracked stage of an EIP in development. An EIP is merged by an EIP Editor into the EIP repository when properly formatted.

Review - An EIP Author marks an EIP as ready for and requesting Peer Review.

Last Call - This is the final review window for an EIP before moving to Final. An EIP editor will assign Last Call status and set a review end date (last-call-deadline), typically 14 days later.

If this period results in necessary normative changes it will revert the EIP to Review.

Final - This EIP represents the final standard. A Final EIP exists in a state of finality and should only be updated to correct errata and add non-normative clarifications.

A PR moving an EIP from Last Call to Final SHOULD contain no changes other than the status update. Any content or editorial proposed change SHOULD be separate from this status-updating PR and committed prior to it.

Stagnant - Any EIP in Draft or Review or Last Call if inactive for a period of 6 months or greater is moved to Stagnant. An EIP may be resurrected from this state by Authors or EIP Editors through moving it back to Draft or it’s earlier status. If not resurrected, a proposal may stay forever in this status.

EIP Authors are notified of any algorithmic change to the status of their EIP

Withdrawn - The EIP Author(s) have withdrawn the proposed EIP. This state has finality and can no longer be resurrected using this EIP number. If the idea is pursued at later date it is considered a new proposal.

Living - A special status for EIPs that are designed to be continually updated and not reach a state of finality. This includes most notably EIP-1.

By following this process, EIP authors can ensure that their proposals are well-vetted and have the support of the community.

EIP Process

blockchainethereumeip3 min read

LooksRare Photo by Exodus

Introduction

In this report, we will examine LooksRare from a variety of aspects (what it does, how it works, a competitor analysis, problems and potentials of such NFT marketplaces) to see what we can learn from LooksRare. The target audience of this report is people with technical backgrounds who are interested in learning more about the current state of the Web3 and NFT industries from both technical and business perspectives.

Background

Before we dive into NFT marketplaces like LooksRare, let me briefly introduce NFT and NFT marketplaces.

NFT (Non-Fungible Token): What is it? To answer this question, we should learn about Fungible Tokens to understand its antonym. According to Larousse, "things that are consumed by usage and can be replaced by things of the same kind, the same quality and the same quantity" are considered fungible. For example, in the blockchain ecosystem, Sandbox's $SAND tokens are fungible and will always have the same value if they are swapped with one other. They can be used to buy LANDs in the Sandbox, which are nonfungible.

(Image: NFT LAND in THE SANDBOX)

An NFT (Non-Fungible Token) is a piece of data that is stored on a blockchain that guarantees a cryptographic asset is unique and hence not interchangeable while also providing a unique digital certificate of ownership for the NFT. In a broader sense, an NFT records the "provenance" of the assigned digital object, providing unquestionable answers to issues like who produced, possessed, and owned the NFT in the past, as well as which of the numerous copies is the original. Photos, films, and audio can all be associated with an NFT as digital objects of various forms. In a variety of contexts, including gaming, art, and sports collectibles, NFTs are currently being utilized to commercialize digital artifacts. NFTs were initially a component of the Ethereum blockchain, but more and more blockchains are now adopting their own versions of NFTs.

NFT Marketplace: As implied by the name, it is a platform where NFTs can be shown, traded, and in some cases created (minted). Similarly to how Amazon or eBay are to products, these marketplaces are to NFTs. Although there are different types of NFT marketplaces for different forms of NFT, we will focus on universal NFT marketplaces (i.e., marketplaces that have any sort of NFT collection) like LooksRare and OpenSea in this report. If you are interested in learning more about NFT and NFT marketplaces, read this and this.

What is LooksRare

LooksRare is a NFT marketplace with a focus on the community, describing itself as a platform “by NFT people, for NFT people”. LooksRare has drawn a lot of interest in the NFT market since its launch on January 11th of this year, primarily because, unlike VC-backed OpenSea, it genuinely conforms to the Web3 principles by rewarding users for their participation and staking its own token $LOOKS. It gained notice right away in terms of both trading volumes (wash trading was making a lot of noise) and protocol profitability.

LooksRare aims to actively reward those who trade, collect, and create. Rewards come in a variety of forms:

  • LOOKS Staking to Earn Platform Fees: LOOKS token stakers earn 100% of the trading fees (in WETH) on LooksRare.
  • Listing Rewards: LooksRare's Listing Rewards program enables NFT collectors and traders to earn LOOKS tokens just by listing NFTs for sale on LooksRare.
  • Trading Rewards: Trade any NFT on LooksRare, Earn LOOKS tokens.
  • LOOKS Staking Rewards: When you stake LOOKS, you also earn additional LOOKS on top of the trading fee rewards received in WETH.
  • Liquidity Provider Rewards (Discontinued since 2022/02/15, 10:15 AM (UTC)): LooksRare is incentivizing liquidity for the LOOKS token by giving rewards for users that stake LOOKS-ETH UniV2 LP tokens. The announcement for the discontinuation is here.

As a part of LooksRare's initial launch, there was an airdrop of LOOKS tokens as well. Users who have transacted > 3ETH worth of NFTs on OpenSea between 16 June and 16 December 2021 are the target users for the airdrop. You may find information on token allocation here. By providing incentives to this group of valuable users, the trading volume rises as a result of their natural inclination to list and trade NFTs on LooksRare. The term "Vampire Attack" refers to such go-to-market strategy of drawing users away from an established platform and toward a competing one by providing an incentive (usually tokens).

The section below titled "How LooksRare Works" will provide a thorough analysis of rewards and airdrop.


As seen in the graph, the rewards and incentives outlined above initially successfully increased trading on LooksRare.

(Graph: LooksRare Volume without wash trades filtered)

However, through wash trading, speculators found opportunities to reap the rewards. In this case, it means that the same individual trades NFTs using his/her own different wallets in order to benefit from trading rewards. The following graph demonstrates how significantly less trading volume when wash trading is filtered. Here, Web3 data scientist Hildobby explains how this filter was used and why the figures are startlingly different.

(Graph: LooksRare Volume with wash trades filtered)

However, I agree with the argument that if used temporarily, such a technique may vampire a network and drain off some of the OpenSea volume, which every day generates millions of dollars in fees. LooksRare views wash trading as dangerous for the traders because they are unsure of how much other traders will contribute to the total trading volume. LooksRare responsed to wash trading in their official docs.

Let's have a quick review at the team and what they get from this project.

  • The platform was created by a team of 28 people (14 previously) under the anonymous Guts and Zodd. The co-founders are "NFT nerds" who have long been active in the NFT field using various aliases, according to the interview with The Block. They were frustrated with the current NFT marketplaces and decided to start LooksRare because they could not fork OpenSea to get what they needed. The team said that by structuring the smart contracts for the marketplace in a modular manner, they would be able to make modifications quickly. They also intend to support L2 networks, which would enable less expensive and quicker transactions. The team is active, polishes the user experience a lot, makes consistent progress, and is actively recruiting for various positions.
  • Since the team also holds the token, they have an incentive to continue developing the platform and enhancing the product because the token's value is based on the amount of transactions and platform fees. The vesting schedule also demonstrates the team's dedication. The team won't start earning LOOKS tokens for another six months. This suggests that, as opposed to a pump-and-dump project, the team truly intends to construct the platform. The token emission schedule and token allocation will be analyzed in "How LooksRare Works" section as well.
  • As the Docs, website, and Discord initially only supported English and Chinese, we might surmise that there are Chinese members who directly participated in this project even though the team remains anonymous.

How LooksRare Works

The most crucial component of LooksRare's system, the LOOKS token, which distinguishes it from OpenSea, can be learned first in order to comprehend how it works.

(Image: LOOKS Token Allocation)

Percentage of supplyTotal LOOKS
Airdrop12%120,000,000
Strategic Sale3.3%33,083,003
Liquidity Management1.7%16,916,997
Volume Rewards44.1%441,000,000
Staking Rewards18.9%189,000,000
Founding Team10%100,000,000
Treasury10%100,000,000
Total Supply100%1,000,000,000

The table above illustrates how tokens are distributed across the team, investors, protocol, and community. Let's focus on the community tokens:

Airdrop: 12% (120M) of the token is used in Airdrop.

(Graph: Number of claimed LOOKS token airdrop)

(Graph: Number of claimed eligible addresses)

As of this writing, 81.97% (98,366,481/120,000,000) of the LOOKS airdrop has been claimed by 67.31% (124,665/185,223) of the eligible addresses. For more stats for the Airdrop, have a look at this stats. Airdropping this group of valuable users encourages them to list and trade NFTs on LooksRare, which can increase trading volume in the market, as we previously indicated.

Staking rewards: 18.9% (189M) of the tokens are distributed as staking rewards.

Along with the trading fee you might receive when you stake LOOKs, the project might give you an additional staking rewards distribution in the short run. This gives people an additional incentive to stake LOOKS at the project's early stages. This is also the reason why a staking reward increase to 1000% is possible.

Actually, about half of the staking reward comes from the staking rewards (LOOKS), with the remaining half comes from the trading fees (WETH). Since the stakers split the benefits proportionally, the APR return eventually declines as the number of users rises.

In addition to the trading fee rewards earned in WETH, you also gain additional LOOKS when you stake LOOKS. Users who want to just leave their LOOKS tokens staked will have their staked LOOKS tokens automatically compounded.

The calculation of staking rewards has a fairly simple formula (Actually, LooksRare's math has always been straightforward. We will discuss its pros and cons later):

The formula used to determine User A's LOOKS staking rewards per block is: LOOKS per block * (LOOKS staked by User A / Total amount of staked LOOKS)

Example

  • User A stakes 10,000 LOOKS during Phase A
  • The total amount of staked LOOKS is now 1,000,000 LOOKS

Based on the above, User A would receive: 189 * (10,000 / 1,000,000) = 1.89 LOOKS per block

PHASELengthLOOKS Per BlockLOOKS Per Day
A195,000 blocks (30 days)189.00 LOOKS1,228,500.00
B585,000 blocks (90 days)89.775 LOOKS583,537.50
C1,560,000 blocks (240 days)35.4375 LOOKS230,343.75
D2,346,250 blocks (361 days)18.90 LOOKS122,850.00

Based on a schedule of 6,500 Ethereum blocks per day, LOOKS staking rewards will be paid during 4 phases at varying reward rates.

Trading rewards: 44.1% (441M) of the tokens are distributed as trading rewards.

The token economy of LooksRare, which aims to become the most liquid NFT market in the world, is fundamentally based on trading rewards. Trading rewards in the form of LOOKS, LooksRare's platform token, are given to users who trade any NFTs on the exchange. For their trade volume, both the buyer and the seller of an item receive rewards (except for private sales). Users receive trading rewards two hours after the end of each day after they are calculated daily.

Similarly, early adopters who trade NFTs through LooksRare receive additional trading benefits. The distribution runs out in 721 days according to the timeline below.

PHASELengthLOOKS Per Day For Trading Rewards
A195,000 blocks (30 days)2,866,500.00
B585,000 blocks (90 days)1,361,587.50
C1,560,000 blocks (240 days)537,468.75
D2,346,250 blocks (361 days)286,650.00

Each day, trade awards are computed based on each user's LooksRare trading volume as a proportion of all daily trading volume on the site, excluding private sales.

User A's trading rewards on Day 1 is: $$c * (a / b)$$

Where:

  • a = User A's Trading Volume During Day 1
  • b = Total Platform Trading Volume During Day 1
  • c = LOOKS Rewards Per Day

Example

  • User A trades 10 ETH worth of NFTs on Day 1
  • There is 10,000 ETH total volume on LooksRare on Day 1

Based on the above, on Day 1, User A would receive: 2,866,500 * (10 / 10,000) = 2,866.5 LOOKS

Platform Fees:

LooksRare charges a baseline 2% (in WETH) sales fee on all NFT transactions aside from private sales. At the conclusion of each recurrent 6,500 Ethereum block period (approximately 24 hours), all WETH earned from these fees is consolidated and distributed to LOOKS stakeholders in a linear format per block during the following 6,500 block period.

Active and Passive Staking:

At the conclusion of the preceding period, incentives are calculated for each day and divided between active and passive stakeholder groups before being given out. Passive staking does not result in more Looks being earned when staked, which is the fundamental distinction between active and passive stakers. The bulk of stakers, whose staked LOOKS tokens are fully unlocked, are active stakers. The term "passive stakers" refers to holders of Team, Treasury, and Strategic sale tokens, which are locked for trade but unlocked for staking (which unlock over time - learn more).

A part of the WETH fees earned during the previous 6,500 blocks is sent to the Passive Staking address at the beginning of each 6,500 block period. The amount is determined as follows: $$c * (a / b)$$

Where:

  • a = Total amount of LOOKS staked passively at start of period
  • b = Total amount of LOOKS staked at start of period (passive + active)
  • c = Amount of WETH fees from previous 6,500 blocks

The remaining WETH is then sent to the Active Staking Pool.

How is WETH fee sharing calculated for Active LOOKS stakers?

The amount of WETH rewards to be awarded to active stakers in each block for each 6,500-block period is determined as follows: Total WETH collected as fees in the prior 6500 block period / 6500.

Each user's amount of staked LOOKS at each block is then compared against the total amount of LOOKS staked at each block, with this being done at every block within the 6,500 block period to find the total amount of WETH rewards received.

Example

  • Let's assume LooksRare processes 10,000 WETH of non-private sale volume in the first 6,500 blocks after launch, collecting total fees of 200 WETH.
  • At block #6500, User A stakes 10,000 LOOKS in preparation to start earning WETH at block #6501.
  • At block #6501,
    • The amount of passive tokens staked is 10% of the total amount of tokens staked, meaning 20 WETH (10% * 200) is sent to the passive staking address.
    • The remaining 180 WETH is put into the active LOOKS staking pool, with 0.027692 WETH to be earned per block for 6,500 blocks (180 / 6,500).
    • The total amount of LOOKS staked from ALL users is 1,000,000 LOOKS.
    • This means that User A will be allocated: 0.027692 * (10,000 / 1,000,000) = 0.00027692 WETH at block #6501.
  • At block #6502,
    • Assuming User A's stake does not change, but the total amount of LOOKS staked from all users increases to 1,500,000 LOOKS, then User A will be allocated: 0.027692 * (10,000 / 1,500,000) = 0.00018641 WETH at block #6502.
  • This calculation each block will then continue for another 6,498 blocks (since our example covers a 6,500 block period), with 0.027692 WETH as the amount to be earned per block.
  • The WETH fees generated from trades on the LooksRare platform in the 6,500-block period between block #6501 and block #13000 will then be used as the rewards to be distributed linearly over the next period, which will be from block #13001 and #19500.

You might be wondering about LooksRare's economic model at this point after reading about its tokenomics and how it supports the platform. The arithmetic behind each reward is straightforward, as we just mentioned. They follow a similar pattern: rewards = (# of User's XXX / # of Total XXX) * Periodical XXX Bonus. Such simplicity has both pros and cons. On the one hand, it's easy to come up with and put into practice. Users may easily grasp it and begin experimenting with the platform and tokens. Unlike the DeFi project, the NFT marketplace should be simple for users to use because they might not be interested in complex mathematical calculations like those used in DeFi.

On the other hand, speculators can more readily see the flaws in a straightforward rewarding mechanism. Wash trading is one of the example that shows the economic model is susceptible to such "attack".

To effectively describe the economic model, I created a circular flow chart:

The initial airdrop attracted valuable users from OpenSea to list NFT on LooksRare --> Token in circulation increases, and there are NFTs coming to the platform. Trading rewards boost the trading volume --> Platform collects platform fees in WETH as staking rewards to give back to stakers --> Staking rewards APR increases (up to 1,000% not long after initial launch) so that users tend to stake their LOOKS token --> Token in circulation decreases. The token price increases as the platform gets more popular and the token in circulation gets smaller --> More people use the platform and contribute to trading volume, the circulation continues. Wash trading could happen since the value of LOOKS tokens earned was high enough to cover the cost of the platform fee in WETH.

However, the model can also be suffering from a "Token value death spiral" because of external factors like crypto/NFT bear market. When it's a bear market, trading volume decreases drastically --> staking rewards APR decreases and token in circulation increases --> token value decreases, so many users will leave --> trading volume keeps decreasing and the "death spiral" begins.

As these two circular flow charts suggest, LooksRare is strongly binded to the LOOKS token. At the time of writing, the LOOKS token price is $0.2647. If the team wants to enter the "healthy circulation" again in the next bull market, they have to improve the platform and refine the rewarding model to attract and retain users.

That's it for the business side of LooksRare. Let's now have a glance at the technical side.

This page contains a list of all the deployed contract addresses. Due to a lack of space, I just chose a few of the interesting ones to discuss. To analyze the LooksRare's technical architecture, I might write another report.

Let's first look at the core of LooksRare exchange. It execute NFT trade after the buyer and the seller have agreed on a price.

/**
* @notice Constructor
* @param _currencyManager currency manager address
* @param _executionManager execution manager address
* @param _royaltyFeeManager royalty fee manager address
* @param _WETH wrapped ether address (for other chains, use wrapped native asset)
* @param _protocolFeeRecipient protocol fee recipient
*/
constructor(
address _currencyManager,
address _executionManager,
address _royaltyFeeManager,
address _WETH,
address _protocolFeeRecipient
) {
// Calculate the domain separator
DOMAIN_SEPARATOR = keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")

In the constructor, we instantiate the value of important variables like the addresses of smart contracts we are interacting with and the fee recipients.

/**
* @notice Cancel all pending orders for a sender
* @param minNonce minimum user nonce
*/
function cancelAllOrdersForSender(uint256 minNonce) external {
require(minNonce > userMinOrderNonce[msg.sender], "Cancel: Order nonce lower than current");
require(minNonce < userMinOrderNonce[msg.sender] + 500000, "Cancel: Cannot cancel more orders");
userMinOrderNonce[msg.sender] = minNonce;

emit CancelAllOrders(msg.sender, minNonce);
}

/**
* @notice Cancel maker orders
* @param orderNonces array of order nonces
*/
function cancelMultipleMakerOrders(uint256[] calldata orderNonces) external {
require(orderNonces.length > 0, "Cancel: Cannot be empty");

for (uint256 i = 0; i < orderNonces.length; i++) {
require(orderNonces[i] >= userMinOrderNonce[msg.sender], "Cancel: Order nonce lower than current");
_isUserOrderNonceExecutedOrCancelled[msg.sender][orderNonces[i]] = true;
}

emit CancelMultipleOrders(msg.sender, orderNonces);
}

These two functions are for cancelling orders. LooksRare like OpenSea uses a system of hybrid orders (off-chain/on-chain) which incorporates off-chain signatures (these are called Maker Orders) and on-chain orders (called Taker Orders). LooksRare uses exclusively EIP-712 signatures, which provide key benefits for users such as greater readability for humans in the message they sign. A maker order is a passive order, which can be executed (if not cancelled!) against a taker order after it is signed. Since the execution of a maker order is done once a taker order matches on-chain, network gas fees are never paid by the maker user.

There are three functions to match maker orders with taker orders and let's look at the first one.

This function matches a maker sell order against a taker buy order if the currecny is ether or wrapped ether:

First we do some sanity checks:

/**
* @notice Match ask with a taker bid order using ETH
* @param takerBid taker bid order
* @param makerAsk maker ask order
*/
function matchAskWithTakerBidUsingETHAndWETH(
OrderTypes.TakerOrder calldata takerBid,
OrderTypes.MakerOrder calldata makerAsk
) external payable override nonReentrant {
require((makerAsk.isOrderAsk) && (!takerBid.isOrderAsk), "Order: Wrong sides");
require(makerAsk.currency == WETH, "Order: Currency must be WETH");
require(msg.sender == takerBid.taker, "Order: Taker must be the sender");

// If not enough ETH to cover the price, use WETH
if (takerBid.price > msg.value) {
IERC20(WETH).safeTransferFrom(msg.sender, address(this), (takerBid.price - msg.value));
} else {
require(takerBid.price == msg.value, "Order: Msg.value too high");
}

Then we transfer the payment amount to this smart contract in ether or wrapped ether

// If not enough ETH to cover the price, use WETH
if (takerBid.price > msg.value) {
IERC20(WETH).safeTransferFrom(msg.sender, address(this), (takerBid.price - msg.value));
} else {
require(takerBid.price == msg.value, "Order: Msg.value too high");
}

// Wrap ETH sent to this contract
IWETH(WETH).deposit{value: msg.value}();

// Check the maker ask order
bytes32 askHash = makerAsk.hash();
_validateOrder(makerAsk, askHash);

Then we check the signature of the sell order. There is no need to check the signature of the buy order since only the buyer can send the buy order.

// Check the maker ask order
bytes32 askHash = makerAsk.hash();
_validateOrder(makerAsk, askHash);

// Retrieve execution parameters
(bool isExecutionValid, uint256 tokenId, uint256 amount) = IExecutionStrategy(makerAsk.strategy)
.canExecuteTakerBid(takerBid, makerAsk);

Then we check if the payment amount is enough:

// Retrieve execution parameters
(bool isExecutionValid, uint256 tokenId, uint256 amount) = IExecutionStrategy(makerAsk.strategy)
.canExecuteTakerBid(takerBid, makerAsk);

require(isExecutionValid, "Strategy: Execution invalid");

// Update maker ask order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerAsk.signer][makerAsk.nonce] = true;

Then we save the nonce of the order in the mapping to prevent replay attack of the order.

// Update maker ask order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerAsk.signer][makerAsk.nonce] = true;

Then we transfer the payment to the seller, royalties to the NFT creator, and the platform fees to the LooksRare.

// Update maker ask order status to true (prevents replay)
_isUserOrderNonceExecutedOrCancelled[makerAsk.signer][makerAsk.nonce] = true;

// Execution part 1/2
_transferFeesAndFundsWithWETH(
makerAsk.strategy,
makerAsk.collection,
tokenId,
makerAsk.signer,
takerBid.price,
makerAsk.minPercentageToAsk
);

Finally, we transfer the NFT to the buyer and emit TakerBid event

// Execution part 2/2
_transferNonFungibleToken(makerAsk.collection, makerAsk.signer, takerBid.taker, tokenId, amount);

emit TakerBid(
askHash,
makerAsk.nonce,
takerBid.taker,
makerAsk.signer,
makerAsk.strategy,
makerAsk.currency,
makerAsk.collection,
tokenId,
amount,
takerBid.price
);

The other two functions are similar so I'll leave them for you to explore.

Competitor Review

LooksRare has been discussed extensively, and we now have sufficient information to evaluate its competitors.

  • OpenSea
    • Overview: The largest NFT market in the world, according to OpenSea, there are about 700 projects total, including naming systems like ENS (Ethereum Name Service), collecting games, trading card games, and collectible games. OpenSea was founded in 2017 and currently supports many blockchains, with Ethereum being the largest. It has over 200 workers, 600k users, 80 million NFTs, and $20 billion in trading activity.
    • In 2021, nearly 90% of NFT trading volume happened on OpenSea.
      • Since it dominates the NFT industry, competing marketplaces have a difficult time attracting people away from it in the first place. New users will tend to use the marketplace that is currently dominating the market.
    • Platform Fee: 2.5%
    • Offering three different options for listing:
      • Fixed Price Listings: Fixed price set by the seller
      • English Auctions: The seller sets the minimum price, waits for bids to climb up, and accepts the highest. Here, the seller can set a minimum reserve price for the NFT.
      • Dutch Auction: Sellers set starting price, an end price and duration. You start the auction at a high price and let the price decline over time. People will then buy the NFT at the price they see fit.
    • Backed by Venture Capital and does not give back to the community (Web3 principles).
    • Does NOT support batch buy/sweep floors
  • gem.xyz
    • Overview: An NFT marketplace aggregator that gathers all NFT transaction information from different chains and consolidates it in one place - improves the efficiency and effectiveness of the transaction.
    • Features:
      • Buy multiple NFTs in a single transaction
      • Sweep the collection floor
      • Pay with any token (or multiple ones)
      • save tons gas compared to buying on the marketplaces directly
  • X2Y2
    • Similar UI to OpenSea, Similar economic model, marketing strategy, and docs to LooksRare
    • The math of rewards is more complex than LooksRare's
    • Does support batch buy/sweep floors

It's worth mentioning that LooksRare has been integrated with geniexyz to allow users to sweep the floor like they can do it using gem.xyz or X2Y2. Long-term competition between LooksRare and X2Y2 and OpenSea is increased by these actively integrated new features (LooksRare's Collection offer, Trait offer, and Multi-cancellation).

Closing Thoughts

By putting the community first, new NFT markets like LooksRare compete with industry leader OpenSea in a Web3 approach. Through "Vampire Attack," LooksRare and X2Y2 have effectively attracted people and attention from OpenSea, but retaining those users is currently the most essential issue. Although the prices of LOOKS ($0.26) and X2Y2 ($0.13) at the time of writing are less than most users had expected, we can see that the teams and community are still actively improving the platforms. The token prices demonstrate how significantly the current NFT bear market has impacted various NFT marketplaces. However, given the trading volume on OpenSea is equally subpar, we cannot yet declare the demise of LooksRare, X2Y2, and other marketplaces. If OpenSea has its own cryptocurrency, I think the price will also drop significantly. OpenSea was formed in 2017, however it didn't achieve success until the 2021 NFT bull market. The supremacy of OpenSea will be challenged by innovative platform(s) in the upcoming bull market.


Disclaimer: The information provided on this website is provided solely for educational purposes and does not constitute any advice, including but not limited to, investment advice, trading advice or financial advice, and you should not treat any of the website's content as such. Social Media Examiner recommends that you independently research any information contained on this Website and that you speak with an investment professional before making any decision to purchase, trade, hold or sell cryptocurrency. Nothing herein should be treated as a recommendation to buy, sell or hold cryptocurrency. Social Media Examiner cannot guarantee the accuracy of any information listed on the website and is not responsible for any missing or wrong information. All information is provided as is and should be used at your own risk. Social Media Examiner disclaims all responsibility and liability for your use of any information found on the website.


References

Mapping the NFT revolution: market trends, trade networks, and visual features, https://www.nature.com/articles/s41598-021-00053-8

LooksRare — Upcoming competitor of Opensea, https://blog.cryptostars.is/looksrare-decentralised-nft-marketplace-58adbce39d07

LooksRare NFT marketplace after a month - the past, present and the way ahead? (NFTmemo #1), https://mirror.xyz/mattbullish.eth/HiN9mtzqex0OVoURXCQZU6yLxmPal6md5qVnAk2K5v0

NonFungible, Quarterly NFT Market Report Q2 2022, https://nonfungible.com/reports/2022/en/q2-quarterly-nft-market-report

A Comprehensive Analysis of 5 Popular NFT Marketplaces, https://onxrp.com/analysis-of-nft-marketplaces/

blockchainethereumnft16 min read

Blockchain Visual Photo by Authena

Blockchain

What is a blockchain?

A blockchain is a distributed database or ledger that is shared among the nodes of a computer network. As a database, a blockchain stores information electronically in digital format. Blockchains are best known for their crucial role in cryptocurrency systems, such as Bitcoin, for maintaining a secure and decentralized record of transactions. The innovation with a blockchain is that it guarantees the fidelity and security of a record of data and generates trust without the need for a trusted third party.

One key difference between a typical database and a blockchain is how the data is structured. A blockchain collects information together in groups, known as blocks, that hold sets of information. Blocks have certain storage capacities and, when filled, are closed and linked to the previously filled block, forming a chain of data known as the blockchain. All new information that follows that freshly added block is compiled into a newly formed block that will then also be added to the chain once filled.

A database usually structures its data into tables, whereas a blockchain, as its name implies, structures its data into chunks (blocks) that are strung together. This data structure inherently makes an irreversible timeline of data when implemented in a decentralized nature. When a block is filled, it is set in stone and becomes a part of this timeline. Each block in the chain is given an exact timestamp when it is added to the chain.

KEY TAKEAWAYS

  • Blockchain is a type of shared database that differs from a typical database in the way that it stores information; blockchains store data in blocks that are then linked together via cryptography.
  • As new data comes in, it is entered into a fresh block. Once the block is filled with data, it is chained onto the previous block, which makes the data chained together in chronological order.
  • Different types of information can be stored on a blockchain, but the most common use so far has been as a ledger for transactions.
  • In Bitcoin's case, blockchain is used in a decentralized way so that no single person or group has control—rather, all users collectively retain control.
  • Decentralized blockchains are immutable, which means that the data entered is irreversible. For Bitcoin, this means that transactions are permanently recorded and viewable to anyone.

Block

Blocks are data structures within the blockchain database, where transaction data in a cryptocurrency blockchain are permanently recorded. A block records some or all of the most recent transactions not yet validated by the network. Once the data are validated, the block is closed. Then, a new block is created for new transactions to be entered into and validated.

A block is thus a permanent store of records that, once written, cannot be altered or removed.

KEY TAKEAWAYS

  • A block is a place in a blockchain where information is stored and encrypted.
  • Blocks are identified by long numbers that include encrypted transaction information from previous blocks and new transaction information.
  • Blocks and the information within them must be verified by a network before new blocks can be created.
  • Blocks and blockchains are not used solely by cryptocurrencies. They also have many other uses.

A blockchain network witnesses a great deal of transaction activity. When used in cryptocurrency, maintaining a record of these transactions helps the system track how much was or wasn't used and which parties were involved. The transactions made during a given period are recorded into a file called a block, which is the basis of the blockchain network.

A block stores information. There are many pieces of information included within a block, but it doesn't occupy a large amount of storage space. Blocks generally include these elements, but it might vary between different types:

  • Magic number: A number containing specific values that identify that block as part of a particular cryptocurrency's network.
  • Blocksize: Sets the size limit on the block so that only a specific amount of information can be written in it.
  • Block header: Contains information about the block.
  • Transaction counter: A number that represents how many transactions are stored in the block.
  • Transactions: A list of all of the transactions within a block.

The transaction element is the largest because it contains the most information. It is followed in storage size by the block header, which includes these sub-elements:

  • Version: The cryptocurrency version being used.
  • Previous block hash: Contains a hash (encrypted number) of the previous block's header.
  • Hash Merkle root: Hash of transactions in the Merkle tree (binary hash tree) of the current block.
  • Time: A timestamp to place the block in the blockchain.
  • Bits: The difficulty rating of the target hash, signifying the difficulty in solving the nonce.
  • Nonce: The encrypted number that a miner must solve to verify the block and close it.

One 32-bit number in the header is called a nonce—the mining program uses random numbers to "guess" the nonce in the hash. When a nonce is verified, the hash is solved when the nonce, or a number less than it, is guessed. Then, the network closes that block, generates a new one with a header, and the process repeats.

Mining's Relationship to Blocks

Mining is the term used for solving the number that is the nonce, the only number that can be changed in a block header. It is also the process the cryptocurrency's network uses if proof-of-work is used in the protocol.

Cryptocurrency mining is commonly thought to be a complex mathematical problem; it is actually a random number generated through hashing. Hashing is the process of encrypting information using the encryption method a cryptocurrency uses. For example, Bitcoin uses SHA256 for its encryption algorithm. For a miner to generate the "winning" number, the mining program must use SHA 256 to hash random numbers and place them into the nonce to see if it is a match.

The difficulty lies in that all previous block headers are encrypted randomly. Hence, the current block header is a randomly generated encrypted number based on the randomly generated encrypted numbers of previous blocks and information from the current block.

How Does a Blockchain Work?

The goal of blockchain is to allow digital information to be recorded and distributed, but not edited. In this way, a blockchain is the foundation for immutable ledgers, or records of transactions that cannot be altered, deleted, or destroyed. This is why blockchains are also known as a distributed ledger technology (DLT).

First proposed as a research project in 1991, the blockchain concept predated its first widespread application in use: Bitcoin, in 2009. In the years since, the use of blockchains has exploded via the creation of various cryptocurrencies, decentralized finance (DeFi) applications, non-fungible tokens (NFTs), and smart contracts.

Transaction Process

Resource:


Consensus Mechanism

What Is a Consensus Mechanism?

A consensus mechanism is a fault-tolerant mechanism that is used in computer and blockchain systems to achieve the necessary agreement on a single data value or a single state of the network among distributed processes or multi-agent systems, such as with cryptocurrencies. It is useful in record-keeping, among other things.

On the Bitcoin blockchain, for instance, the consensus mechanism is known as Proof-of-Work (PoW), which requires the exertion of computational power in order to solve a difficult but arbitrary puzzle in order to keep all nodes in the network honest.

KEY TAKEAWAYS

  • A consensus mechanism refers to any number of methodologies used to achieve agreement, trust, and security across a decentralized computer network.
  • In the context of blockchains and cryptocurrencies, proof-of-work (PoW) and proof-of-stake (PoS) are two of the most prevalent consensus mechanisms.
  • Critics of Bitcoin miners have argued that PoW is overly energy-intensive, which has sparked the creation of new and more efficient mechanisms.

Consensus Mechanism Explained

In any centralized system, like a database holding key information about driving licenses in a country, a central administrator has the authority to maintain and update the database. The task of making any updates—like adding/deleting/updating names of people who qualified for certain licenses—is performed by a central authority who remains the sole in-charge of maintaining genuine records.

Public blockchains that operate as decentralized, self-regulating systems work on a global scale without any single authority. They involve contributions from hundreds of thousands of participants who work on verification and authentication of transactions occurring on the blockchain, and on the block mining activities.

In such a dynamically changing status of the blockchain, these publicly shared ledgers need an efficient, fair, real-time, functional, reliable, and secure mechanism to ensure that all the transactions occurring on the network are genuine and all participants agree on a consensus on the status of the ledger. This all-important task is performed by the consensus mechanism, which is a set of rules that decides on the legitimacy of contributions made by the various participants (i.e., nodes or transactors) of the blockchain.

Blockchain Consensus Mechanisms

There are different kinds of consensus mechanism algorithms, each of which works on different principles.

The proof of work (PoW) is a common consensus algorithm used by the most popular cryptocurrency networks like bitcoin and litecoin. It requires a participant node to prove that the work done and submitted by them qualifies them to receive the right to add new transactions to the blockchain. However, this whole mining mechanism of bitcoin needs high energy consumption and a longer processing time.

The proof of stake (PoS) is another common consensus algorithm that evolved as a low-cost, low-energy consuming alternative to the PoW algorithm. It involves the allocation of responsibility in maintaining the public ledger to a participant node in proportion to the number of virtual currency tokens held by it. However, this comes with the drawback that it incentivizes cryptocoin hoarding instead of spending.

While PoW and PoS are by far the most prevalent in the blockchain space, there are other consensus algorithms like Proof of Capacity (PoC) which allow sharing of memory space of the contributing nodes on the blockchain network. The more memory or hard disk space a node has, the more rights it is granted for maintaining the public ledger. Proof of Activity (PoA), used on the Decred blockchain, is a hybrid that makes use of aspects of both PoW and PoS. Proof of Burn (PoB) is another that requires transactors to send small amounts of cryptocurrency to inaccessible wallet addresses, in effect "burning" them out of existence.

Another, called Proof of History (PoH), developed by the Solana Project and similar to Proof of Elapsed Time (PoET), encodes the passage of time itself cryptographically to achieve consensus without expending many resources.

Proof-of-Work & Mining

Proof of work (PoW) describes a system that requires a not-insignificant but feasible amount of effort in order to deter frivolous or malicious uses of computing power, such as sending spam emails or launching denial of service attacks. The concept was subsequently adapted to securing digital money by Hal Finney in 2004 through the idea of "reusable proof of work" using the SHA-256 hashing algorithm.

Following its introduction in 2009, Bitcoin became the first widely adopted application of Finney's PoW idea (Finney was also the recipient of the first bitcoin transaction). Proof of work forms the basis of many other cryptocurrencies as well, allowing for secure, decentralized consensus.

KEY TAKEAWAYS

  • Proof of work (PoW) is a decentralized consensus mechanism that requires members of a network to expend effort solving an arbitrary mathematical puzzle to prevent anybody from gaming the system.
  • Proof of work is used widely in cryptocurrency mining, for validating transactions and mining new tokens.
  • Due to proof of work, Bitcoin and other cryptocurrency transactions can be processed peer-to-peer in a secure manner without the need for a trusted third party.
  • Proof of work at scale requires huge amounts of energy, which only increases as more miners join the network.
  • Proof of Stake (POS) was one of several novel consensus mechanisms created as an alternative to proof of work.

Understanding Proof of Work

This explanation will focus on proof of work as it functions in the bitcoin network. Bitcoin is a digital currency that is underpinned by a kind of distributed ledger known as a "blockchain." This ledger contains a record of all bitcoin transactions, arranged in sequential "blocks," so that no user is allowed to spend any of their holdings twice. In order to prevent tampering, the ledger is public, or "distributed"; an altered version would quickly be rejected by other users.

The way that users detect tampering in practice is through hashes, long strings of numbers that serve as proof of work. Put a given set of data through a hash function (bitcoin uses SHA-256), and it will only ever generate one hash. Due to the "avalanche effect," however, even a tiny change to any portion of the original data will result in a totally unrecognizable hash. Whatever the size of the original data set, the hash generated by a given function will be the same length. The hash is a one-way function: it cannot be used to obtain the original data, only to check that the data that generated the hash matches the original data.

Generating just any hash for a set of bitcoin transactions would be trivial for a modern computer, so in order to turn the process into "work," the bitcoin network sets a certain level of "difficulty." This setting is adjusted so that a new block is "mined"—added to the blockchain by generating a valid hash—approximately every 10 minutes. Setting difficulty is accomplished by establishing a "target" for the hash: the lower the target, the smaller the set of valid hashes, and the harder it is to generate one. In practice, this means a hash that starts with a very long string of zeros.

FAST FACT

Proof of work was initially created as a proposed solution to the growing problem of spam email.

Special Considerations

Since a given set of data can only generate one hash, how do miners make sure they generate a hash below the target? They alter the input by adding an integer, called a nonce ("number used once"). Once a valid hash is found, it is broadcast to the network, and the block is added to the blockchain.

Mining is a competitive process, but it is more of a lottery than a race. On average, someone will generate acceptable proof of work every ten minutes, but who it will be is anyone's guess. Miners pool together to increase their chances of mining blocks, which generates transaction fees and, for a limited time, a reward of newly-created bitcoins.

Proof of work makes it extremely difficult to alter any aspect of the blockchain, since such an alteration would require re-mining all subsequent blocks. It also makes it difficult for a user or pool of users to monopolize the network's computing power, since the machinery and power required to complete the hash functions are expensive.

Important

If part of a mining network begins accepting an alternative proof of work, it is known as a hard fork.

What happens if two miners mine the next block at the same time?

In Bitcoin terms, simultaneous answers occur frequently, but at the end of the day, there can only be one winning answer. When multiple simultaneous answers are presented that are equal to or less than the target number, the Bitcoin network will decide by a simple majority—51%—which miner to honor.

Typically, it is the miner who has done the most work or, in other words, the one that verifies the most transactions. The losing block then becomes an "orphan block." Orphan blocks are those that are not added to the blockchain. Miners who successfully solve the hash problem but haven't verified the most transactions are not rewarded with bitcoin.

Source: How Does Bitcoin Mining Work?

What is a 51% Attack

A 51% attack is an attack on a cryptocurrency blockchain by a group of miners who control more than 50% of the network's mining hash rate. Owning 51% of the nodes on the network gives the controlling parties the power to alter the blockchain. This group then introduces an altered blockchain to the network at a very specific point in the blockchain, which is theoretically accepted by the network because the attackers would own most of it.

The attackers would be able to prevent new transactions from gaining confirmations, allowing them to halt payments between some or all users. They would also be able to reverse transactions that were completed while they were in control of the network. Reversing transactions could allow them to double-spend coins, one of the issues consensus mechanisms like proof-of-work were created to prevent.

KEY TAKEAWAYS

  • Blockchains are distributed ledgers that record every transaction made on a cryptocurrency's network.
  • A 51% attack is an attack on a blockchain by a group of miners who control more than 50% of the network's mining hash rate.
  • Attackers with majority network control can interrupt the recording of new blocks by preventing other miners from completing blocks.
  • Changing historical blocks is difficult due to the hard-coding of past transactions into Bitcoin software.
  • Although a successful attack on Bitcoin or Ethereum is unlikely, smaller networks are frequent targets for 51% attacks.

Changing historical blocks—transactions locked in before the start of the attack—would be extremely difficult even in the event of a 51% attack. The further back the transactions are, the more difficult it is to change them. It would be impossible to change transactions before a checkpoint, where transactions become hard-coded into Bitcoin's software.

In addition to the costs, a group that attempts to attack the network using a 51% attack must not only control 51% of the network but must also introduce the altered blockchain at a very precise time. Even if they own 51% of the network hashing rate, they still might not be able to keep up with the block creation rate or get their chain inserted before valid new blocks are created by the 'honest' blockchain network.

Again, this is possible on smaller cryptocurrency networks because there is less participation and lower hash rates. Large networks make it nearly impossible to introduce an altered blockchain.

Proof-of-Stake

Proof-of-stake is a cryptocurrency consensus mechanism for processing transactions and creating new blocks in a blockchain. A consensus mechanism is a method for validating entries into a distributed database and keeping the database secure. In the case of cryptocurrency, the database is called a blockchain—so the consensus mechanism secures the blockchain.

Learn more about proof-of-stake and how it is different from proof-of-work. Additionally, find out the issues proof-of-stake is attempting to address within the cryptocurrency industry.

KEY TAKEAWAYS

  • With proof-of-stake (POS), cryptocurrency owners validate block transactions based on the number of coins a validator stakes.
  • Proof-of-stake (POS) was created as an alternative to Proof-of-work (POW), the original consensus mechanism used to validate a blockchain and add new blocks.
  • While PoW mechanisms require miners to solve cryptographic puzzles, PoS mechanisms require validators to simply hold and stake tokens.
  • Proof-of-stake (POS) is seen as less risky in terms of the potential for an attack on the network, as it structures compensation in a way that makes an attack less advantageous.
  • The next block writer on the blockchain is selected at random, with higher odds being assigned to nodes with larger stake positions.

Proof-of-stake reduces the amount of computational work needed to verify blocks and transactions that keep the blockchain, and thus a cryptocurrency, secure. Proof-of-stake changes the way blocks are verified using the machines of coin owners. The owners offer their coins as collateral for the chance to validate blocks. Coin owners with staked coins become "validators."

Validators are then selected randomly to "mine," or validate the block. This system randomizes who gets to "mine" rather than using a competition-based mechanism like proof-of-work.

To become a validator, a coin owner must "stake" a specific amount of coins. For instance, Ethereum will require 32 ETH to be staked before a user can become a validator. Blocks are validated by more than one validator, and when a specific number of the validators verify that the block is accurate, it is finalized and closed.

Different proof-of-stake mechanisms may use different methods for validating blocks—when Ethereum transitions to PoS, it will use shards for transaction submissions. A validator will verify the transactions and add them to a shard block, which requires at least 128 validators to attest to. Once shards are validated and block created, two-thirds of the validators must agree that the transaction is valid, then the block is closed.

FAST FACT

To summarize the Ethereum PoS process, you might say it is validation sharing across a cryptocurrency network instead of a validation competition.


Ethereum Consensus Mechanism

Proof-of-work

Ethereum, like Bitcoin, currently uses a proof-of-work (PoW) consensus protocol.

Block creation

Proof-of-work is done by miners, who compete to create new blocks full of processed transactions. The winner shares the new block with the rest of the network and earns some freshly minted ETH. The race is won by the computer which is able to solve a math puzzle fastest - this produces the cryptographic link between the current block and the block that went before. Solving this puzzle is the work in "proof-of-work".

Security

The network is kept secure by the fact that you'd need 51% of the network's computing power to defraud the chain. This would require such huge investments in equipment and energy; you're likely to spend more than you'd gain.

More on proof-of-work


Ethereum Proof-of-Stake

Ethereum plans to upgrade to a proof-of-stake (PoS) consensus protocol.

Proof-of-stake comes with a number of improvements to the proof-of-work system:

  • better energy efficiency - there is no need to use lots of energy on proof-of-work computations
  • lower barriers to entry, reduced hardware requirements - there is no need for elite hardware to stand a chance of creating new blocks
  • reduced centralization risk - proof-of-stake should lead to more nodes securing the network
  • because of the low energy requirement less ETH issuance is required to incentivize participation
  • economic penalties for misbehaviour make 51% style attacks exponentially more costly for an attacker compared to proof-of-work
  • the community can resort to social recovery of an honest chain if a 51% attack were to overcome the crypto-economic defenses.

VALIDATORS

To participate as a validator, a user must deposit 32 ETH into the deposit contract and run three separate pieces of software: an execution client, a consensus client, and a validator. On depositing their ether, the user joins an activation queue that limits the rate of new validators joining the network. Once activated, validators receive new blocks from peers on the Ethereum network. The transactions delivered in the block are re-executed, and the block signature is checked to ensure the block is valid. The validator then sends a vote (called an attestation) in favor of that block across the network.

Whereas under proof-of-work, the timing of blocks is determined by the mining difficulty, in proof-of-stake, the tempo is fixed. Time in proof-of-stake Ethereum is divided into slots (12 seconds) and epochs (32 slots). One validator is randomly selected to be a block proposer in every slot. This validator is responsible for creating a new block and sending it out to other nodes on the network. Also in every slot, a committee of validators is randomly chosen, whose votes are used to determine the validity of the block being proposed.

FINALITY

A transaction has "finality" in distributed networks when it's part of a block that can't change without a significant amount of ether getting burned. On proof-of-stake Ethereum, this is managed using "checkpoint" blocks. The first block in each epoch is a checkpoint. Validators vote for pairs of checkpoints that it considers to be valid. If a pair of checkpoints attracts votes representing at least two-thirds of the total staked ether, the checkpoints are upgraded. The more recent of the two (target) becomes "justified". The earlier of the two is already justified because it was the "target" in the previous epoch. Now it is upgraded to "finalized". To revert a finalized block, an attacker would commit to losing at least one-third of the total supply of staked ether (currently around $10,000,000,000). The exact reason for this is explained in this Ethereum Foundation blog post. Since finality requires a two-thirds majority, an attacker could prevent the network from reaching finality by voting with one-third of the total stake. There is a mechanism to defend against this: the inactivity leak. This activates whenever the chain fails to finalize for more than four epochs. The inactivity leak bleeds away the staked ether from validators voting against the majority, allowing the majority to regain a two-thirds majority and finalize the chain.

FORK CHOICE

When the network performs optimally and honestly, there is only ever one new block at the head of the chain, and all validators attest to it. However, it is possible for validators to have different views of the head of the chain due to network latency or because a block proposer has equivocated. Therefore, consensus clients require an algorithm to decide which one to favor. The algorithm used in proof-of-stake Ethereum is called LMD-GHOST, and it works by identifying the fork that has the greatest weight of attestations in its history.

ATTESTATIONS

Every epoch (6.4 minutes) a validator proposes an attestation to the network. The attestation is for a specific slot in the epoch. The purpose of the attestation is to vote in favor of the validator's view of the chain, in particular the most recent justified block and the first block in the current epoch (known as source and target checkpoints). This information is combined for all participating validators, enabling the network to reach consensus about the state of the blockchain.

The attestation contains the following components:

  • aggregation_bits: a bitlist of validators where the position maps to the validator index in their committee; the value (0/1) indicates whether the validator signed the data (i.e. whether they are active and agree with the block proposer)
  • data: details relating to the attestation, as defined below
  • signature: a BLS signature that aggregates the signatures of individual validators

The first task for an attesting validator is to build the data. The data contains the following information:

  • slot: The slot number that the attestation refers to
  • index: A number that identifies which committee the validator belongs to in a given slot
  • beacon_block_root: Root hash of the block the validator sees at the head of the chain (the result of applying the fork-choice algorithm)
  • source: Part of the finality vote indicating what the validators see as the most recent justified block
  • target: Part of the finality vote indicating what the validators see as the first block in the current epoch

Once the data is built, the validator can flip the bit in aggregation_bits corresponding to their own validator index from 0 to 1 to show that they participated.

Finally, the validator signs the attestation and broadcasts it to the network.


Block creation

Proof-of-stake is done by validators who have staked ETH to participate in the system. A validator is chosen at random to create new blocks, share them with the network and earn rewards. Instead of needing to do intense computational work, you simply need to have staked your ETH in the network. This is what incentivises healthy network behaviour.

Security

A proof-of-stake system is kept secure by the fact that you'd need 51% of the total staked ETH to defraud the chain. And that your stake is slashed for malicious behaviour.


Ethereum Misc. and Ethereum 2.0

Why Are Most dApps Built on Ethereum?

Decentralized applications (dApps) are built on blockchain networks and use smart contracts to create platforms that streamline and democratize the entry into industries ranging from finance to gaming — all without intermediaries and centralized authorities. In terms of front-end user experience, dApps appear nearly identical to traditional web applications. However, on the back-end, dApps function much differently than their conventional counterparts. Instead of employing the HTTP protocol to communicate with the broader network, dApps connect to the blockchain in a decentralized manner rather than routing through centralized servers.

The Ethereum network currently dominates dApp development for several reasons. Ethereum implements a development interface that reduces programming time and helps quickly launch projects. Beyond this, the Ethereum developer community has grown remarkably since the platform's launch. And Ethereum retains formidable network effects from its global coalition of technologists who remain committed to maintaining the network and actively developing user resources that drive adoption. Further, the ability to adequately monetize dApp projects incentivizes others to partake in the Ethereum ecosystem.

  • The Ethereum Virtual Machine (EVM)
    • Ethereum is known for providing a distinct and accommodating developer experience that makes it easier for novice blockchain developers to enter the space. A prime example of this is the Ethereum Virtual Machine (EVM), a unique software system that allows developers to launch any dApp regardless of the underlying coding language. Ethereum also uses a network-native language known as Solidity for coding smart contracts. This network architecture eliminates the need to develop an entirely new blockchain for every dApp.
    • Developers can work with the ready-made Ethereum system to fast-track onboarding and get their applications up and running sooner than other alternatives. This dynamic continues to drive the rapid development of DeFi products on the Ethereum network. By combining application templates, MetaMask integration, and the EVM, the overall Ethereum development kit allows companies to focus on refining their applications and developing on top of open-source code among a global, mission-based developer community that prioritizes cooperation over competition.
  • Developer Community and Network
    • Since launching in 2015, Ethereum has moved quickly from first mover to legacy status in the decentralized blockchain ecosystem. The network benefits from a highly skilled community of developers who have since built out crucial extension documentation and network updates to help the broader community. For example, Microsoft's Blockchain Development Kit for Ethereum and Diligence's Solidity Visual Auditor extension for Visual Studio code are used to enhance development on the Ethereum network. The increasing number of developers utilizing these solutions has perpetuated the development of better tools, better code, better platforms, and ultimately, better dApps.
    • Further, dApps like MakerDAO, IDEX, Bancor, and even CryptoKitties serve to amplify this network effect, drawing even greater attention to the Ethereum ecosystem. The function of composability, exemplified by dApps using open source code from other projects and building out token interoperability between platforms, has reinforced the cooperative infrastructure of the network. As a result, Ethereum has become the infrastructure of choice in every single dApp market segment.
  • Monetizing Ethereum dApps
    • Many dApps utilize a native token that facilitates activity within the application — also known as a utility token. On the Ethereum network, these tokens adhere to the ERC-20 tokenization standard, a set of rules that ensure Ethereum-based tokens can interact seamlessly with one another. This component of network architecture is critical to ensuring the continuity of Ethereum-based applications. To generate revenue, dApps can monetize their assets on existing crypto exchanges or launch their own decentralized exchange (DEX).
    • The ERC-20 standard enables the frictionless exchange of these crypto assets. Further, the increase in trading volume brings more awareness to dApps residing within the Ethereum ecosystem; the network reinvests in itself. A clear path toward monetization results from Ethereum's vast community and robust, interoperable network infrastructure.

Ethereum 2.0

Five Stages of Ethereum 2.0 Development (All about scaling, security, efficiency, and sustainability)

Vitalik Buterin:

“The Merge is proof of stake. The Surge is sharding, and The Verge is Verkle Trees, The Purge is things like state expiry and deleting old history, and The Splurge is basically just all of the other fun stuff.”

  • The Merge

    • 現時的以太坊主鏈和 Beacon Chain 將會合併,原本的 PoW (工作量證明) 共識將會轉成 PoS (權益證明)。由於 PoS 的電力消耗會比 PoW 低 99.95%, 消耗的電力比起 PoW 幾乎可以忽略不計, 這對在可持續發展方面有更多考量的企業來說, 以太坊變成了一個可行的選擇, 不會再因為環保問題被垢病。
    • 在 PoS 機制中,不再需要發行大量新的代幣去補貼礦工,因為發行量的減少,以太坊會有新的加密經濟模型,大部分的 ETH 代幣都會被質押,市場上的供應量會大大減少,令以太幣變成更稀有的硬通貨。
  • The Surge

    • 將區塊鏈的整個網路分成更小的分區,以後多條分片鏈將能同時進行交易與驗證,提升整個 Ethereum 網絡的效率。The Surge 其實就是以太坊 2.0 一直在強調的分片設計。The Surge 會將區塊鏈的整個網路分成更小的分區,以後多條分片鏈將能同時進行交易與驗證,提升整個網絡的效率。分片是以太幣的擴容方案中最複雜和最難實行的設計,為了確保分片能順利進行,分片會發生較後期的更新階段,給開發者充足的時間開發和測試。最新的分片提案和過往的已經有一些出入,更加以 Rollup 為中心來進行各種優化和升級,例 如在分片的設計方案上會更方便 Rollup 去調用數據。
    • Sharding is the process of splitting one blockchain into multiple blockchains known as shards. It makes the entire network more efficient as a single validator does not have to handle the workload alone.
    • Every validator maintains information related to “their” shard. These validators are also shuffled between shards regularly to avoid any kind of manipulation. The Beacon Chain is used for the communication and coordination of the shards.
    • The Beacon Chain is a ledger of accounts that conducts and coordinates the network of stakers. It isn't quite like the Ethereum Mainnet of today. It does not process transactions or handle smart contract interactions.
  • The Verge

    • The verge will implement what Buterin calls “Verkle trees” (a type of mathematical proof) and “stateless clients.” These technical upgrades will allow users to become network validators without having to store extensive amounts of data on their machines. In a proof-of-stake network, validators with locked-up or “staked” ETH confirm and verify transactions. In Buterin's view, the verge will be “great for decentralization.”
    • This upgrade involves a “powerful upgrade to Merkle proofs” which optimizes data storage for Ethereum nodes. It will also assist with Ethereum scaling, as it allows for a greater number of blockchain transactions while keeping the blockchain decentralized.
    • 在原來區塊鏈的設計中, 如果客戶端想要確認一個交易的狀態, 會需要用到 Merkle Proof, 而在引入 Verkle Tree 後, 因為所佔用的空間將大幅減少, 也令「Stateless Client」的概念變得可行。
    • 簡單來說 Stateless Clients 就是「不需要儲存所有狀態,卻能參與交易驗證」的角色,現在區塊鏈網絡裏所有的共識和驗證都是由全節點完成的,但有了 Stateless Clients 之後,將不再需要花大量的記憶體儲存相關的數據,令整條區塊鏈更有效率。
  • The Purge: 通過剔除歷史數據和消除技術債務,驗證者不再需要使用大量硬盤空間去進行驗證工作。

    • “The purge: trying to actually cut down the amount of space you have to have on your hard drive, trying to simplify the Ethereum protocol over time and not requiring nodes to store history,” Buterin said of the phase.
    • 現時以太坊的驗證者需要下載自 2014 年開始的整個以太坊交易歷史數據,佔用的記憶體空間太大,甚至還隨這時間過去而不斷增加。
    • The Purge 目的是要改變這一點,減少節點的存儲需求,甚至不需要節點儲存歷史數據,從而大大提高效率,增加 TPS。
  • The Splurge: 四個不同部分升級後的協調,旨在減少錯誤 (Bugs) 的出現和確保網絡能暢順運作。

Ethereum Layer 2

Scaling Ethereum without compromising on security or decentralization.

Layer 2 (L2) is a collective term to describe a specific set of Ethereum scaling solutions. A layer 2 is separate blockchain that extends Ethereum and inherits the security guarantees of Ethereum.

Now let's dig into it a bit more, and to do this we need to explain layer 1 (L1).

Layer 1 is the base blockchain. Ethereum and Bitcoin are both layer 1 blockchains because they are the underlying foundation that various layer 2 networks build on top of. Examples of layer 2 projects include "rollups" on Ethereum and the Lightning Network on top of Bitcoin. All user transaction activity on these layer 2 projects can ultimately settle back to the layer 1 blockchain.

Ethereum also functions as a data availability layer for layer 2s. Layer 2 projects will post their transaction data onto Ethereum, relying on Ethereum for data availability. This data can be used to get the state of the layer 2, or to dispute transactions on layer 2.

Ethereum as the layer 1 includes:

  1. A network of node operators to secure and validate the network
  2. A network of block producers
  3. The blockchain itself and the history of transaction data
  4. The consensus mechanism for the network

Why do we need layer 2?

Three desirable properties of a blockchain are that it is decentralized, secure, and scalable. The blockchain trilemma states that a simple blockchain architecture can only achieve two out of three. Want a secure and decentralized blockchain? You need to sacrifice scalability.

Ethereum has reached the network's current capacity with 1+ million transactions per day and high demand for each of these transactions. The success of Ethereum and the demand to use it has caused gas prices to rise substantially. Therefore the need for scaling solutions has increased in demand as well. This is where layer 2 networks come in.

Scalability

The main goal of scalability is to increase transaction speed (faster finality) and transaction throughput (higher transactions per second) without sacrificing decentralization or security.

The Ethereum community has taken a strong stance that it would not throw out decentralization or security in order to scale. Until sharding, Ethereum Mainnet (layer 1) is only able to process roughly 15 transactions per second. When demand to use Ethereum is high, the network becomes congested, which increases transaction fees and prices out users who cannot afford those fees. That is where layer 2 comes in to scale Ethereum today.

Rollups

Rollups are currently the preferred layer 2 solution for scaling Ethereum. By using rollups, users can reduce gas fees by up to 100x compared to layer 1.

Rollups bundle (or 'roll up') hundreds of transactions into a single transaction on layer 1. This distributes the L1 transaction fees across everyone in the rollup, making it cheaper for each user. Rollup transactions get executed outside of layer 1 but the transaction data gets posted to layer 1. By posting transaction data onto layer 1, rollups inherit the security of Ethereum. There are two different approaches to rollups: optimistic and zero-knowledge - they differ primarily on how this transaction data is posted to L1.


Credits

Blockchain Facts

Block (Blockchain Block)

Consensus Mechanism (Cryptocurrency)

How Does Bitcoin Mining Work?

The proof of work (PoW)

PoS

What is a 51% Attack

Ethereum Consensus Mechanism

Why Are Most dApps Built on Ethereum?

Merge, Surge, Verge, Purge, Splurge 到底是什麼?

Ethereum 2.0

Layer 2

Ethereum Merge? Get Ready for the 'Surge, Verge, Purge, and Splurge', Says Vitalik Buterin

blockchainethereumbitcoin24 min read