This article will explore Worldcoin— a project that beckons us to comprehend its essence, components, and operational mechanics.
By now, we have been in the blockchain space for long enough that we don’t need to understand what a DEX is or what Uniswap is. Although, one thing we should know is that the Uniswap protocol has undergone significant upgrades and iterations, now leading to Uniswap v4. The v1 of this DEX was launched on mainnet in November 2018, and in March 2020, v2 came around. Let’s just go through the key differences between these two versions briefly. Uniswap v3, an upgrade to the Uniswap protocol, addresses the issue of capital inefficiency found in constant function market makers. It introduces the concept of concentrated liquidity, allowing liquidity providers to concentrate their liquidity in smaller price ranges, rather than providing liquidity across the entire price range. Now let’s take a look at key features of this version Liquidity providers in Uniswap v3 can concentrate their liquidity within specified price ranges. This allows for more efficient capital allocation and reduces the amount of capital at risk compared to earlier versions. Liquidity providers can create liquidity positions within the specified price ranges. When the market price moves outside of a position, the liquidity is converted entirely to the less valuable asset until the price moves back into the specified range or the position is updated. LPs do not earn fees or suffer impermanent loss when their liquidity is not active. Uniswap v3 introduced the concept of multiple pools for each token pair, each with a different swap fee. This allows for more customization and flexibility in fee structures. In this version of Uniswap, liquidity positions are represented by non-fungible tokens (NFTs) using the ERC721 standard. Each liquidity position is unique and represents a specific price range and fee tier chosen by the liquidity provider. Uniswap v3 introduces a governance mechanism where UNI token holders have the power to make decisions and changes to the protocol. The fee amount and fee tiers can be adjusted through governance. Uniswap v3 improves the price oracles by tracking the sum of log prices, which allows for more accurate computation of time-weighted average prices (TWAP). This is especially useful when multiple pools for the same token pair exist. Fees in Uniswap v3 are collected in the form of tokens, rather than in terms of liquidity. Liquidity providers can collect the tokens owed to them by burning their liquidity positions. These are some of the key features and changes introduced in Uniswap v3, aimed at providing more power and flexibility to liquidity providers while improving capital efficiency in automated market making. Uniswap is the most used DEX out of all the dexes available in web3. This statement is driven on the basis of the trading volume of DEXes. Uniswap shares the most market share [Dated: Aug, 10, 2023] The trading volume for DEXes in the last 7 days is $13B, out of which Uniswap alone has a total of $7.5B, giving it the highest rank in the 7 days volume trading metric. However, innovation never stops, does it? The community started to wonder about v4 soon after the launch of v3. And the much-anticipated version will launch in the near future. However, what it has to offer is already out in the open, with the draft code being public. The Uniswap team aims to empower the community by enabling anyone and everyone to contribute in this version. However, some architectural changes are already there, such as singleton contracts, hooks, and custom pools. In the rest of the article, I will explain what Uniswap v4 has to offer as per the draft whitepaper written in June 2023. First things first, Uniswap v3 focuses on customization and architectural changes for gas efficiency. Now, what are some factors in Uniswap v3 which could be targeted for gas efficiency? Uniswap V4 introduces different features for this purpose of optimization, let’s go through them one by one. In Uniswap v4, hooks are introduced as externally deployed contracts that allow for customization and flexibility in concentrated liquidity pools. These hooks execute developer-defined logic at specific points in a pool's execution, enabling integrators to create pools with custom functionalities. Some points to be noted regarding hooks in Uniswap v4 are as follows: When creating a pool in Uniswap v4, a hook contract can be specified. This hook contract contains custom logic that the pool will call during its execution. Uniswap v4 supports several hook callbacks The specific hook callbacks executed are determined by the address of the hook contract, allowing for expressive and gas-efficient customization. With hooks, a wide range of new features and functionalities can be implemented. For instance, developers can use hooks to execute large orders over time through a Time-Weighted Average Market Maker (TWAMM). This can be particularly useful for executing large trades without causing excessive price slippage. More examples include on-chain limit orders that fill at tick prices, volatility-shifting dynamic fees, mechanisms to internalize Miner Extractable Value (MEV) for liquidity providers, and custom oracle implementations. These functionalities can be complex. Uniswap v4 supports both swap fees and withdrawal fees, which hook contracts can manage. Swap fees can be either static or dynamically managed by a hook contract. The hook contract can allocate a percentage of the swap fees to itself or any other designated party. Withdrawal fees, on the other hand, cannot be set natively in the pool. To set a withdrawal fee, a hook contract must be set up to manage the fee, and the collected withdrawal fees are directed to the hook contract. Note: that the introduction of hooks in Uniswap v4 allows for increased customization and functionality but also adds complexity to the protocol. Proper consideration and design are required to ensure the hook contracts' security,integrity and interactions with the core Uniswap v4 protocol. In Uniswap v4, a significant architectural shift occurred with the singleton design pattern and the introduction of flash accounting. These changes brought about substantial improvements in efficiency and gas cost reduction. Previous versions of the Uniswap Protocol, including Uniswap v1 and v2, followed the factory/pool pattern. Each time a new token pair was created, a separate contract was deployed for that pair. This approach worked well but came with certain limitations and costs, especially as the number of token pairs grew. Every new contract deployment incurred additional gas costs and added to the overall complexity of the ecosystem. To address these concerns, Uniswap v4 embraced the singleton design pattern, where a single contract manages all pools. This design significantly reduced the cost of pool deployment by avoiding the creation of separate contracts for each token pair. Instead, all liquidity pools are now handled by a central contract, streamlining the management and maintenance of the protocol. As a result, pool deployment costs were reduced by a remarkable 99%. How does a single contract keep track of all pools? The contract assigns keys to the pool, and stores it’s state. When a new pool is initialized, the contract sets several crucial parameters, such as By utilizing this systematic approach and leveraging the pool IDs as keys, the contract efficiently manages and accesses relevant information for all pools, facilitating seamless decentralized exchange functionality across various token pairs and liquidity pools. Another key improvement in Uniswap v4 is the adoption of flash accounting. In previous versions of Uniswap, every operation, such as swapping or adding liquidity to a pool, involved external transfers of tokens. This meant that every operation required transferring tokens to complete the process, which could lead to multiple transfers and higher gas costs. In Uniswap v4, flash accounting was introduced to optimize this process. Instead of immediately transferring tokens during each operation, Uniswap v4 uses an internal net balance known as a delta to track changes. These deltas are updated throughout the operation but are only settled externally at the end of the transaction, using the new take() and settle() functions. This flash accounting mechanism simplifies complex pool operations, such as atomic swapping and adding liquidity. The pool's solvency is maintained by ensuring that no tokens are owed to the pool manager or caller at the end of the call. The introduction of flash accounting drastically reduces the number of external transfers required, leading to significant gas savings for users. The singleton design and the implementation of flash accounting have paved the way for improved routing across multiple Uniswap v4 pools. This is especially crucial with the introduction of hooks, which is expected to increase the number of pools. These architectural changes in Uniswap v4 have laid the foundation for a more scalable, cost-effective, and flexible decentralized exchange protocol, empowering liquidity providers and developers. In earlier versions, Uniswap v1 allowed trading pairs only between ETH and ERC-20 tokens. However, in Uniswap v2, native ETH pairs were removed due to complexities in implementation and concerns regarding liquidity fragmentation across WETH (Wrapped Ether) and ETH pairs. Introducing the singleton design pattern and flash accounting in Uniswap v4 mitigated these issues, making it possible to reintroduce native ETH pairs alongside WETH pairs. One of the significant advantages of native ETH pairs is the reduced gas cost for transfers. Sending native ETH incurs approximately half the gas cost of sending ERC-20 tokens. For native ETH, the gas cost is around 21,000 gas, while for ERC-20 tokens, it is typically around 40,000 gas. This cost difference can add up significantly, especially for users engaging in multiple transactions. In Uniswap v4, ERC-1155 accounting enables the minting and burning of singleton-implemented ERC-1155 tokens for additional token accounting purposes. This feature allows users to keep their tokens within the singleton contract and avoid frequent ERC-20 transfers to and from the contract. Simply put, instead of performing separate transfers for each ERC-20 token interaction, users can consolidate their token balances into ERC-1155 tokens, representing multiple token classes in a single contract. Uniswap v4 introduced separate governance fee mechanisms for swap fees and withdrawal fees. Swap Fees: Similar to Uniswap v3, governance in Uniswap v4 has the authority to elect to take a capped percentage of the swap fee on a specific pool. This means that a portion of the fees generated from trading activities within a pool can be directed to the governance address. Withdrawal Fees: Uniswap v4 introduces a new governance feature related to withdrawal fees. If hooks within a pool have chosen to enable withdrawal fees, governance can take up to a capped percentage of the collected withdrawal fees. Every version of Uniswap came forward with innovation, and the source code to each version is open source. The previous version of Uniswap are also out there although liquidity in each version varies as LPs moved to probably the more profitabel choice. Uniswap v4 demonstrates an intriguing synergy with some of the innovative DeFi protocols that have contributed to shaping the blockchain ecosystem. Notable among these are Balancer v2 Vaults and the concept of interactions in CowSwap, which share resemblances in certain aspects with Uniswap v4's architecture. Balancer v2 Vaults, which debuted on May 11, 2021, introducted the idea of segregating core token accounting, balance, and management logic from the specific functionalities tied to swaps, joins, and exits. This clear-cut distinction streamlines the structure of pool contracts, resulting in greater modularity and a laser focus on essential operations. On a similar note, CowSwap presents a distinct yet relevant approach. Particularly, when settlement occurs in CowSwap, it introduces a parameter named "interactions." This element encapsulates the concept of sending arbitrary calls to various smart contracts. Here, interactions serve as key steps between token transfers, executing multiple times to manage the flow effectively. CodeBlock taken from CowSwap’s smart contract: In the context of Uniswap v4, these intriguing concepts converge harmoniously. The Singleton contract architecture in Uniswap v4 mirrors the separation approach found in Balancer v2 Vaults. This segregation ensures that token accounting and management stand distinctly apart from the functional intricacies of swaps, enriching the protocol's efficiency and usability. Uniswap v4 assimilates the concept of interactions, similar to those found in CowSwap. Although the execution mechanism differs, Uniswap v4 introduces hooks before and after swap operations, which bear a resemblance to interactions in CowSwap's settlement process. This alignment brings greater flexibility and control to Uniswap v4's operations, allowing for custom logic to be injected at pivotal points. In essence, Uniswap v4 emerges as an amalgamation of these two innovative approaches. It harnesses the streamlined separation of core logic and functional elements from Balancer v2 Vaults while infusing the essence of interactions from CowSwap's settlement. Uniswap, a decentralized exchange (DEX) protocol, has gone through significant upgrades leading to Uniswap v4. Uniswap v1 supported ETH-based pairs, while Uniswap v2 added ERC20 token pairs and introduced other changes. Uniswap v3 introduced concentrated liquidity, multiple pools, non-fungible liquidity, and governance. Uniswap v4 brings further enhancements, including the introduction of hooks for customizable pools, singleton design for efficient pool management, and flash accounting for reduced gas costs. Native ETH support is reintroduced for lower gas fees. ERC-1155 accounting allows users to consolidate token balances. Governance can set fees for swaps and withdrawals. Uniswap remains the most used DEX in the web3 space. Finally, the article talks about how uniswap v4 singleton contract share similarities with Balancer, whereas the hooks share similarities with CowSwap.A Look Back on previous versions of Uniswap
Features Uniswap V1 Uniswap V2 Pair Creation ETH-based pairs Any ERC20 token pairs Routing Through ERC20/ETH pair Direct swaps between ERC20 tokens Liquidity Exposed to ETH in all pools Supports arbitrary ERC20 pairs Deterministic Address Non-deterministic addresses Deterministic addresses using CREATE2 opcode Flash Swaps Not supported Introduced flash swaps for borrowing liquidity Protocol Fee No protocol fee Introduced 0.05% protocol fee on trades Contract Re-Architecture Single pair contract Two-layer architecture with core and periphery Meta Transactions Not supported Introduced meta transactions Solidity Written in Vyper language Written in Solidity Fee Adjustment Fee deducted from output amount Fee deducted from both input and output amounts What v3 Offered
Concentrated Liquidity
Position Management
Multiple Pool Pairs
Non-fungible Liquidity
Governance
Oracles
Fee Collection
Uniswap v3: The Leading DEX
Uniswap V4: The Next Stage
Hooks
Action Hooks
Custom Functionality
Hook-Managed Fees
Singleton & Flash Accounting
Evolution to Singleton Design
Flash Accounting Implementation
Native ETH Support
ERC1155 Accounting
Governance Updates
Uniswap v4: Synergies From DeFi protocols
function settle(
IERC20[] calldata tokens,
uint256[] calldata clearingPrices,
GPv2Trade.Data[] calldata trades,
GPv2Interaction.Data[][3] calldata interactions
) external nonReentrant onlySolver {
executeInteractions(interactions[0]);
(
GPv2Transfer.Data[] memory inTransfers,
GPv2Transfer.Data[] memory outTransfers
) = computeTradeExecutions(tokens, clearingPrices, trades);
vaultRelayer.transferFromAccounts(inTransfers);
executeInteractions(interactions[1]);
vault.transferToAccounts(outTransfers);
executeInteractions(interactions[2]);
emit Settlement(msg.sender);
}
TL;DR
This article will explore Worldcoin— a project that beckons us to comprehend its essence, components, and operational mechanics.
In Part II of the Zero-Knowledge Cryptography Primer, we have explored the world of asymmetric cryptography and essential concepts like Diffie-Hellman, groups, and finite fields, delving into the fascinating realm of Elliptic Curve Cryptography
Uniswap v4 emerges as a DeFi pinnacle, with groundbreaking features. Hooks introduce customizable pool functions, while a singleton design streamlines pool management. Flash accounting optimizes gas efficiency, while native ETH support reduces transfer costs. ERC1155 accounting consolidates token balances, and enhanced governance empowers users. Notably, Uniswap v4 synergizes with Balancer v2 Vaults and CowSwap, reflecting modularity and interaction concepts. Uniswap's evolution continues, redefining DeFi's horizons.