Uniswap Code Analysis: 7 Practical Contract Development Tips

robot
Abstract generation in progress

Practical Tips for Contract Development: Lessons Learned from Uniswap Code

Recently, while developing a tutorial for a decentralized exchange, I referred to the code implementation of Uniswap V3 and learned many interesting insights. As a developer attempting to create Defi contracts for the first time, these tips will be very helpful for newcomers wanting to learn contract development.

Next, let's take a look at these practical tips, some of which can even be called clever tricks.

Web3 Beginner Series: Tips on Contract Development I Learned from Uniswap Code

Prediction Contract Deployment Address

In general, the address obtained from deploying a contract appears random because it is related to the nonce and is unpredictable. However, in certain scenarios, we need to infer the contract address through trading pairs and related information. This is useful in determining transaction permissions or obtaining pool addresses, among other situations.

Uniswap uses the CREATE2 method to create contracts, making the generated contract address predictable by adding a salt parameter. The logic for generating the new address is: hash("0xFF", creator address, salt, initcode). This method makes the contract address predictable, facilitating subsequent operations.

Web3 Beginner Series: Tips for Contract Development I Learned from Uniswap Code

Smart Use of Callback Functions

Contracts can call each other in Solidity. A common scenario is when method A calls method B, and B calls back to A in the method it was called. This can be very useful in certain situations.

Taking Uniswap as an example, when calling the swap method of the UniswapV3Pool contract to perform a transaction, it will call back swapCallback, passing in the tokens actually needed for this transaction that have been computed. The caller needs to transfer the required tokens into the UniswapV3Pool in the callback. This design ensures the complete execution and safety of the swap method without the need for cumbersome variable recording.

Using Exception to Pass Information, Implementing Transaction Estimation with Try Catch

In the Uniswap Quoter contract, the swap method of UniswapV3Pool is executed using a try-catch block. This is to simulate the swap method to estimate the tokens required for the transaction. Since no actual token exchange occurs during estimation, an error will be thrown. Uniswap throws a special error in the transaction callback function, then catches that error and parses the required information from it.

This method may seem like a shortcut, but it is very practical. It avoids the need to modify the swap method for estimating trading demand, making the logic more straightforward.

Web3 Beginner Series: Contract Development Tips I Learned from Uniswap Code

Solving Precision Issues with Big Numbers

Uniswap's code involves a large amount of computational logic, such as calculating the exchanged tokens based on the current price and liquidity. To avoid precision loss caused by division operations, Uniswap often uses "<< FixedPoint96.RESOLUTION" operation, which is a left shift of 96 bits, equivalent to multiplying by 2^96. By left shifting before performing division, it can ensure precision using uint256 in normal transactions without overflow, typically handling (.

Although there will still be a slight loss of precision in theory, this level of error is usually acceptable.

Calculate Earnings Using Share Method

Uniswap needs to record the fee earnings of liquidity provider ) for LP(. To avoid consuming a lot of Gas by recording fees for each LP with every transaction, Uniswap employs a clever method.

The Position structure defines feeGrowthInside0LastX128 and feeGrowthInside1LastX128, which record the fees due to each liquidity provider at the last fee withdrawal for each position. This allows for recording only the total fees and the fees to be allocated to each liquidity provider, enabling the calculation of withdrawable fees based on the liquidity held at the time of withdrawal. This is similar to a stock dividend mechanism, where one only needs to know the historical earnings per share and the earnings at the last withdrawal.

![Web3 Beginner Series: Contract Development Tips I Learned from Uniswap Code])https://img-cdn.gateio.im/webp-social/moments-45e66af69435e6d4412ae506e77ab893.webp(

Reasonable Selection of Information Acquisition Channels

On-chain storage is relatively expensive, so not all information needs to be on-chain or retrieved from the chain. For example, many interfaces called by the Uniswap front-end website are traditional Web2 interfaces.

The trading pool list, trading pool information, etc. can be stored in a regular database. Some data may need to be periodically synchronized from the chain, but there is no need to call the chain or node service's RPC interface in real-time to obtain relevant data.

Some blockchain RPC providers offer advanced interfaces that allow for faster and more cost-effective access to certain data. These interfaces typically use caching to enhance performance and efficiency.

Of course, key transactions still need to be conducted on-chain.

Learning Contract Splitting and Utilizing Existing Standard Contracts

A project may contain multiple contracts that are actually deployed. Even if there is only one contract actually deployed, we can maintain the contract by splitting it into multiple parts through inheritance.

For example, the NonfungiblePositionManager contract of Uniswap inherits multiple contracts. When implementing the ERC721Permit contract, it directly uses the @openzeppelin/contracts/token/ERC721/ERC721.sol contract. This not only facilitates position management through NFTs but also improves development efficiency by utilizing existing standard contracts.

Summary

Practicing by developing a simple decentralized exchange will allow you to gain a deeper understanding of the code implementation of Uniswap and learn more practical knowledge points from actual projects. I believe these skills will be very helpful for beginners who want to learn contract development.

![Web3 Beginner Series: Tips on Contract Development I Learned from Uniswap Code])https://img-cdn.gateio.im/webp-social/moments-f95ddc9d89809cf11dbe65b9bafda157.webp(

UNI-0.69%
View Original
This page may contain third-party content, which is provided for information purposes only (not representations/warranties) and should not be considered as an endorsement of its views by Gate, nor as financial or professional advice. See Disclaimer for details.
  • Reward
  • 7
  • Share
Comment
0/400
DataPickledFishvip
· 7h ago
Studying code again, my head hurts!
View OriginalReply0
PermabullPetevip
· 7h ago
It's starting, I don't understand these, I only know how to lose money.
View OriginalReply0
MEVSandwichVictimvip
· 7h ago
This CREATE2 is quite advanced, no wonder it's from uni.
View OriginalReply0
MrRightClickvip
· 7h ago
Hey, create2 is really amazing!
View OriginalReply0
PanicSeller69vip
· 7h ago
Even the code dogs shed tears.
View OriginalReply0
BearMarketBardvip
· 7h ago
Laoganma is really a bull.
View OriginalReply0
Deconstructionistvip
· 8h ago
I'm researching production code again, I'm struggling to keep up.
View OriginalReply0
Trade Crypto Anywhere Anytime
qrCode
Scan to download Gate app
Community
English
  • 简体中文
  • English
  • Tiếng Việt
  • 繁體中文
  • Español
  • Русский
  • Français (Afrique)
  • Português (Portugal)
  • Bahasa Indonesia
  • 日本語
  • بالعربية
  • Українська
  • Português (Brasil)