From 989fa1306bcbb39f58ad486c1304454c2827f955 Mon Sep 17 00:00:00 2001 From: Austin Chen Date: Sat, 11 Jun 2022 09:15:07 -0700 Subject: [PATCH] Implement Balancer math on Uv3 --- common/calculate-swap3.ts | 37 ++++++++++++++++++++++++++++++++++++- web/pages/swap.tsx | 8 +++++--- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/common/calculate-swap3.ts b/common/calculate-swap3.ts index f67b290d..4e648d75 100644 --- a/common/calculate-swap3.ts +++ b/common/calculate-swap3.ts @@ -162,7 +162,7 @@ export function addPosition( maxTick, deltaL ) - console.log(`Deducting required N: ${requiredN} and required Y: ${requiredY}`) + // console.log(`Deducting required N: ${requiredN} and required Y: ${requiredY}`) // Add liquidity as we pass through the smaller tick const minTickState = pool.tickStates[minTick] || { @@ -187,6 +187,41 @@ export function addPosition( return pool } +export function addBalancer(pool: Swap3Pool, p: number, deltaL: number) { + // TODO: math is borked, shouldn't be returning infinity + function tickL(tick: number) { + const q = 1 - p + return deltaL * 2 * p ** q * q ** p * 1.0001 ** ((p - 0.5) * tick) + } + + // See how much liquidity is provided at +/- 5pp around p + // const minTick = fromProb(p - 0.1) + // const maxTick = fromProb(p + 0.05) + const minTick = fromProb(0.000001) + const maxTick = fromProb(0.999999) + let totalN = 0 + let totalY = 0 + const stride = 300 + for (let t = minTick; t <= maxTick; t += stride) { + // console.log('liquidity at tick ', t, toProb(t), tickL(t)) + const { requiredN, requiredY } = calculateLPCost( + fromProb(p), + t, + t + stride, + tickL(t) + ) + totalN += requiredN + totalY += requiredY + // Add liquidity + addPosition(pool, t, t + stride, tickL(t)) + } + + console.log('rough number of ticks', (maxTick - minTick) / stride) + console.log(`Total N: ${totalN} and total Y: ${totalY}`) + grossLiquidity(pool) + return pool +} + // This also mutates the pool directly export function grossLiquidity(pool: Swap3Pool) { let liquidityGross = 0 diff --git a/web/pages/swap.tsx b/web/pages/swap.tsx index b347ab83..e0158f67 100644 --- a/web/pages/swap.tsx +++ b/web/pages/swap.tsx @@ -1,4 +1,5 @@ import { + addBalancer, addPosition, buyYes, calculateLPCost, @@ -203,8 +204,9 @@ export default function Swap() { tick: fromProb(0.3), tickStates: [], } - INIT_POOL = addPosition(INIT_POOL, -(2 ** 23), 2 ** 20, 100) - INIT_POOL = addPosition(INIT_POOL, fromProb(0.32), fromProb(0.35), 100) + INIT_POOL = addPosition(INIT_POOL, -(2 ** 23), 2 ** 20, 1) + // INIT_POOL = addPosition(INIT_POOL, fromProb(0.32), fromProb(0.35), 100) + INIT_POOL = addBalancer(INIT_POOL, 0.3, 100) INIT_POOL = grossLiquidity(INIT_POOL) const [pool, setPool] = useState(INIT_POOL) @@ -215,7 +217,7 @@ export default function Swap() { return ( {/* */} - + {/* */}