Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol

IntermediateMay 21, 2024
This article explains the concept of the Hooks programming model, which allows developers to insert custom code into the execution path of the system, application or library through predefined functions or code blocks, improving the scalability and customizability of the program. Uniswap V4 introduces Hooks, through which functions such as dynamic fees, on-chain price limit orders, and time-weighted average market makers can be implemented, enhancing the functions of DApp and the network effect of Uniswap.
Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol

What Are Hooks

Hooks, or Hook Programming, is a programming model that allows developers to insert custom code into the execution path of a system, application or library through Hooks, which are predefined functions or code blocks. There is no need to modify the original code. Hooks are often used in many programming environments and frameworks, such as operating systems, frameworks and libraries, web development, and plug-in systems.

By using Hooks, developers can increase the scalability and customizability of the program without having to modify the original code for every change or expansion requirement, which helps to keep the code clean and stable. Hooks provide an elegant implementation method for software extension and are a very useful programming model in software design.

In particular, AOP (Aspect-oriented Programming) is often compared with Hook programming. AOP is a modular programming paradigm that implements cross-cutting concerns, and the goal is not to change the main business logic. It enhances or modifies functionality if necessary. I won’t expand on AOP in detail here. You can simply think of AOP as a higher-level abstraction of HooK programming.

Uniswap V4: Hooks Revolution

In June 2023, Uniswap announced and made public a draft version of the Uniswap V4 white paper. An important feature of Uniswap V4 is the introduction of Hooks.

Hooks have been widely used in Web2 financial systems, because these systems usually require a high degree of customization and scalability. Customized scenarios, such as when processing transactions, use Hooks to insert additional verification logic before and after transaction execution, such as secondary verification, risk control detection, and anti-money laundering (AML) strategies. Scalability scenarios include integrating with external APIs or microservices through Hooks to expand new functions in the financial system, such as identity authentication services, exchange rate conversion, payment gateways, etc.But by introducing Hooks into DeFi, Uniswap has set a precedent.

Uniswap V4 Hooks is essentially an external contract created and defined by developers. When a liquidity pool is created, you can choose to bind a Hook contract. Afterwards, the liquidity pool will call the previously bound Hook contract to perform specified operations at different stages of the life cycle, providing a high degree of customization. Developers can use Uniswap’s Hooks to meet more personalized trading scenarios and build DApps with richer functions, such as:

  • Dynamic fees: Through Hooks, liquidity pools can dynamically adjust fees based on market volatility or other input parameters to better adapt to market conditions;
  • On-chain Limit Orders: Hooks can create and execute limit orders on the chain, allowing users to trade at specified prices;
  • Time Weighted Average Market Maker (TWAMM): Utilizes the Hooks mechanism to create a liquidity pool that supports the TWAMM strategy to evenly spread the transactions of large orders over a while. \

Currently, Uniswap V4 supports four groups of Hook callbacks, each group contains a pair of callbacks:

  • beforeInitialize/afterInitialize: Initialize the liquidity pool;
  • beforeModifyPosition/afterModifyPosition: add/reduce/remove liquidity;
  • beforeSwap/afterSwap: exchange;
  • beforeDonate/afterDonate: Donation (a new feature introduced by Uniswap V4, tip liquidity providers within the trading scope).

The following diagram illustrates the beforeSwap/afterSwap Hook process as presented in the whitepaper. It can be observed that before and after executing the swap, it first checks whether the corresponding flag of the liquidity pool’s Hook is enabled. If it is enabled, it will then call the corresponding functions of the Hook contract.

These Hooks can be executed before a trade begins and after a trade ends, enabling functionality similar to on-chain limit orders. The user places a limit order on the Hook contract, and then uses a custom or managed oracle in the afterSwap callback to determine whether the price meets the limit. If it does, the transaction will be executed. If it does not, the transaction will be cancelled.

Uniswap V4 deeply binds liquidity to the development of DApp itself through Hooks. It enhances the functions of DApp and also enhances the network effect of Uniswap, making it the underlying infrastructure of the entire DeFi ecosystem.

Security Issues of Uniswap V4 Hooks

The BlockSec team has explored the security risks of the Hooks mechanism in Uniswap V4. In addition to the fact that the Hook contract itself is malicious, benign Hook contracts are also extremely prone to vulnerabilities. The BlockSec team analyzed the Awesome Uniswap v4 Hooks repository (commit hash 3a0a444922f26605ec27a41929f3ced924af6075) and found that more than 30% of the projects in the repository were vulnerable. These vulnerabilities mainly originate from risk interactions between Hook, PoolManager and external third parties, and can be mainly divided into two categories:

  • Access control issues: The main concern is the callback functions in Uniswap V4. These functions should only be called by PoolManager and cannot be called by other addresses (including EOA and contracts). For example, in the case where rewards are distributed by pool keys, rewards may be claimed incorrectly if the corresponding function can be called by any account. Therefore, Hooks must establish strong access control mechanisms, especially since they can be called by other parties besides the pool itself;
  • Enter verification question: Various types of attacks, including well-known reentrancy attacks, result from improper input validation in some vulnerable Hook implementations. The most common situation is that untrusted external contracts are called in some key Hook functions. In order to attack these vulnerable Hooks, the attacker can register a malicious fund pool for his own fake tokens, and then call the Hook to use the funds. Pool performs operations. When interacting with the pool, the malicious token logic hijacks the control flow in order to engage in unwanted behavior.

Even if necessary access control to sensitive external/public functions is properly implemented and input parameters are verified to reduce the security risks related to the above two types of Hooks, the contract vulnerability itself cannot be completely avoided, especially if the Hook is upgradeable If the contract is implemented, you may also encounter related problems similar to OpenZeppelin’s UUPSUpgradeable vulnerability.

The reason lies in the fact that Hook programming increases the complexity of smart contracts, thereby enlarging the attack surface. For regular smart contracts, OpenZeppelin provides a series of best practice libraries to ensure that contracts developed based on it are secure. However, fundamentally, it adds “security usage constraints” for developers. In comparison, Hook contracts require even stricter “security usage constraints” than regular contracts. Therefore, for Hook programming to be widely applied, a comprehensive framework is needed: it requires a secure execution environment, applicable programming paradigms for Hooks, and stricter usage constraints.

Artela Aspect: Protocol-level Support for Hook Programming

Uniswap V4 Hooks are implemented through smart contracts, and its security issues are also caused by the limitations of smart contracts. Is there a solution that supports Hook programming from the protocol level? Artela Aspect gives us the answer!

Artela is a highly scalable and high-performance EVM-compatible Layer 1 blockchain network designed for developers to build modular, feature-rich, scalable and customizable applications. Artela defines a new programmable module as a native extension called Aspect, which innovatively introduces AOP into the blockchain network. Aspect needs to specify a connection point, that is, the location where Aspect is executed in the entire transaction processing life cycle. Similar to Hook’s callback, the connection points include:

  • Block Init
  • Transaction Verification
  • Pre Execute
  • Post Execute
  • Block Finalize

Aspect currently only supports TypeScript, and its code is compiled into WebAssembly (WASM) bytecode and deployed to the Artela network. After Aspect deployment, smart contract owners can bind their contracts with Aspect. A smart contract owner is defined as an external account (EOA) address that can pass the isOwner(address) returns (bool) check in the smart contract.

Subsequently, subsequent transactions calling the smart contract will be handled by Aspect, as shown in the diagram below:

As a protocol-level Hooks implementation, Artela Aspects has great advantages over Uniswap V4 Hooks:

First, Artela Aspects uses WASM to execute its code, and the execution efficiency is several orders of magnitude higher than EVM;

Secondly, Artela Aspects can hook the entire transaction life cycle, not just the core logic of DeFi, and can build DApps with richer functions;

Finally, and most importantly, Artela Aspects runs independently in a secure sandbox environment. This isolation ensures that the execution of Aspects will not affect the security of contract execution.

The isolation of Artela Aspects limits the mutual calls between the Hook contract as a normal contract and other external contracts, solving the stubborn problem of Uniswap V4 Hooks access control and input verification. For DeFi contracts like Uniswap, you can enjoy a faster, stronger and safer Hook experience by deploying it to Artela.

Summary

As a significant participant and leader in the DeFi industry, Uniswap has played a crucial role in driving industry progress and enhancing functionality. The introduction of Hooks in Uniswap V4 undoubtedly sets the direction for DEX development and is eagerly emulated by successors.

However, Uniswap V4 Hooks are limited by the inherent constraints of smart contracts. Regardless of how robust the protocol design is and how comprehensive the toolkits are, it cannot fundamentally prevent the mutual invocation between Hook contracts and external contracts, posing potential security vulnerabilities.

Artela, as a high-performance EVM-compatible Layer 1 blockchain network, has designed Aspect to run independently in WASM from the protocol’s inception, natively supporting Hook programming. This greatly enhances security, providing an advanced solution for DeFi protocols that consider security as paramount.

Statement:

  1. This article originally titled “Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol” is reproduced from [小猪Web3]. All copyrights belong to the original author [web3朱大胆]. If you have any objection to the reprint, please contact the Gate Learn team, the team will handle it as soon as possible.

  2. Disclaimer: The views and opinions expressed in this article represent only the author’s personal views and do not constitute any investment advice.

  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

What Are Hooks

Uniswap V4: Hooks Revolution

Security Issues of Uniswap V4 Hooks

Artela Aspect: Protocol-level Support for Hook Programming

Summary

Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol

IntermediateMay 21, 2024
This article explains the concept of the Hooks programming model, which allows developers to insert custom code into the execution path of the system, application or library through predefined functions or code blocks, improving the scalability and customizability of the program. Uniswap V4 introduces Hooks, through which functions such as dynamic fees, on-chain price limit orders, and time-weighted average market makers can be implemented, enhancing the functions of DApp and the network effect of Uniswap.
Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol

What Are Hooks

Uniswap V4: Hooks Revolution

Security Issues of Uniswap V4 Hooks

Artela Aspect: Protocol-level Support for Hook Programming

Summary

What Are Hooks

Hooks, or Hook Programming, is a programming model that allows developers to insert custom code into the execution path of a system, application or library through Hooks, which are predefined functions or code blocks. There is no need to modify the original code. Hooks are often used in many programming environments and frameworks, such as operating systems, frameworks and libraries, web development, and plug-in systems.

By using Hooks, developers can increase the scalability and customizability of the program without having to modify the original code for every change or expansion requirement, which helps to keep the code clean and stable. Hooks provide an elegant implementation method for software extension and are a very useful programming model in software design.

In particular, AOP (Aspect-oriented Programming) is often compared with Hook programming. AOP is a modular programming paradigm that implements cross-cutting concerns, and the goal is not to change the main business logic. It enhances or modifies functionality if necessary. I won’t expand on AOP in detail here. You can simply think of AOP as a higher-level abstraction of HooK programming.

Uniswap V4: Hooks Revolution

In June 2023, Uniswap announced and made public a draft version of the Uniswap V4 white paper. An important feature of Uniswap V4 is the introduction of Hooks.

Hooks have been widely used in Web2 financial systems, because these systems usually require a high degree of customization and scalability. Customized scenarios, such as when processing transactions, use Hooks to insert additional verification logic before and after transaction execution, such as secondary verification, risk control detection, and anti-money laundering (AML) strategies. Scalability scenarios include integrating with external APIs or microservices through Hooks to expand new functions in the financial system, such as identity authentication services, exchange rate conversion, payment gateways, etc.But by introducing Hooks into DeFi, Uniswap has set a precedent.

Uniswap V4 Hooks is essentially an external contract created and defined by developers. When a liquidity pool is created, you can choose to bind a Hook contract. Afterwards, the liquidity pool will call the previously bound Hook contract to perform specified operations at different stages of the life cycle, providing a high degree of customization. Developers can use Uniswap’s Hooks to meet more personalized trading scenarios and build DApps with richer functions, such as:

  • Dynamic fees: Through Hooks, liquidity pools can dynamically adjust fees based on market volatility or other input parameters to better adapt to market conditions;
  • On-chain Limit Orders: Hooks can create and execute limit orders on the chain, allowing users to trade at specified prices;
  • Time Weighted Average Market Maker (TWAMM): Utilizes the Hooks mechanism to create a liquidity pool that supports the TWAMM strategy to evenly spread the transactions of large orders over a while. \

Currently, Uniswap V4 supports four groups of Hook callbacks, each group contains a pair of callbacks:

  • beforeInitialize/afterInitialize: Initialize the liquidity pool;
  • beforeModifyPosition/afterModifyPosition: add/reduce/remove liquidity;
  • beforeSwap/afterSwap: exchange;
  • beforeDonate/afterDonate: Donation (a new feature introduced by Uniswap V4, tip liquidity providers within the trading scope).

The following diagram illustrates the beforeSwap/afterSwap Hook process as presented in the whitepaper. It can be observed that before and after executing the swap, it first checks whether the corresponding flag of the liquidity pool’s Hook is enabled. If it is enabled, it will then call the corresponding functions of the Hook contract.

These Hooks can be executed before a trade begins and after a trade ends, enabling functionality similar to on-chain limit orders. The user places a limit order on the Hook contract, and then uses a custom or managed oracle in the afterSwap callback to determine whether the price meets the limit. If it does, the transaction will be executed. If it does not, the transaction will be cancelled.

Uniswap V4 deeply binds liquidity to the development of DApp itself through Hooks. It enhances the functions of DApp and also enhances the network effect of Uniswap, making it the underlying infrastructure of the entire DeFi ecosystem.

Security Issues of Uniswap V4 Hooks

The BlockSec team has explored the security risks of the Hooks mechanism in Uniswap V4. In addition to the fact that the Hook contract itself is malicious, benign Hook contracts are also extremely prone to vulnerabilities. The BlockSec team analyzed the Awesome Uniswap v4 Hooks repository (commit hash 3a0a444922f26605ec27a41929f3ced924af6075) and found that more than 30% of the projects in the repository were vulnerable. These vulnerabilities mainly originate from risk interactions between Hook, PoolManager and external third parties, and can be mainly divided into two categories:

  • Access control issues: The main concern is the callback functions in Uniswap V4. These functions should only be called by PoolManager and cannot be called by other addresses (including EOA and contracts). For example, in the case where rewards are distributed by pool keys, rewards may be claimed incorrectly if the corresponding function can be called by any account. Therefore, Hooks must establish strong access control mechanisms, especially since they can be called by other parties besides the pool itself;
  • Enter verification question: Various types of attacks, including well-known reentrancy attacks, result from improper input validation in some vulnerable Hook implementations. The most common situation is that untrusted external contracts are called in some key Hook functions. In order to attack these vulnerable Hooks, the attacker can register a malicious fund pool for his own fake tokens, and then call the Hook to use the funds. Pool performs operations. When interacting with the pool, the malicious token logic hijacks the control flow in order to engage in unwanted behavior.

Even if necessary access control to sensitive external/public functions is properly implemented and input parameters are verified to reduce the security risks related to the above two types of Hooks, the contract vulnerability itself cannot be completely avoided, especially if the Hook is upgradeable If the contract is implemented, you may also encounter related problems similar to OpenZeppelin’s UUPSUpgradeable vulnerability.

The reason lies in the fact that Hook programming increases the complexity of smart contracts, thereby enlarging the attack surface. For regular smart contracts, OpenZeppelin provides a series of best practice libraries to ensure that contracts developed based on it are secure. However, fundamentally, it adds “security usage constraints” for developers. In comparison, Hook contracts require even stricter “security usage constraints” than regular contracts. Therefore, for Hook programming to be widely applied, a comprehensive framework is needed: it requires a secure execution environment, applicable programming paradigms for Hooks, and stricter usage constraints.

Artela Aspect: Protocol-level Support for Hook Programming

Uniswap V4 Hooks are implemented through smart contracts, and its security issues are also caused by the limitations of smart contracts. Is there a solution that supports Hook programming from the protocol level? Artela Aspect gives us the answer!

Artela is a highly scalable and high-performance EVM-compatible Layer 1 blockchain network designed for developers to build modular, feature-rich, scalable and customizable applications. Artela defines a new programmable module as a native extension called Aspect, which innovatively introduces AOP into the blockchain network. Aspect needs to specify a connection point, that is, the location where Aspect is executed in the entire transaction processing life cycle. Similar to Hook’s callback, the connection points include:

  • Block Init
  • Transaction Verification
  • Pre Execute
  • Post Execute
  • Block Finalize

Aspect currently only supports TypeScript, and its code is compiled into WebAssembly (WASM) bytecode and deployed to the Artela network. After Aspect deployment, smart contract owners can bind their contracts with Aspect. A smart contract owner is defined as an external account (EOA) address that can pass the isOwner(address) returns (bool) check in the smart contract.

Subsequently, subsequent transactions calling the smart contract will be handled by Aspect, as shown in the diagram below:

As a protocol-level Hooks implementation, Artela Aspects has great advantages over Uniswap V4 Hooks:

First, Artela Aspects uses WASM to execute its code, and the execution efficiency is several orders of magnitude higher than EVM;

Secondly, Artela Aspects can hook the entire transaction life cycle, not just the core logic of DeFi, and can build DApps with richer functions;

Finally, and most importantly, Artela Aspects runs independently in a secure sandbox environment. This isolation ensures that the execution of Aspects will not affect the security of contract execution.

The isolation of Artela Aspects limits the mutual calls between the Hook contract as a normal contract and other external contracts, solving the stubborn problem of Uniswap V4 Hooks access control and input verification. For DeFi contracts like Uniswap, you can enjoy a faster, stronger and safer Hook experience by deploying it to Artela.

Summary

As a significant participant and leader in the DeFi industry, Uniswap has played a crucial role in driving industry progress and enhancing functionality. The introduction of Hooks in Uniswap V4 undoubtedly sets the direction for DEX development and is eagerly emulated by successors.

However, Uniswap V4 Hooks are limited by the inherent constraints of smart contracts. Regardless of how robust the protocol design is and how comprehensive the toolkits are, it cannot fundamentally prevent the mutual invocation between Hook contracts and external contracts, posing potential security vulnerabilities.

Artela, as a high-performance EVM-compatible Layer 1 blockchain network, has designed Aspect to run independently in WASM from the protocol’s inception, natively supporting Hook programming. This greatly enhances security, providing an advanced solution for DeFi protocols that consider security as paramount.

Statement:

  1. This article originally titled “Evolution of DeFi Hooks: From Uniswap V4 Contract Security to Artela Native Protocol” is reproduced from [小猪Web3]. All copyrights belong to the original author [web3朱大胆]. If you have any objection to the reprint, please contact the Gate Learn team, the team will handle it as soon as possible.

  2. Disclaimer: The views and opinions expressed in this article represent only the author’s personal views and do not constitute any investment advice.

  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.

Start Now
Sign up and get a
$100
Voucher!
Create Account