TWAMM Research: November 2022

The turmoil of the FTX saga has made it abundantly clear users simply cannot trust centralized custodial entities. This is a great time for building fully on-chain DeFi legos instead of inheriting the faults of TradFi for momentary convenience.

Future is DeFi

Auditable open-source code ensures that there are no secret back doors, non-liquidatable accounts, or misuse of user funds. DeFi protocols are guaranteed by code instead of backdoor dealings.

Attracting Large Order Flow

A big reason CEXs & OTC desks attract large order flows is because of the availability of novel trade execution schemes beyond the obvious reasons like MEV and gas fees. V1 of TWAMMs solves the non-custodial gas efficient DCA problem, and future versions will enable limit orders as well.

V1 TWAMM enables gasless on-chain DCA
V1 TWAMM enables gasless on-chain DCA

Segmenting Toxic Flow

Given the size & compute limitations of smart contracts, a single DEX cannot serve every single persona, retail, whale, protocol, institutions, etc. Uniswap and other atomic execution DEXs have done a great job of incentivizing for sub $200k trades.

Large trades ($4M+) are positive probs due to price insensitive flow from hackers (e.g. Nomad hack)

TWAMMs are the ideal on-chain complement to these tools for trades that are much larger and aren’t time sensitive such as peg maintenance, liquidations, & asset diversification.

Automating Trades On-Chain

Large firms write scripts and other one-off tools to duplicate what TWAMMs do inherently. The below order would simply translate to sell 2M ETH for USDC in 4M blocks.

TWAMMs automate the execution of such large orders by breaking the order into smaller pieces. Arbitrageurs correct asset prices as they deviate and source external liquidity. Liquidity providers earn swap fees plus MEV kickbacks, and the entire trade lifecycle stays on-chain.

Technical Updates

Contract optimizations since the last update took a turn towards reducing contract size while maintaining gas efficiency. Upon meeting a target size under 20kB and exhausting the pool of available optimization ideas, the development focus shifted towards numerical analysis. Specifically an analysis of the differentiating storage optimization of scaled proceeds at each block of virtual order execution. This analysis thus far is promising and indicates that the optimization can likely be used in a variety of operational conditions. Diagrams and gas savings are presented in the section on the numerical analysis below.

Optimizations

To reduce contract size while maintaining gas efficiency, a number of optimizations were employed, varying in effort and magnitude.

Perhaps the most drastic change was combining the code for withdrawing and canceling an order, employing simple predicates to effect cancel behavior when needed.

Other changes included:

  • Modifying the contracts interface to share setter functions of common types using enumerations.

  • Refactoring to simplify longer passages of code and use stack variables instead of memory.

  • Paying balancer fees, if enabled, for all operation branches within join and exit methods instead of for mint and burn branches.

  • Efficient increment and decrement methods for bit-packed variables based on usage pattern analysis.

The final change was modifying our use of the Solidity 0.7 compiler’s optimization passes from 10,000 down to only 1,000.

Results

The figures below show that the recent optimization efforts, starting at change iteration 39 up to 57 did not reduce gas efficiency in benchmark testing. However, these optimizations significantly reduced contract size to 19.316 kB, meeting the stated 20kB goal:

Figure 1.0:  Averaged gas use of the benchmark design for each change iteration. Note that change iteration 39 and beyond is the most recent work for the December update.
Figure 1.0: Averaged gas use of the benchmark design for each change iteration. Note that change iteration 39 and beyond is the most recent work for the December update.
Figure 2.0:  Contract Size for each change iteration. Note that change iteration 39 and beyond is the most recent work for the December update.
Figure 2.0: Contract Size for each change iteration. Note that change iteration 39 and beyond is the most recent work for the December update.

Noteworthy Failed Optimizations

Interestingly while the Solidity compiler is known to be most efficient when dealing with 256-bit native types, adding additional code to deal with smaller word lengths, extending this notion to boolean variables did not reduce contract size and resulted in slightly more gas use.

Another optimization that did not measure success in benchmarking was storing calculated values (fees, trade amounts) for executing virtual order loop iterations, only updating them on dependency changes. This resulted in increased average gas use by 0.2% - 0.37%. The conclusion from this experiment is that computing values use less gas than caching them in memory variables—for systems with fewer variables to store, the use of the stack over memory may have provided an advantage.

Numerical Analysis

The key optimization in our TWAMM contract is to combine the storage of scaled proceeds for every execute virtual order loop iteration. This implementation saves a significant amount of gas as shown in the table below, which compares the gas use of the contract with and without the storage optimization:

Table 1.0: Increase in gas use for benchmark design of Cron-Fi TWAMM contract when scaled proceeds storage optimization is removed.
Table 1.0: Increase in gas use for benchmark design of Cron-Fi TWAMM contract when scaled proceeds storage optimization is removed.

The results of Table 1.0 were useful in guiding the schedule and making a strong case for spending additional effort to analyze and incorporate the storage optimization if possible.

Analyzing the Storage Optimization Further

To aid in the numerical analysis of this optimization, a diagram of the TWAMM system’s implementation of the staking algorithm for one-half of the trading directions was constructed and is shown below in Figure 3.0. It was annotated with types, values, and concerns and is currently being used in conjunction with a scenario and limit tests to further complete the analysis:

Figure 3.0: Cron-Fi TWAMM contract diagram of staking algorithm implementation for one-half of the trading directions.
Figure 3.0: Cron-Fi TWAMM contract diagram of staking algorithm implementation for one-half of the trading directions.

The diagram of Figure 3.0 shows a number of considerations currently being analyzed for the contract’s production release:

  • The effect of scaling factor selection on the permissible range of different order sizes. For instance, what is the smallest order that can be entered before a larger order will eclipse it due to finite precision effects from scaling?

  • What is the best scaling factor value choice for current and expected instances of the Cron-Fi TWAMM contract?

  • What is the maximum disparity in reserves that can be supported by the current scaling factor? (Examining the system shows that a massive disparity in reserves results in amplification or attenuation of the input trade value, which stresses the scaling of the stored procedure. For instance, if the disparity exceeded 2^64, the resulting value would be clipped and incorrectly reduced due to finite precision losses. Obviously, 2^64 is an extreme example).

Another consideration is that the reduced range of the stored proceeds reduces the space upon which proceeds can be stored. If a trade is large enough or if the aggregation of trades is large enough, the resulting proceeds may overflow multiple times resulting in losses. An analysis of this scenario and when it can realistically be expected is being performed and may lead to an interface change that permits long-term swap users to specify blocks to withdraw up to, thus preventing losses.

Towards Production

Beyond the aforementioned numerical analysis concerns and investigations, the remainder of the contract needs to undergo further scrutiny, a battery of tests, and fuzzing before it will be ready for production. That will be the development focus this month.

White paper explaining our numerical analysis planned for early January
White paper explaining our numerical analysis planned for early January
Subscribe to 0x70626a
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.