Uniswap Source Code Unveiled: 7 Smart Contract Development Tips to Help DeFi Newbies To da moon

robot
Abstract generation in progress

Contract Development Tips: Learning from Uniswap Source Code

Recently, while writing a tutorial on developing a decentralized exchange, I referred to the code implementation of Uniswap V3 and learned many valuable insights. As a developer trying to develop Defi contracts for the first time, these tips will be very helpful for beginners who want to learn about contract development.

Here are some little tips I've learned, some of which can even be considered clever tricks.

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

Predictable Contract Deployment Address

The contract deployed usually gets a seemingly random address, because it is related to the nonce, making the contract address difficult to predict. However, in certain scenarios, we can derive the contract address through the trading pair and related information. This is useful in situations such as determining trading permissions or obtaining pool addresses.

Uniswap creates contracts by adding a salt parameter and using CREATE2, making the created contract address predictable. The address generation logic is: new address = hash("0xFF", creator address, salt, initcode).

![Web3 Beginner Series: Tips for Contract Development I Learned from Uniswap Code](https://img-cdn.gateio.im/webp-social/moments-0aaa61a4d43aba7fdeddbc55e3665305.webp011928374656574839201

Clever Use of Callback Functions

In certain scenarios, Contract A calls a method of Contract B, and B calls back A in the method that is invoked. This approach is very practical.

For example, when trading using the swap method of the UniswapV3Pool contract in Uniswap, it will call back the swapCallback, passing in the calculated tokens actually needed for this transaction. The caller needs to transfer the required tokens to the UniswapV3Pool in the callback, rather than splitting the swap method into two parts for the caller to invoke. This ensures the security of the swap method, guaranteeing that the entire logic is executed completely, without the need for cumbersome variable records to ensure safety.

Use exception transmission to convey information, implement transaction estimation with try catch

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

This method seems to be a shortcut, but it is very practical. There is no need to modify the swap method for estimating trading demand, and the logic is simpler.

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

Using Big Numbers to Solve Precision Issues

The Uniswap code contains a large amount of computational logic, such as calculating the exchanged tokens based on the current price and liquidity. To avoid precision loss during division operations, the calculation process often uses the "<< FixedPoint96.RESOLUTION" operation, which is equivalent to shifting left by 96 bits, or multiplying by 2^96. After the left shift, division operations are performed to ensure precision under normal trading conditions without overflow.

Calculate Earnings Using Share Method

In Uniswap, it is necessary to record the fee income of LP) liquidity provider (. Obviously, it is not feasible to record the fees for each LP for every transaction, as this would consume a large amount of Gas.

Uniswap's solution is to record feeGrowthInside0LastX128 and feeGrowthInside1LastX128 in the Position structure, indicating the fees that each liquidity should receive at the last time they withdrew fees. It only needs to record the total fees and the fees to be allocated to each liquidity, which can be calculated based on the liquidity held when the LP withdraws. This is similar to holding company stocks, where you only need to know the company's historical earnings per share and the earnings at the last withdrawal to extract the profits.

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

Non-essential information does not need to be retrieved from the chain

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

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

Of course, key transactions must be conducted on-chain.

Reasonable Split of Contracts, Utilizing Existing Standard Contracts

A project may contain multiple contracts that are actually deployed. Even if only one contract is actually deployed, the code can be split into multiple contracts for maintenance through inheritance.

For example, Uniswap's NonfungiblePositionManager contract inherits from multiple contracts. When looking at the implementation of the ERC721Permit contract, it is found that it directly uses the @openzeppelin/contracts/token/ERC721/ERC721.sol contract. This not only facilitates managing positions through NFTs but also leverages existing standard contracts to improve development efficiency.

Summary

Practice is the best method of learning. Trying to implement a simplified version of a decentralized exchange by yourself can help you gain a deeper understanding of the code implementation of Uniswap and learn more practical knowledge points from real projects.

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

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
  • 8
  • Share
Comment
0/400
SchrodingerWalletvip
· 07-09 09:07
Too basic, I'm outta here~
View OriginalReply0
LiquidityWizardvip
· 07-08 13:06
Just copy it.
View OriginalReply0
PoolJumpervip
· 07-07 22:21
Contract pro help me!
View OriginalReply0
IntrovertMetaversevip
· 07-06 09:37
The contract is rolling in again.
View OriginalReply0
SerumSurfervip
· 07-06 09:37
The v3 source code is pretty impressive.
View OriginalReply0
FlyingLeekvip
· 07-06 09:36
Looks good, looking forward to being played for suckers.
View OriginalReply0
LiquidityWhisperervip
· 07-06 09:31
Finally able to understand the uniV3 code.
View OriginalReply0
GateUser-75ee51e7vip
· 07-06 09:10
This code is interesting.
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)