owned this note
owned this note
Published
Linked with GitHub
# [PUBLIC] Proposal: On-Chain Automated Treasury Management
###### tags: `grant`
[toc]
**Proponent:** 12wWLUd5qMzLFGqBsMnHLVFeTuYJwuo5ygMAxuSywrBX1XSF
**Date:** 30.03.2023
**Requested DOT:** $494,500 ~ 80,999 DOT (EMA7)
**Short description:** TWAMM (Time Weighted Automated Market Maker) eliminates front-running vulnerabilities of traditional AMMs when executing large orders, especially in the context of passive procedures, such as governance. The proposed solution will be executed as a seamless extension to [pallet-asset-conversion](https://forum.polkadot.network/t/statemint-e-swap-discussion), thereby enhancing its capabilities as an embedded AMM.
**Contact:** William Freudenberger (william@k-f.co)
## Context of the Proposal
This grant is proposed by k/factory, a core development contributing to the [Centrifuge](http://centrifuge.io/) project. A team made of experienced Substrate builders and a well established project in the Polkadot/Kusama ecosystem.
We have already received and successfully delivered multiple grants:
1. We developed a Go-based RPC library for interacting with Substrate nodes ([GSRPC](https://github.com/centrifuge/go-substrate-rpc-client/)) as a Web3 Foundation grant in [Q3 2019](https://github.com/w3f/Grants-Program/blob/master/applications/index.md#%EF%B8%8F-wave-3---q3-2019) and maintenance coverage as one of the first [Polkadot treasury proposals](https://polkadot.polkassembly.io/motion/12) in Q3 2020.
2. We also built [an early bridge](https://github.com/ChainSafe/ChainBridge) together with ChainSafe in [Q1 2019](https://github.com/w3f/Grants-Program/blob/master/applications/index.md#%EF%B8%8F-wave-1---q1-2019) and [Q1 2020](https://github.com/w3f/Grants-Program/blob/master/applications/index.md#%EF%B8%8F-wave-5---q1-2020) which was funded by a Web3 Foundation grant.
3. Last but not least, [FUDGE](https://github.com/centrifuge/fudge) received a [Polkadot treasury grant](https://polkadot.polkassembly.io/treasury/184) In Q4 2022. This tool provides a simple and generic way to interact with and manipulate the database of a Substrate-based blockchain.
Moreover, the k/f team has contributed to the Substrate and other related repositories in numerous [pull requests](https://github.com/search?q=user%3Aparitytech+author%3Awischli+author%3Amustermeiszer+author%3Abranan+author%3Anunoalexande+author%3Alemunozm+author%3Amikiquantum+author%3Alucasvo+author%3Aofferijns+author%3Acdamian&type=pullrequests), [new issues](https://github.com/search?q=user%3Aparitytech+author%3Awischli+author%3Amustermeiszer+author%3Abranan+author%3Anunoalexande+author%3Alemunozm+author%3Amikiquantum+author%3Alucasvo+author%3Aofferijns+author%3Acdamian&type=issues) and [discussions](https://forum.polkadot.network/search?expanded=true&q=%40mustermeiszer). We have deep knowledge in distributed/decentralized applications, libp2p, Golang, Solidity and Ethereum overall, zkSNARKs, and tokenization of assets with NFTs and has been developing with Substrate since Summer 2019. Various team members have presented talks on Polkadot related events such as Sub0, AmsterDOT, Polkadot Decoded, or Polkadot Parachain Summit.
In recent months, we have engaged in several discussions with the System Parachains Team at Parity regarding the development of a Multi-Asset Treasury. Of particular importance was the need to execute substantial orders securely, without succumbing to front-running vulnerabilities. Given that Parity is presently interfacing a Multi-Asset Treasury based on [this discussion](https://github.com/paritytech/polkadot/issues/5293), we would like to proffer our proposed solution to this challenge.
### Team Members
The team working on this composed of
* William Freudenberger (Rust developer, TWAMM project lead)
* Jeroen Offerijns (CTO of k/factory)
* Frederik Gartenmeister (Rust developer)
* Branan Riley (Rust developer)
## Problem Statement
The [ongoing discussion](https://forum.polkadot.network/t/statemint-update-roadmap/1200/) about automated market makers (AMMs) in the Statemint roadmap is mainly focused on improving the user and custodian experience by allowing small atomic swaps natively and making Statemint a central hub for asset deposits. This addresses important pain points by enabling transaction fees to be paid in non-native tokens and facilitating interaction with the entire asset variety of the ecosystem without requiring to run custom nodes or infrastructure.
However, we believe that one aspect has been overlooked: the slow swaps of large volumes, which can be easily front-run or sandwiched. This is particularly relevant in the context of trades proposed through governance for use cases such as
1. Paying out treasury grants, bounties or even [salaries](https://github.com/paritytech/substrate/pull/13378) in less volatile currencies (ie. stablecoins).
2. Enabling parachains to build a DOT reserve which can be used to acquire a parachain lease, pay XCM fees, or [increase availability cores](https://forum.polkadot.network/t/parachain-scaling-by-parablock-splitting/341) during times of high demand (once supported).
3. Governance deciding to invest part of the treasury into a token to diversify their treasury
What we need is the opposite of what a traditional AMM provides: atomic swaps with immediate execution, even in relatively illiquid assets. A governance vote is unable to time the market and is highly predictable. Therefore, executing such a transaction as a market order on an AMM is problematic, as it will be guaranteed to be front-run. A better solution is to "dollar-cost-average" over a long period of time making it harder for price manipulation to affect the purchase.
## Solution
At Centrifuge, we have researched distinct approaches of how to achieve hard-to-front-run slower transactions. In our opinion, the most elegant solution is [TWAMM (Time Weighted Automated Market Maker](https://www.paradigm.xyz/2021/07/twamm). We are of the firm conviction that the implementation of this model represents the most efficacious approach for executing token swaps in the context of slower and passive procedures, such as governance.
### Time Weighted Average Market Maker
The TWAMM protocol represents a sophisticated advancement of the conventional constant product (Uniswap-v2 style) automated market maker (AMM) framework. It introduces a novel feature wherein users can split their orders into infinitely small fractions and execute them at each block interval. This feature addresses a significant shortcoming of traditional AMMs that encounter severe slippage issues when processing sizable orders, leaving them vulnerable to front-running tactics.
Furthermore, the inherent risk associated with executing transactions within a single block is nullified by the TWAMM protocol. By segmenting orders into hundreds of small units spread over a prolonged time frame, the slippage rate of the embedded AMM is markedly reduced, and the cost of price manipulation is exponentially elevated. Artificially manipulating prices over multiple blocks creates an opportunity for other traders to exploit the price-inflation tactic, which ultimately undermines the manipulative effort. This innovative solution offers an elegant means of executing large orders even in relatively illiquid markets. It is particularly well-suited for slow automated processes, such as governance-controlled treasury operations, that can effectively implement a dollar-cost averaging strategy over extended periods.
### Treasury Dashboard
Practically, to manage the treasury portfolio requires the ability to submit long-term swap orders to the TWAMM pallet, to swap between different tokens. Relying purely on polkadot.js will make this hard to manage for council members or, with gov v2, the relevant collective members.
Moreover, it is reasonable to anticipate the emergence of various treasuries beyond the primary DOT treasury in the future, such as those designated for the Fellowship and Ambassador programs, among others. These treasuries are likely to possess a unified logic situated in a centralized location, such as the pallet-treasury module on the Governance System (para-) chain. In addition, these treasuries may be granted authority to oversee assets on any other parachain that recognizes their corresponding origin. Consequently, holders of tokens will require an informative dashboard that presents all assets accessible within their treasury across the entirety of the network.
To simplify this, we aim to build a simple Treasury Dashboard, similar in vein to the existing [Staking Dashboard](https://staking.polkadot.network/#/overview). The goal would be to make a simple, open-source, easily self-hosted app that includes:
- An aggregated overview of a treasury portfolio consisting of
- The current on-chain treasury portfolio
- Optional remote treasury account portfolios
- An overview of proposed and currently being executed long-term swap orders for the treasury
- And a tool to easily submit new long-term swap orders for voting
Technically, the goal would be to make this work for a single Substrate chain that includes the `asset-conversion` and `twamm` pallets. Ideally we can make this work using XCM for retrieving asset data, but alternatively we look to making this work directly on `orml-tokens` and/or `assets`. If possible, this would use [the same design system](https://github.com/paritytech/polkadot-dashboard-ui) as the Staking Dashboard.
### Resources
* [pallet-asset-conversion](https://github.com/paritytech/substrate/pull/12984)
* [Original Paper](https://www.paradigm.xyz/2021/07/twamm)
* [Reference implementation](https://github.com/para-dave/twamm)
* [Mathematical details](https://docs.pulsarswap.com/advanced-topics/mathematical-principle-of-twamm)
## Breakdown Deliverables
### Milestone 1 - Implement TWAMM pallet for Substrate
Based on [Paradigm Paper](https://www.paradigm.xyz/2021/07/twamm).
#### Components
##### Embedded AMM
* Uses `pallet-asset-conversion`
* Provides basic AMM functionality such as liquidity providing, removing and swapping token pairs
* Triggers Virtual Order Execution of long-term orders on swap executions with configurable buffer period
##### Long-term Orders
* Splits orders into infinitely many infinitely small suborders for a given time interval
* Keeps track of Virtual Order Execution
* Orders can be canceled anytime
* By setting a minimum block duration, enables advancing state for multiple blocks in a single computation
##### Orderpool
* Abstraction for set of long-term orders which sell a token at a constant rate to the embedded AMM
* Serves as an order book which does not provide liquidity
* Handles distribution logic for proceeds from long-term order sales to the corresponding owner
#### Features
* Lazy updating of virtual trades since last interaction triggered by executing _normal_ asset swaps on the embedded AMM
* Pull-based approach of claiming proceeds: O(1) per asset
*Estimated hours: 950h*
*Estimated budget: 190,000$*
### Milestone 2: Protocol improvements
* Benchmark and optimize Virtual Order Execution data structures for Substrate such as utilizing Binary Search Trees
* Research supporting generic embedded AMMs such as Curve
* Add fuzzy tests
* Documentation
* Add runtime API calls to inform about
* Claimable proceeds for an order
* Aggregated order data for a given token
* Last Virtual Order Execution
*Estimated hours: 400h*
*Estimated budget: 80,000$*
### Milestone 3 - Security Audit
* Security audit from SR Labs
*Budget: 120,000$*
### Milestone 4 - Frontend development
* Setup react.js-based frontend
* Retrieve treasury overview data from on-chain and remote addresses
* Retrieve proposed swaps in governance
* Retrieve existing running swaps
* Submit new long-term swap orders
* Cancel long-term swap orders
* Document and make the frontend easy to self-host
*Estimated hours: 630h*
*Estimated budget: 94,500$*
## Budget Summary
This table provides a cost breakdown based on the milestones and deliverables above. Centrifuge charges $200 / hour of work for Substrate development and 150 $ / hour for frontend development.
| | | | Estimates |
| ------ |:----------------------- |:---------- | ------------ |
| **MS** | **Deliverable** | **Hours** | **Budget** |
| 1. | TWAMM implementation | 950 | $190,000 |
| 2. | Protocol improvements | 400 | $80,000 |
| 3. | External Security Audit | --- | $120,000 |
| 4. | Frontend development | 630 | $94,500 |
| | **Totals** | **1980** | **$494,500** |
## Payment Conditions
The grant is proposed to the Polkadot Treasury and as such, if granted, will be paid in DOT.
At the time of writing the total grant amount of $494,500 results in a total grant amount of 80,999 DOT, based on EMA7 March 30th, 2023 (source: [Subscan](https://polkadot.subscan.io/tools/charts?type=price)).
The full deliverable will be found on https://github.com/centrifuge/twamm/.