Uniswap V4 Hook + Brevis ZK Coprocessor = Data-driven DEX Experiences

[read_meter]

Brevis has supported Uniswap V4 hooks to trustlessly read and compute LPs’ and traders’ transaction history, and directly verify results in the hook contracts. This means that hook contracts can now implement dynamic data-driven features for how Uniswap pools, swaps, fees, and LP positions interact, all based on dynamic and trustless data computation. 

To clearly illustrate how Brevis works for a Uniswap hook, we walk you through the design and implementation of a VIP Trader Fee Discount hook we’ve built, and discuss other exciting use cases that can be built by combining Uniswap V4 Hooks and the Brevis ZK Coprocessor in an asynchronous computation design pattern. 

The Missing VIP Trader Program in DEXes

One notable distinction between centralized exchanges (CEXes) and decentralized exchanges (DEXes) lies in the existence of trading-volume-based fee structures, commonly referred to as “VIP trader loyalty programs”. These programs serve as potent tools for retaining traders, bolstering liquidity, and ultimately augmenting revenue for CEXes.

Interestingly, while every CEX offers at least one such program, DEXes are void of them. Why is this the case?

As it turns out, implementing this in DEXes is considerably more arduous and costly than in CEXes.

In a CEX, implementing a loyalty program is a straightforward process:

  1. Log all users’ trading history in a centralized database, a cost-effective task that facilitates easy retrieval in the future.
  2. On a monthly basis, execute a simple query on the highly efficient centralized database to get each user’s trading volume and determine fee tiers based on historical data.

However, DEXes encounter significant hurdles when attempting to replicate these steps:

  1. There is no customization capability in the architecture of existing DEXes to compose any additional customized business logic, such as charging different fees for different users. 
  2. For a DEX, recording every user’s trade in smart contracts for future query purposes means exorbitant storage costs, and it is even more expensive to do statistical queries and calculations on such trade data. Specifically, a smart contract can only easily and trustlessly access:
    • Data stored in the VM state (excluding transaction or event data).
    • Data from the most recent block (historical data access is constrained).
    • Data from other smart contracts that is made public via “view” functions (excluding private or internal contract data).

In addition, we cannot use the data generated by off-chain indexing solutions such as Dune Analytics because it will introduce additional trust in those external and often centralized indexing solutions. 

While it may appear counterintuitive, the truth is that it’s simply impractical to drive DEX features with only smart contracts, while allowing a DEX to access and compute substantial volumes of historical transaction data or states. For a more in-depth explanation, you can also refer to this article.

The Magic of Uniswap V4 Hook and the Brevis ZK Coprocessor

By leveraging both Uniswap V4 Hooks and Brevis, it’s now possible to enable DEXes with data-driven features to match CEX user experiences. 

Hooks are programmable plugins introduced in Uniswap V4 to add new features for liquidity pools. With hooks, pool deployers can introduce code that performs a designated action at key points throughout the pool’s lifecycle – like before or after a swap, or before or after an LP position is deployed or changed. 

Hooks make it possible to integrate logic customized to different groups of users and LPs, and solve the customization challenge mentioned above. 

With Brevis, we complete the second half of the puzzle. 

Brevis is a smart ZK coprocessor that empowers smart contracts to read from the full historical on-chain data, such as states, transactions, and events, from Ethereum and other chains, decode them with developer-specified logic, and run customizable computations in a completely trustless way. Blockchain can offload computation tasks to Brevis for fast and low-cost computation. Brevis then generates a ZK proof for the computation results, which can be seamlessly verified on-chain, providing a data-driven user experience for decentralized applications (dApps).

For example, in a VIP Trader Program we’ve built, periodically, Uniswap v4 can read a user’s historical transactions in the past 30 days, parse each trade event with customized logic, and compute the trading volume with Brevis. The trading volume and a ZK Proof generated by Brevis are then trustlessly verified in a Uniswap v4 Hook smart contract, which determines and records the user’s VIP fee tier asynchronously. 

After the proof verification, any future trades of an eligible user will trigger the getFee() function to simply look up the VIP record and reduce trading fees for them accordingly. 

To successfully push this into production use with large-scale data computation, Brevis leverages novel cryptography and system architecture designs that reduce the proving time significantly. Please refer to the last section for benchmark results. 

Note that in the demo, the proofs are generated on a per-user basis. We want to highlight that these proofs can be further aggregated across multiple users using solutions such as NEBRA to reduce the on-chain verification costs for each user. 

A New-era of Data-driven and Asynchronous Computation Design Patterns 

For Uniswap hooks, integrating with Brevis can mean a new way to design the trading fee structure of a pool, and create trustless loyalty programs, but this is just the tip of the iceberg. Brevis opens up opportunities for various other data-driven use cases in DeFi. 

Let’s look at another example: improving liquidity efficiency by redesigning the liquidity mining reward mechanisms. 

Presently, liquidity incentives on DEXes function on a “pay-as-you-go” model — farming rewards are directly distributed to LPs as they contribute liquidity. This model, however, is far from optimal. Sensing market volatility, expert farmers can promptly withdraw their liquidity to sidestep impermanent losses. In doing so, they offer minimal value to the protocol but reap disproportionately significant rewards.

The ideal liquidity incentive would retrospectively assess the steadfastness of LPs, especially during significant market fluctuations. Those who consistently support the pool during such times should receive the highest rewards. Yet, accessing historical LP behavior data, which is crucial for this model, remains unfeasible today with only smart-contract computation.

Similar to the trade-volume-based loyalty program described earlier, when combined with the Brevis ZK Coprocessor, it’s now possible to implement logic in Uniswap V4 Hooks to compute and prove historical LP behavior data in a trustless yet efficient way. 

Another prime example is in the domain of machine-learning-powered active liquidity management. Active liquidity management, potentially driven by AI, has been a hot topic. However, current solutions suffer from challenges such as centralized trust in the liquidity manager or exposure to private quantitative models. Combining Uniswap V4, Brevis, and ZK-ML solutions such as EZKL or Modulus Labs, one can build trust-free liquidity yield management products while maintaining full privacy of their proprietary liquidity management models. 

The list goes on. 

By combining Brevis and Uniswap V4 Hooks, developers enter a new era of asynchronous computation on DeFi where complex computation can be offloaded to ZK coprocessors to create efficient yet trustless features, and from here we can now build exciting data-driven user experiences on par with our Web 2 counterparts. 

Production-ready Scalability and Other Technical Details

Lastly, we want to provide a few technical notes. 

One of the biggest challenges in pushing ZK Coprocessing to large-scale production use is the high computation cost incurred by generating ZK Proofs of data access, raw data decoding and computation on large data. 

Brevis solves this challenge by building a high-performance parallel and distributed proving framework. We will release more details about this framework in the future. 

In our performance benchmark, we used a private cluster of servers combined with one public cloud instance: 

  • 100 servers with spec: GPU RTX 4090(24GB) + Intel(R) Xeon(R) Platinum 8352V CPU @ 2.10GHz + 90GB Memory
  • 1 of r7i.metal-48xl from Amazon EC2 (over-provisioned)

We leveraged the Icicle library from Ingonyama to achieve amazing GPU acceleration performance. 

On a 100-node prover cluster, it took 403s to generate a ZK Proof for the whole process of accessing 2600 Uniswap transactions, decoding the trade size of each transaction, and adding each decoded value up to the total trading volume. The computation cost for such a proof, based on the quote for short-term rental on the open market and computation time used, is roughly $2.5. 

We tested with 2600 transactions because during Q3 2023, among all wallets with monthly trading volume larger than $1M on the USDC-WETH pool, only 2% of them traded more than 2600 times. Therefore, the scalability provided by Brevis today is sufficient to handle use cases in production. However, the upper bound of the scalability of Brevis is significantly higher. 

We expect that the next release of our ZK prover framework will further reduce the latency and costs by an order of magnitude or more.

The smart contract code used in this demo is already open source. Brevis is a programmable platform and does not require developers to write ZK circuits. The following functional components will be released soon along with our V2.0 SDK:

  • API calls to access a list of Uniswap transactions
  • Business logic to decode trade events based on developer-specified data schemas 
  • Computation logic based on decoded data fields. 

Interested in building with Brevis?

We will help you get started! Reach out and get connected with a builder now: https://form.typeform.com/to/lduiliob.