evm/Pool/Foundation

examples/evm/Pool/Foundation.omg

examples/evm/Pool/Foundation.omg1731 lines
1{-  The pool's pure transition functions and their kernel-checked laws.
2    The pricing formulas are defined once over arithmetic operations.
3    The contract instantiates them at Word 256. The proofs use exact
4    natural arithmetic and show where the two instances agree.
5-}
6let A = std:Arith
7let E = std:Equal
8let R = std:Ring
9
10let cap = std:Natural.pow2 112
11let locked = 1000
12let fee = 997
13let whole = 1000
14
15let Arithmetic =
16      \(t : Type) -> { lit : Natural -> t, add : t -> t -> t, mul : t -> t -> t, div : t -> t -> t }
17
18let naturals
19    : Arithmetic Natural
20    = { lit = \(v : Natural) -> v, add = Natural/plus, mul = Natural/times, div = Natural/div }
21
22let words
23    : Arithmetic (Word 256)
24    = { lit = Word/fromNatural 256, add = Word/add, mul = Word/mul, div = Word/div }
25
26let swapTerms =
27      \{t : Type} (ops : Arithmetic t) (a y x : t) ->
28        let effective = ops.mul (ops.lit fee) a
29        in  { numerator = ops.mul effective y
30            , denominator = ops.add (ops.mul (ops.lit whole) x) effective
31            }
32
33let quoteSwap =
34      \{t : Type} (ops : Arithmetic t) (a y x : t) ->
35        let terms = swapTerms @t ops a y x
36        in  ops.div terms.numerator terms.denominator
37
38let quoteShare =
39      \{t : Type} (ops : Arithmetic t) (a total reserve : t) -> ops.div (ops.mul a total) reserve
40
41let swapOut : Natural -> Natural -> Natural -> Natural = quoteSwap @Natural naturals
42let swapNumerator = \(a y x : Natural) -> (swapTerms @Natural naturals a y x).numerator
43let sharePriceOf : Natural -> Natural -> Natural -> Natural = quoteShare @Natural naturals
44
45let lit = words.lit
46let capWord = lit cap
47let lowWord = \(packed : Word 256) -> Word/mod packed capWord
48let highWord = \(packed : Word 256) -> Word/shr 112 packed
49let packWord = \(r0 r1 : Word 256) -> Word/add r0 (Word/shl 112 r1)
50let swapWord : Word 256 -> Word 256 -> Word 256 -> Word 256 = quoteSwap @(Word 256) words
51let shareWord : Word 256 -> Word 256 -> Word 256 -> Word 256 = quoteShare @(Word 256) words
52
53let minted
54    : Word 256 -> Word 256 -> Word 256
55    = \(p0 : Word 256) (p1 : Word 256) -> if Word/lt p0 p1 then p0 else p1
56
57-- The square root the first deposit uses, seven Newton steps from a power
58-- of two above the root, then one step back if the last one overshot.
59let isqrt
60    : Word 256 -> Word 256
61    = \(n : Word 256) ->
62        let bits = std:Natural.minus 256 (Word/clz n)
63        let seed = Word/shl (Natural/div (bits + 1) 2) (lit 1)
64        let z = std:Natural.fold 7 (\(z : Word 256) -> Word/shr 1 (Word/add z (Word/div n z))) seed
65        in  Word/sub z (if Word/lt (Word/div n z) z then lit 1 else lit 0)
66
67-- The operation takes reserves in trade order. The direction only decides
68-- which stored reserve and token the handler supplies in each position.
69let swap =
70      \(amount minOut x y : Word 256) ->
71        let out = swapWord amount y x
72        let reserveIn = Word/add x amount
73        in  { out
74            , liquid = Word/lt out y
75            , meetsMinimum = std:Bool.not (Word/lt out minOut)
76            , fits = Word/lt reserveIn capWord
77            , reserveIn
78            , reserveOut = Word/sub y out
79            }
80
81let deposited =
82      \(a0 a1 x y : Word 256) ->
83        let reserve0 = Word/add x a0
84        let reserve1 = Word/add y a1
85        in  { reserve0
86            , reserve1
87            , fits = Word/lt reserve0 capWord && Word/lt reserve1 capWord
88            }
89
90let initialMint =
91      \(a0 a1 : Word 256) (findRoot : Word 256 -> Word 256) ->
92        let product = Word/mul a0 a1
93        let root = findRoot product
94        let next = Word/add root (lit 1)
95        in  { total = root
96            , minted = Word/sub root (lit locked)
97            , validRoot =
98                Word/lt root capWord
99                && (std:Bool.not (Word/lt product (Word/mul root root))
100                    && Word/lt product (Word/mul next next))
101            , aboveLock = Word/lt (lit locked) root
102            }
103
104let liveMint =
105      \(a0 a1 x y total : Word 256) ->
106        let shares = minted (shareWord a0 total x) (shareWord a1 total y)
107        in  { minted = shares, total = Word/add total shares }
108
109let hasMinted = \(shares : Word 256) -> Word/lt (lit 0) shares
110
111let credit = \(held minted : Word 256) -> Word/add held minted
112
113let keepsLock =
114      \(amount total : Word 256) -> std:Bool.not (Word/lt total (Word/add amount (lit locked)))
115
116let burn =
117      \(amount x y total held : Word 256) ->
118        let amount0 = shareWord amount x total
119        let amount1 = shareWord amount y total
120        in  { covered = std:Bool.not (Word/lt held amount)
121            , amount0
122            , amount1
123            , reserve0 = Word/sub x amount0
124            , reserve1 = Word/sub y amount1
125            , total = Word/sub total amount
126            , held = Word/sub held amount
127            }
128
129let Transition =
130      { cap
131      , locked
132      , capWord
133      , lit
134      , low = lowWord
135      , high = highWord
136      , pack = packWord
137      , swapOut = swapWord
138      , sharePrice = shareWord
139      , minted
140      , swap
141      , deposited
142      , initialMint
143      , isqrt
144      , liveMint
145      , hasMinted
146      , credit
147      , keepsLock
148      , burn
149      }
150
151let low = \(r : Natural) -> Natural/mod r cap
152
153let high = \(r : Natural) -> Natural/div r cap
154
155let pack = \(r0 : Natural) (r1 : Natural) -> r0 + r1 * cap
156
157{-  halves: the low half of a packed word is its first reserve and the high
158    half its second, each below the cap.  A swap writes `pack x1 y1` and the
159    next call reads `x1` and `y1` back out of it.
160-}
161let Halves =
162      forall (h : A.NatFacts) (r0 r1 : Natural)
163      -> A.Lt r0 cap
164      -> A.Lt r1 cap
165      -> (low (pack r0 r1) === r0) * (high (pack r0 r1) === r1)
166
167let halves
168    : Halves
169    = \h r0 r1 below0 below1 ->
170        let split = A.divModPlusTimes h r0 (Natural/subtract 1 cap) r1
171
172        let lowHalf
173            : Natural/mod (pack r0 r1) cap === r0
174            = E.trans split.2 (A.modOfLt h r0 (Natural/subtract 1 cap) below0)
175
176        let highHalf
177            : Natural/div (pack r0 r1) cap === r1
178            = E.trans
179                split.1
180                (E.cong (\(m : Natural) -> m + r1) (A.divOfLt h r0 (Natural/subtract 1 cap) below0))
181
182        in  (lowHalf, highHalf)
183
184{-  wordFits: two reserves below the cap pack into a word below `cap * cap`,
185    the bound the handler's `uint112` pairs need: the sum `r0 + r1 * cap` is
186    less than `cap * cap` because each half is.
187-}
188let WordFits =
189      forall (h : A.NatFacts) (r0 r1 : Natural)
190      -> A.Lt r0 cap
191      -> A.Lt r1 cap
192      -> A.Lt (pack r0 r1) (cap * cap)
193
194let wordFits
195    : WordFits
196    = \h r0 r1 low0 low1 ->
197        let shifted
198            : r0 + 1 + r1 * cap === r0 + r1 * cap + 1
199            = R.ring
200                h
201                [ r0, r1 ]
202                (R.add (R.add (R.var 0) (R.const 1)) (R.mul (R.var 1) (R.const cap)))
203                (R.add (R.add (R.var 0) (R.mul (R.var 1) (R.const cap))) (R.const 1))
204                refl
205
206        -- the first half is below the cap, so the sum is below cap * (1 + r1)
207        let first
208            : A.Le (r0 + r1 * cap + 1) (cap + r1 * cap)
209            = A.eqTransLe
210                (r0 + r1 * cap + 1)
211                (r0 + 1 + r1 * cap)
212                (cap + r1 * cap)
213                (E.sym shifted)
214                (A.lePlus (r0 + 1) cap (r1 * cap) (r1 * cap) low0 (A.leRefl (r1 * cap)))
215
216        let regrouped
217            : cap + r1 * cap === (r1 + 1) * cap
218            = R.ring
219                h
220                [ r0, r1 ]
221                (R.add (R.const cap) (R.mul (R.var 1) (R.const cap)))
222                (R.mul (R.add (R.var 1) (R.const 1)) (R.const cap))
223                refl
224
225        -- and the second half too, so both are below cap * cap
226        let second
227            : A.Le (cap + r1 * cap) (cap * cap)
228            = A.eqTransLe
229                (cap + r1 * cap)
230                ((r1 + 1) * cap)
231                (cap * cap)
232                regrouped
233                (A.leTimesRight h (r1 + 1) cap cap low1)
234
235        in  A.leTrans (r0 + r1 * cap + 1) (cap + r1 * cap) (cap * cap) first second
236
237{-  kcore: with `x = u + 1 > 0`, the floor of the output's division by
238    `D = 1000 * x + 997 * a` is at most the swapNumerator without the fee: from
239    `out * D <= 997 * a * y` and `997 * x + 3 * x = 1000 * x`,
240    `(x + a) * out <= a * y`.
241-}
242let feeGap = Natural/subtract fee whole
243let wholePred = Natural/subtract 1 whole
244
245let KCore =
246      forall (h : A.NatFacts) (u a y out : Natural)
247      -> A.Le (out * (whole * (u + 1) + fee * a)) (fee * a * y)
248      -> A.Le ((u + 1 + a) * out) (a * y)
249
250let kcore
251    : KCore
252    = \h u a y out floor ->
253        let X = u + 1 + a
254
255        let D = whole * (u + 1) + fee * a
256
257        -- fee * X <= D, with the difference feeGap * (u + 1)
258        let e1 : fee * X === fee * (u + 1) + fee * a = A.distribLeft h fee (u + 1) a
259
260        let e2
261            : fee * (u + 1) + feeGap * (u + 1) === whole * (u + 1)
262            = E.trans
263                (E.cong (\(t : Natural) -> t + feeGap * (u + 1)) (A.timesComm h fee (u + 1)))
264                (E.trans
265                   (E.cong (\(t : Natural) -> (u + 1) * fee + t) (A.timesComm h feeGap (u + 1)))
266                   (E.trans
267                      (E.sym (A.distribLeft h (u + 1) fee feeGap))
268                      (A.timesComm h (u + 1) whole)))
269
270        let short
271            : fee * X + feeGap * (u + 1) === D
272            = E.trans
273                (E.cong (\(t : Natural) -> t + feeGap * (u + 1)) e1)
274                (E.trans
275                   (A.plusAssoc (fee * (u + 1)) (fee * a) (feeGap * (u + 1)))
276                   (E.trans
277                      (E.cong
278                         (\(t : Natural) -> fee * (u + 1) + t)
279                         (A.plusComm (fee * a) (feeGap * (u + 1))))
280                      (E.trans
281                         (E.sym (A.plusAssoc (fee * (u + 1)) (feeGap * (u + 1)) (fee * a)))
282                         (E.cong (\(t : Natural) -> t + fee * a) e2))))
283
284        let discount : A.Le (fee * X) D = (feeGap * (u + 1), short)
285
286        -- multiply the floor by X: X * (out * D) <= X * (fee * a * y)
287        --   = (fee * X) * (a * y) <= D * (a * y)
288        let s1
289            : A.Le (X * (out * D)) (X * (fee * a * y))
290            = A.leTimesLeft h (out * D) (fee * a * y) X floor
291
292        let r1
293            : X * (fee * a * y) === fee * X * (a * y)
294            = E.trans
295                (E.cong (\(t : Natural) -> X * t) (A.timesAssoc h fee a y))
296                (E.trans
297                   (E.sym (A.timesAssoc h X fee (a * y)))
298                   (E.cong (\(t : Natural) -> t * (a * y)) (A.timesComm h X fee)))
299
300        let s2
301            : A.Le (fee * X * (a * y)) (D * (a * y))
302            = A.leTimesRight h (fee * X) D (a * y) discount
303
304        let s3
305            : A.Le (X * out * D) (a * y * D)
306            = A.eqTransLe
307                (X * out * D)
308                (X * (out * D))
309                (a * y * D)
310                (A.timesAssoc h X out D)
311                (A.leTransEq
312                   (X * (out * D))
313                   (D * (a * y))
314                   (a * y * D)
315                   (A.leTrans
316                      (X * (out * D))
317                      (fee * X * (a * y))
318                      (D * (a * y))
319                      (A.leTransEq (X * (out * D)) (X * (fee * a * y)) (fee * X * (a * y)) s1 r1)
320                      s2)
321                   (A.timesComm h D (a * y)))
322
323        -- D = (whole * u + fee * a + wholePred) + 1, a positive factor: cancel it
324        let successor
325            : D === whole * u + fee * a + wholePred + 1
326            = E.cong (\(t : Natural) -> t + fee * a) (A.distribLeft h whole u 1)
327
328        let s4
329            : A.Le
330                (X * out * (whole * u + fee * a + wholePred + 1))
331                (a * y * (whole * u + fee * a + wholePred + 1))
332            = E.subst (\(t : Natural) -> A.Le (X * out * t) (a * y * t)) successor s3
333
334        in  A.leTimesCancel h (X * out) (a * y) (whole * u + fee * a + wholePred) s4
335
336{-  swapKeepsK: the product of the reserves does not decrease.  The floor
337    gives `out * D <= 997 * a * y`, kcore gives `(x + a) * out <= a * y`,
338    hence `out <= y`, and `(x + a) * (y - out) = x * y + a * y - (x + a) * out`.
339-}
340let SwapKeepsK =
341      forall (h : A.NatFacts) (u a y : Natural)
342      -> A.Le ((u + 1) * y) ((u + 1 + a) * Natural/subtract (swapOut a y (u + 1)) y)
343
344let swapKeepsK
345    : SwapKeepsK
346    = \h u a y ->
347        let X = u + 1 + a
348
349        let D = whole * (u + 1) + fee * a
350
351        let out = swapOut a y (u + 1)
352
353        let s = Natural/subtract out y
354
355        let rX = R.add (R.add (R.var 0) (R.const 1)) (R.var 1)
356
357        let rY = R.add (R.var 2) (R.var 3)
358
359        let expand
360            : (u + 1) * (s + out) + a * (s + out) === X * s + X * out
361            = R.ring
362                h
363                [ u, a, s, out ]
364                (R.add (R.mul (R.add (R.var 0) (R.const 1)) rY) (R.mul (R.var 1) rY))
365                (R.add (R.mul rX (R.var 2)) (R.mul rX (R.var 3)))
366                refl
367
368        -- X * out + e = a * y, the difference e a variable
369        in  A.leElim
370              (X * out)
371              (a * y)
372              (kcore h u a y out (A.divTimesLe h (swapNumerator a y (u + 1)) D))
373              (\e (paid : X * out + e === a * y) ->
374                 -- out <= y, since X * out <= a * y <= X * y
375                 let below
376                     : A.Le out y
377                     = A.leTimesCancel
378                         h
379                         out
380                         y
381                         (u + a)
382                         (A.eqTransLe
383                            (out * X)
384                            (X * out)
385                            (y * X)
386                            (A.timesComm h out X)
387                            (A.leTrans
388                               (X * out)
389                               (a * y)
390                               (y * X)
391                               (e, paid)
392                               (A.leTransEq
393                                  (a * y)
394                                  (X * y)
395                                  (y * X)
396                                  (A.leTimesRight h a X y (A.lePlusLeft (u + 1) a))
397                                  (A.timesComm h X y))))
398
399                 let wholeSum : s + out === y = A.subtractOfLe h out y below
400
401                 let rest
402                     : X * out + e === a * (s + out)
403                     = E.trans paid (E.cong (\(t : Natural) -> a * t) (E.sym wholeSum))
404
405                 let sum
406                     : (u + 1) * (s + out) + e + X * out === X * s + X * out
407                     = E.trans
408                         (A.plusSwapRight ((u + 1) * (s + out)) e (X * out))
409                         (E.trans
410                            (A.plusAssoc ((u + 1) * (s + out)) (X * out) e)
411                            (E.trans
412                               (E.cong (\(t : Natural) -> (u + 1) * (s + out) + t) rest)
413                               expand))
414
415                 let gained
416                     : (u + 1) * (s + out) + e === X * s
417                     = A.plusCancelRight ((u + 1) * (s + out) + e) (X * s) (X * out) sum
418
419                 in  E.subst (\(t : Natural) -> A.Le ((u + 1) * t) (X * s)) wholeSum (e, gained))
420
421{-  removalPays: a removal hands out `sh * x / L` and `sh * y / L` for a
422    share count `sh` that the handler has checked against the total `L`, and
423    neither is more than the reserve it comes from: the reserves it writes
424    back never go below zero.
425-}
426let RemovalPays =
427      forall (h : A.NatFacts) (sh x total : Natural)
428      -> A.Le sh (total + 1)
429      -> A.Le (Natural/div (sh * x) (total + 1)) x
430
431let removalPays
432    : RemovalPays
433    = \h sh x total held ->
434        let quotient = Natural/div (sh * x) (total + 1)
435
436        let bounded
437            : A.Le (sh * x) ((total + 1) * x)
438            = A.leTimesRight h sh (total + 1) x held
439
440        let floor : A.Le (quotient * (total + 1)) (sh * x) = A.divTimesLe h (sh * x) (total + 1)
441
442        in  A.leTimesCancel
443              h
444              quotient
445              x
446              total
447              (A.leTrans
448                 (quotient * (total + 1))
449                 (sh * x)
450                 (x * (total + 1))
451                 floor
452                 (A.leTransEq
453                    (sh * x)
454                    ((total + 1) * x)
455                    (x * (total + 1))
456                    bounded
457                    (A.timesComm h (total + 1) x)))
458
459-- Truncated subtraction is below its minuend.
460let below
461    : forall (h : A.NatFacts) (a b : Natural) -> A.Le a b -> A.Le (Natural/subtract a b) b
462    = \h a b p -> (a, A.subtractOfLe h a b p)
463
464{-  firstMint: the first deposit mints `root - 1000`, and the handler's
465    `1000 < root` check makes that at least one share.
466-}
467let FirstMint =
468      forall (h : A.NatFacts) (root : Natural)
469      -> A.Lt locked root
470      -> A.Lt 0 (Natural/subtract locked root)
471
472let firstMint
473    : FirstMint
474    = \h root above ->
475        -- root = locked + 1 + d, so gained + locked = locked + (1 + d)
476        A.leElim
477          (locked + 1)
478          root
479          above
480          (\d (sum : locked + 1 + d === root) ->
481             let gained
482                 : Natural/subtract locked root === 1 + d
483                 = A.plusCancelLeft
484                     (Natural/subtract locked root)
485                     (1 + d)
486                     locked
487                     (E.trans
488                        (A.subtractOfLe h locked root (A.leOfLt locked root above))
489                        (E.sym sum))
490
491             in  E.subst (\(t : Natural) -> A.Le 1 t) (E.sym gained) (d, refl))
492
493{-  burnHeld: the removal takes `sh` from the caller's balance, which the
494    handler has checked it holds, and putting it back gives the balance: the
495    share accounting of a removal is exact.
496-}
497let BurnHeld =
498      forall (h : A.NatFacts) (holding sh : Natural)
499      -> A.Le sh holding
500      -> Natural/subtract sh holding + sh === holding
501
502let burnHeld
503    : BurnHeld
504    = \h holding sh held -> A.subtractOfLe h sh holding held
505
506{-  burnLocked: the handler refuses unless `sh + 1000 <= total`, so what is
507    left of the total after a removal still holds the locked thousand.
508-}
509let BurnLocked =
510      forall (h : A.NatFacts) (sh total : Natural)
511      -> A.Le (sh + locked) total
512      -> A.Le locked (Natural/subtract sh total)
513
514let burnLocked
515    : BurnLocked
516    = \h sh total kept ->
517        let rest = Natural/subtract sh total
518
519        -- what the removal leaves plus what it took is the total
520        let share
521            : rest + sh === total
522            = A.subtractOfLe
523                h
524                sh
525                total
526                (A.leTrans sh (sh + locked) total (A.lePlusRight sh locked) kept)
527
528        in  A.leElim
529              (sh + locked)
530              total
531              kept
532              (\d (spent : sh + locked + d === total) ->
533                 let equal
534                     : rest === locked + d
535                     = A.plusCancelLeft
536                         rest
537                         (locked + d)
538                         sh
539                         (E.trans
540                            (E.sym (A.plusComm rest sh))
541                            (E.trans share (E.trans (E.sym spent) (A.plusAssoc sh locked d))))
542
543                 in  E.subst (\(t : Natural) -> A.Le locked t) (E.sym equal) (d, refl))
544
545{-  The two additions a removal needs: `L * (x - a) + L * a = L * x` for
546    `a <= x`, and `(L - sh) * x + sh * x = L * x` for `sh <= L`.
547-}
548let timesRestore
549    : forall (h : A.NatFacts) (total a x : Natural)
550      -> A.Le a x
551      -> total * Natural/subtract a x + total * a === total * x
552    = \h total a x small ->
553        E.trans
554          (E.sym (A.distribLeft h total (Natural/subtract a x) a))
555          (E.cong (\(k : Natural) -> total * k) (A.subtractOfLe h a x small))
556
557let sharesRestore
558    : forall (h : A.NatFacts) (total sh x : Natural)
559      -> A.Le sh total
560      -> Natural/subtract sh total * x + sh * x === total * x
561    = \h total sh x small ->
562        E.trans
563          (E.sym (A.distribRight h (Natural/subtract sh total) sh x))
564          (E.cong (\(k : Natural) -> k * x) (A.subtractOfLe h sh total small))
565
566{-  burnKeepsK: a removal does not lower the pool's product per share
567    either.  The payout `a0 = sh * x / L` is at most `x`, and
568    `(L - sh) * x + sh * x = L * x = L * (x - a0) + L * a0` with
569    `L * a0 <= sh * x`, so `(L - sh) * x <= L * (x - a0)`; the same on
570    the second reserve, multiplied, gives `L'² * x * y <= L² * x' * y'`.
571-}
572let BurnKeepsK =
573      forall (h : A.NatFacts) (x y total sh : Natural)
574      -> A.Lt 0 total
575      -> A.Le sh total
576      -> A.Le
577           (Natural/subtract sh total * Natural/subtract sh total * (x * y))
578           (total
579            * total
580            * (Natural/subtract (Natural/div (sh * x) total) x
581               * Natural/subtract (Natural/div (sh * y) total) y))
582
583let burnKeepsK
584    : BurnKeepsK
585    = \h x y total sh positive small ->
586        let a0 = Natural/div (sh * x) total
587
588        let a1 = Natural/div (sh * y) total
589
590        let remain = Natural/subtract sh total
591
592        let newX = Natural/subtract a0 x
593
594        let newY = Natural/subtract a1 y
595
596        let floor0 : A.Le (a0 * total) (sh * x) = A.divTimesLe h (sh * x) total
597
598        let floor1 : A.Le (a1 * total) (sh * y) = A.divTimesLe h (sh * y) total
599
600        -- the total is a successor, so its factor cancels
601        let succ
602            : total === Natural/subtract 1 total + 1
603            = E.sym (A.subtractOfLe h 1 total positive)
604
605        let sharesBelow
606            : forall (a n : Natural) -> A.Le (a * total) (sh * n) -> A.Le a n
607            = \a n bound ->
608                let byN
609                    : A.Le (a * total) (n * total)
610                    = A.leTrans
611                        (a * total)
612                        (sh * n)
613                        (n * total)
614                        bound
615                        (A.eqTransLe
616                           (sh * n)
617                           (n * sh)
618                           (n * total)
619                           (A.timesComm h sh n)
620                           (A.leTimesLeft h sh total n small))
621
622                in  A.leTimesCancel
623                      h
624                      a
625                      n
626                      (Natural/subtract 1 total)
627                      (E.subst (\(t : Natural) -> A.Le (a * t) (n * t)) succ byN)
628
629        let a0LeX : A.Le a0 x = sharesBelow a0 x floor0
630
631        let a1LeY : A.Le a1 y = sharesBelow a1 y floor1
632
633        -- one reserve: what stays is at most what the deposit-less
634        -- product says it should be
635        let side
636            : forall (reserve a : Natural)
637              -> A.Le a reserve
638              -> A.Le (a * total) (sh * reserve)
639              -> A.Le (remain * reserve) (total * Natural/subtract a reserve)
640            = \reserve a smallA floor ->
641                let stay : Natural = remain * reserve
642
643                let kept : Natural = total * Natural/subtract a reserve
644
645                let paid : Natural = total * a
646
647                let taken : Natural = sh * reserve
648
649                let staySum
650                    : stay + taken === total * reserve
651                    = sharesRestore h total sh reserve small
652
653                let keptSum
654                    : kept + paid === total * reserve
655                    = timesRestore h total a reserve smallA
656
657                let paidBelow
658                    : A.Le paid taken
659                    = A.eqTransLe paid (a * total) taken (A.timesComm h total a) floor
660
661                in  A.leElim
662                      paid
663                      taken
664                      paidBelow
665                      (\d (spent : paid + d === taken) ->
666                         let equal
667                             : stay + d === kept
668                             = A.plusCancelRight
669                                 (stay + d)
670                                 kept
671                                 paid
672                                 (E.trans
673                                    (A.plusAssoc stay d paid)
674                                    (E.trans
675                                       (E.cong (\(k : Natural) -> stay + k) (A.plusComm d paid))
676                                       (E.trans
677                                          (E.cong (\(k : Natural) -> stay + k) spent)
678                                          (E.trans staySum (E.sym keptSum)))))
679
680                         in  (d, equal))
681
682        let restX : A.Le (remain * x) (total * newX) = side x a0 a0LeX floor0
683
684        let restY : A.Le (remain * y) (total * newY) = side y a1 a1LeY floor1
685
686        let vars = [ x, y, total, remain, newX, newY ]
687
688        let multiplied
689            : A.Le (remain * x * (remain * y)) (total * newX * (total * newY))
690            = A.leTimes h (remain * x) (total * newX) (remain * y) (total * newY) restX restY
691
692        in  A.eqTransLe
693              (remain * remain * (x * y))
694              (remain * x * (remain * y))
695              (total * total * (newX * newY))
696              (R.ring
697                 h
698                 vars
699                 (R.mul (R.mul (R.var 3) (R.var 3)) (R.mul (R.var 0) (R.var 1)))
700                 (R.mul (R.mul (R.var 3) (R.var 0)) (R.mul (R.var 3) (R.var 1)))
701                 refl)
702              (A.leTransEq
703                 (remain * x * (remain * y))
704                 (total * newX * (total * newY))
705                 (total * total * (newX * newY))
706                 multiplied
707                 (R.ring
708                    h
709                    vars
710                    (R.mul (R.mul (R.var 2) (R.var 4)) (R.mul (R.var 2) (R.var 5)))
711                    (R.mul (R.mul (R.var 2) (R.var 2)) (R.mul (R.var 4) (R.var 5)))
712                    refl))
713
714{-  DepositKeepsK: a deposit does not lower the pool's product per share:
715    the minted shares are at most `a0 * L / x` and `a1 * L / y`, so
716    `L' * x <= L * x'` and `L' * y <= L * y'`, and multiplying the two gives
717    `L'² * x * y <= L² * x' * y'` with `L' = L + minted`, `x' = x + a0`,
718    `y' = y + a1`.
719-}
720let DepositKeepsK =
721      forall (h : A.NatFacts) (x a0 y a1 total minted : Natural)
722      -> A.Le (minted * x) (a0 * total)
723      -> A.Le (minted * y) (a1 * total)
724      -> A.Le
725           ((total + minted) * (total + minted) * (x * y))
726           (total * total * ((x + a0) * (y + a1)))
727
728let depositKeepsK
729    : DepositKeepsK
730    = \h x a0 y a1 total minted smallFirst smallSecond ->
731        let sum = total + minted
732
733        let vars = [ x, a0, y, a1, total, minted ]
734
735        let rSum = R.add (R.var 4) (R.var 5)
736
737        let rX = R.add (R.var 0) (R.var 1)
738
739        let rY = R.add (R.var 2) (R.var 3)
740
741        let reorderLeft
742            : sum * sum * (x * y) === sum * x * (sum * y)
743            = R.ring
744                h
745                vars
746                (R.mul (R.mul rSum rSum) (R.mul (R.var 0) (R.var 2)))
747                (R.mul (R.mul rSum (R.var 0)) (R.mul rSum (R.var 2)))
748                refl
749
750        let scaledFirst
751            : A.Le (sum * x) (total * (x + a0))
752            = A.eqTransLe
753                (sum * x)
754                (total * x + minted * x)
755                (total * (x + a0))
756                (A.distribRight h total minted x)
757                (A.leTransEq
758                   (total * x + minted * x)
759                   (total * x + a0 * total)
760                   (total * (x + a0))
761                   (A.lePlus
762                      (total * x)
763                      (total * x)
764                      (minted * x)
765                      (a0 * total)
766                      (A.leRefl (total * x))
767                      smallFirst)
768                   (R.ring
769                      h
770                      vars
771                      (R.add (R.mul (R.var 4) (R.var 0)) (R.mul (R.var 1) (R.var 4)))
772                      (R.mul (R.var 4) rX)
773                      refl))
774
775        let scaledSecond
776            : A.Le (sum * y) (total * (y + a1))
777            = A.eqTransLe
778                (sum * y)
779                (total * y + minted * y)
780                (total * (y + a1))
781                (A.distribRight h total minted y)
782                (A.leTransEq
783                   (total * y + minted * y)
784                   (total * y + a1 * total)
785                   (total * (y + a1))
786                   (A.lePlus
787                      (total * y)
788                      (total * y)
789                      (minted * y)
790                      (a1 * total)
791                      (A.leRefl (total * y))
792                      smallSecond)
793                   (R.ring
794                      h
795                      vars
796                      (R.add (R.mul (R.var 4) (R.var 2)) (R.mul (R.var 3) (R.var 4)))
797                      (R.mul (R.var 4) rY)
798                      refl))
799
800        let multiplied
801            : A.Le (sum * x * (sum * y)) (total * (x + a0) * (total * (y + a1)))
802            = A.leTimes
803                h
804                (sum * x)
805                (total * (x + a0))
806                (sum * y)
807                (total * (y + a1))
808                scaledFirst
809                scaledSecond
810
811        in  A.eqTransLe
812              (sum * sum * (x * y))
813              (sum * x * (sum * y))
814              (total * total * ((x + a0) * (y + a1)))
815              reorderLeft
816              (A.leTransEq
817                 (sum * x * (sum * y))
818                 (total * (x + a0) * (total * (y + a1)))
819                 (total * total * ((x + a0) * (y + a1)))
820                 multiplied
821                 (R.ring
822                    h
823                    vars
824                    (R.mul (R.mul (R.var 4) rX) (R.mul (R.var 4) rY))
825                    (R.mul (R.mul (R.var 4) (R.var 4)) (R.mul rX rY))
826                    refl))
827
828{-  The contract's word functions, read as naturals.  ./Transition.omg's
829    functions are what ../Pool.omg computes with; these theorems say that
830    reading them through `Word/toNatural` gives the specification above, so
831    a property proved of the specification is a property of the contract's
832    arithmetic.  The bounds are the ones the pool maintains: a reserve is
833    below the cap, so a numerator of `997 * a * y` and a divisor of
834    `1000 * x + 997 * a` fit a word.
835-}
836let N = std:Natural.pow2 256
837
838let capSquare
839    : A.Lt (cap * cap) N
840    = (115792089210356248756420345214020892766250353992003419616917011526809519390719, refl)
841
842let capCeil
843    : A.Lt (cap * cap + cap) N
844    = (115792089210356248756420345214020892766250348799706561082089382996313190170623, refl)
845
846let feeCapSquare
847    : A.Lt (fee * (cap * cap)) N
848    = (115792062358249368274383109725673866094698203049407574766506820347613711171583, refl)
849
850let divisorCeil
851    : A.Lt (whole * cap + fee * cap) N
852    = (115792089237316195423570985008687907853259615648814069988683408606743677108223, refl)
853
854-- A product of two capped factors is at most `cap * cap`.
855let cappedProduct
856    : forall (h : A.NatFacts) (a b : Natural)
857      -> A.Le a cap
858      -> A.Le b cap
859      -> A.Le (a * b) (cap * cap)
860    = \h a b pa pb -> A.leTimes h a cap b cap pa pb
861
862let wordLow
863    : forall (packed : Word 256)
864      -> Word/toNatural (Transition.low packed) === low (Word/toNatural packed)
865    = \packed -> A.modBridge packed Transition.capWord
866
867let wordHigh
868    : forall (packed : Word 256)
869      -> Word/toNatural (Transition.high packed) === high (Word/toNatural packed)
870    = \packed -> A.shrBridge 112 packed refl
871
872let wordPack
873    : forall (h : A.NatFacts) (r0 r1 : Word 256)
874      -> A.Lt (Word/toNatural r0) cap
875      -> A.Lt (Word/toNatural r1) cap
876      -> Word/toNatural (Transition.pack r0 r1) === pack (Word/toNatural r0) (Word/toNatural r1)
877    = \h r0 r1 low0 low1 ->
878        let shifted
879            : Word/toNatural (Word/shl 112 r1) === Word/toNatural r1 * cap
880            = E.trans
881                (A.word256Shl 112 r1 refl)
882                (A.modOfLt
883                   h
884                   (Word/toNatural r1 * cap)
885                   (Natural/subtract 1 N)
886                   (A.leLtTrans
887                      (Word/toNatural r1 * cap)
888                      (cap * cap)
889                      N
890                      (cappedProduct
891                         h
892                         (Word/toNatural r1)
893                         cap
894                         (A.leOfLt (Word/toNatural r1) cap low1)
895                         (A.leRefl cap))
896                      capSquare))
897
898        let under
899            : A.Le (Word/toNatural r0 + Word/toNatural (Word/shl 112 r1)) (cap + cap * cap)
900            = E.subst
901                (\(t : Natural) -> A.Le (Word/toNatural r0 + t) (cap + cap * cap))
902                (E.sym shifted)
903                (A.lePlus
904                   (Word/toNatural r0)
905                   cap
906                   (Word/toNatural r1 * cap)
907                   (cap * cap)
908                   (A.leOfLt (Word/toNatural r0) cap low0)
909                   (cappedProduct
910                      h
911                      (Word/toNatural r1)
912                      cap
913                      (A.leOfLt (Word/toNatural r1) cap low1)
914                      (A.leRefl cap)))
915
916        let sum
917            : A.Lt (Word/toNatural r0 + Word/toNatural (Word/shl 112 r1)) N
918            = A.leLtTrans
919                (Word/toNatural r0 + Word/toNatural (Word/shl 112 r1))
920                (cap + cap * cap)
921                N
922                under
923                capCeil
924
925        in  E.trans
926              (A.word256AddExact h r0 (Word/shl 112 r1) sum)
927              (E.trans (E.cong (\(t : Natural) -> Word/toNatural r0 + t) shifted) refl)
928
929let wordSharePrice
930    : forall (h : A.NatFacts) (a total reserve : Word 256)
931      -> A.Lt (Word/toNatural a * Word/toNatural total) N
932      -> Word/toNatural (Transition.sharePrice a total reserve)
933         === sharePriceOf (Word/toNatural a) (Word/toNatural total) (Word/toNatural reserve)
934    = \h a total reserve fits ->
935        E.cong
936          (\(t : Natural) -> Natural/div t (Word/toNatural reserve))
937          (A.word256MulExact h a total fits)
938
939let wordSwapOut
940    : forall (h : A.NatFacts) (a x y : Word 256)
941      -> A.Lt (Word/toNatural a) cap
942      -> A.Lt (Word/toNatural x) cap
943      -> A.Lt (Word/toNatural y) cap
944      -> Word/toNatural (Transition.swapOut a y x)
945         === swapOut (Word/toNatural a) (Word/toNatural y) (Word/toNatural x)
946    = \h a x y sa sx sy ->
947        let n = Word/toNatural @256
948        let wordsHere = swapTerms @(Word 256) words a y x
949        let naturalsHere = swapTerms @Natural naturals (n a) (n y) (n x)
950        let f = Transition.lit fee
951        let w = Transition.lit whole
952        let weighted = Word/mul f a
953        let reserve = Word/mul w x
954        let aCap = A.leOfLt (n a) cap sa
955        let xCap = A.leOfLt (n x) cap sx
956        let yCap = A.leOfLt (n y) cap sy
957        let feeBound = A.leTimesLeft h (n a) cap fee aCap
958        let wholeBound = A.leTimesLeft h (n x) cap whole xCap
959        let feeFits =
960              A.leLtTrans
961                (fee * cap)
962                (whole * cap + fee * cap)
963                N
964                (A.lePlusLeft (whole * cap) (fee * cap))
965                divisorCeil
966        let wholeFits =
967              A.leLtTrans
968                (whole * cap)
969                (whole * cap + fee * cap)
970                N
971                (A.lePlusRight (whole * cap) (fee * cap))
972                divisorCeil
973        let feeExact =
974              A.word256MulExact h f a (A.leLtTrans (fee * n a) (fee * cap) N feeBound feeFits)
975        let reserveExact =
976              A.word256MulExact
977                h
978                w
979                x
980                (A.leLtTrans (whole * n x) (whole * cap) N wholeBound wholeFits)
981        let numeratorBound =
982              A.leTimes
983                h
984                (n weighted)
985                (fee * cap)
986                (n y)
987                cap
988                (A.eqTransLe (n weighted) (fee * n a) (fee * cap) feeExact feeBound)
989                yCap
990        let numeratorFits =
991              A.leLtTrans
992                (n weighted * n y)
993                (fee * (cap * cap))
994                N
995                (A.leTransEq
996                   (n weighted * n y)
997                   (fee * cap * cap)
998                   (fee * (cap * cap))
999                   numeratorBound
1000                   (A.timesAssoc h fee cap cap))
1001                feeCapSquare
1002        let numerator =
1003              E.trans
1004                (A.word256MulExact h weighted y numeratorFits)
1005                (E.cong (\(v : Natural) -> v * n y) feeExact)
1006        let sumBound =
1007              A.lePlus
1008                (n reserve)
1009                (whole * cap)
1010                (n weighted)
1011                (fee * cap)
1012                (A.eqTransLe (n reserve) (whole * n x) (whole * cap) reserveExact wholeBound)
1013                (A.eqTransLe (n weighted) (fee * n a) (fee * cap) feeExact feeBound)
1014        let denominator =
1015              E.trans
1016                (A.word256AddExact
1017                   h
1018                   reserve
1019                   weighted
1020                   (A.leLtTrans
1021                      (n reserve + n weighted)
1022                      (whole * cap + fee * cap)
1023                      N
1024                      sumBound
1025                      divisorCeil))
1026                (E.trans
1027                   (E.cong (\(v : Natural) -> v + n weighted) reserveExact)
1028                   (E.cong (\(v : Natural) -> whole * n x + v) feeExact))
1029        in  E.trans
1030              (A.word256Div wordsHere.numerator wordsHere.denominator)
1031              (E.trans
1032                 (E.cong (\(v : Natural) -> Natural/div v (n wordsHere.denominator)) numerator)
1033                 (E.cong (Natural/div naturalsHere.numerator) denominator))
1034
1035-- The following theorems refer to fields of the very transitions that
1036-- Pool.omg calls. Their guard hypotheses are the checks made before
1037-- the handler can commit a returned update.
1038let n = Word/toNatural @256
1039
1040let Small = \(w : Word 256) -> A.Lt (n w) cap
1041
1042let atMostCap
1043    : forall (w : Word 256) -> Small w -> A.Le (n w) cap
1044    = \w p -> A.leOfLt (n w) cap p
1045
1046let doubleCap
1047    : A.Lt (cap + cap) N
1048    = (Natural/subtract (cap + cap + 1) N, refl)
1049
1050let addSmall
1051    : forall (h : A.NatFacts) (x a : Word 256)
1052      -> Small x
1053      -> Small a
1054      -> n (Word/add x a) === n x + n a
1055    = \h x a sx sa ->
1056        A.word256AddExact
1057          h
1058          x
1059          a
1060          (A.leLtTrans
1061             (n x + n a)
1062             (cap + cap)
1063             N
1064             (A.lePlus (n x) cap (n a) cap (atMostCap x sx) (atMostCap a sa))
1065             doubleCap)
1066
1067let mulCap
1068    : forall (h : A.NatFacts) (x y : Word 256)
1069      -> A.Le (n x) cap
1070      -> A.Le (n y) cap
1071      -> n (Word/mul x y) === n x * n y
1072    = \h x y sx sy ->
1073        A.word256MulExact
1074          h
1075          x
1076          y
1077          (A.leLtTrans (n x * n y) (cap * cap) N (cappedProduct h (n x) (n y) sx sy) capSquare)
1078
1079let mulFits
1080    : forall (h : A.NatFacts) (x y : Word 256) -> Small x -> Small y -> A.Lt (n x * n y) N
1081    = \h x y sx sy ->
1082        A.leLtTrans
1083          (n x * n y)
1084          (cap * cap)
1085          N
1086          (cappedProduct h (n x) (n y) (atMostCap x sx) (atMostCap y sy))
1087          capSquare
1088
1089let leGuard
1090    : forall (h : A.NatFacts) (x y : Word 256)
1091      -> std:Bool.not (Word/lt y x) === True
1092      -> A.Le (n x) (n y)
1093    = \h x y ok ->
1094        A.word256LtFalse
1095          h
1096          y
1097          x
1098          (A.boolCases
1099             (\(b : Bool) -> std:Bool.not b === True -> b === False)
1100             (Word/lt y x)
1101             (\_ p -> A.falseNotTrue p)
1102             (\_ _ -> refl)
1103             ok)
1104
1105let belowCap
1106    : forall (h : A.NatFacts) (x : Word 256) -> Word/lt x Transition.capWord === True -> Small x
1107    = \h x ok -> A.word256LtSound h x Transition.capWord ok
1108
1109let packRoundTrip
1110    : forall (h : A.NatFacts) (x y : Word 256)
1111      -> Small x
1112      -> Small y
1113      -> { first : n (Transition.low (Transition.pack x y)) === n x
1114         , second : n (Transition.high (Transition.pack x y)) === n y
1115         , fits : A.Lt (n (Transition.pack x y)) (cap * cap)
1116         }
1117    = \h x y sx sy ->
1118        let packed = Transition.pack x y
1119        let packs = wordPack h x y sx sy
1120        let parts = halves h (n x) (n y) sx sy
1121        in  { first = E.trans (wordLow packed) (E.trans (E.cong low packs) parts.1)
1122            , second = E.trans (wordHigh packed) (E.trans (E.cong high packs) parts.2)
1123            , fits =
1124                E.subst
1125                  (\(v : Natural) -> A.Lt v (cap * cap))
1126                  (E.sym packs)
1127                  (wordFits h (n x) (n y) sx sy)
1128            }
1129
1130let SwapResult
1131    : Word 256 -> Word 256 -> Word 256 -> Word 256 -> Type
1132    = \amount minimum x y ->
1133        let trade = Transition.swap amount minimum x y
1134        in  { price : n trade.out === swapOut (n amount) (n y) (n x)
1135            , minimum : A.Le (n minimum) (n trade.out)
1136            , input : n trade.reserveIn === n x + n amount
1137            , output : n trade.reserveOut === Natural/subtract (n trade.out) (n y)
1138            , inputFits : Small trade.reserveIn
1139            , outputFits : Small trade.reserveOut
1140            , keepsK : A.Le (n x * n y) (n trade.reserveIn * n trade.reserveOut)
1141            }
1142
1143let swapTransition
1144    : forall (h : A.NatFacts) (amount minimum x y : Word 256) (u : Natural)
1145      -> n x === u + 1
1146      -> Small amount
1147      -> Small x
1148      -> Small y
1149      -> (Transition.swap amount minimum x y).liquid === True
1150      -> (Transition.swap amount minimum x y).meetsMinimum === True
1151      -> (Transition.swap amount minimum x y).fits === True
1152      -> SwapResult amount minimum x y
1153    = \h amount minimum x y u positive sa sx sy liquid enough fits ->
1154        let trade = Transition.swap amount minimum x y
1155        let priced = wordSwapOut h amount x y sa sx sy
1156        let paid = A.leOfLt (n trade.out) (n y) (A.word256LtSound h trade.out y liquid)
1157        let added = addSmall h x amount sx sa
1158        let reduced = A.word256SubExact h y trade.out paid
1159        let quoted
1160            : A.Le
1161                (n x * n y)
1162                ((n x + n amount) * Natural/subtract (swapOut (n amount) (n y) (n x)) (n y))
1163            = E.subst
1164                (\(v : Natural) ->
1165                   A.Le
1166                     (v * n y)
1167                     ((v + n amount) * Natural/subtract (swapOut (n amount) (n y) v) (n y)))
1168                (E.sym positive)
1169                (swapKeepsK h u (n amount) (n y))
1170        in  { price = priced
1171            , minimum = leGuard h minimum trade.out enough
1172            , input = added
1173            , output = reduced
1174            , inputFits = belowCap h trade.reserveIn fits
1175            , outputFits =
1176                A.leLtTrans
1177                  (n trade.reserveOut)
1178                  (n y)
1179                  cap
1180                  (A.eqTransLe
1181                     (n trade.reserveOut)
1182                     (Natural/subtract (n trade.out) (n y))
1183                     (n y)
1184                     reduced
1185                     (below h (n trade.out) (n y) paid))
1186                  sy
1187            , keepsK =
1188                E.subst
1189                  (\(v : Natural) -> A.Le (n x * n y) (n trade.reserveIn * v))
1190                  (E.sym
1191                     (E.trans reduced (E.cong (\(o : Natural) -> Natural/subtract o (n y)) priced)))
1192                  (E.subst
1193                     (\(v : Natural) ->
1194                        A.Le
1195                          (n x * n y)
1196                          (v * Natural/subtract (swapOut (n amount) (n y) (n x)) (n y)))
1197                     (E.sym added)
1198                     quoted)
1199            }
1200
1201let depositReserves
1202    : forall (h : A.NatFacts) (a0 a1 x y : Word 256)
1203      -> Small a0
1204      -> Small a1
1205      -> Small x
1206      -> Small y
1207      -> (Transition.deposited a0 a1 x y).fits === True
1208      -> { first : n (Transition.deposited a0 a1 x y).reserve0 === n x + n a0
1209         , second : n (Transition.deposited a0 a1 x y).reserve1 === n y + n a1
1210         , firstFits : Small (Transition.deposited a0 a1 x y).reserve0
1211         , secondFits : Small (Transition.deposited a0 a1 x y).reserve1
1212         }
1213    = \h a0 a1 x y sa0 sa1 sx sy fits ->
1214        let next = Transition.deposited a0 a1 x y
1215        let first = Word/lt next.reserve0 Transition.capWord
1216        let second = Word/lt next.reserve1 Transition.capWord
1217        in  { first = addSmall h x a0 sx sa0
1218            , second = addSmall h y a1 sy sa1
1219            , firstFits = belowCap h next.reserve0 (A.andLeft first second fits)
1220            , secondFits = belowCap h next.reserve1 (A.andRight first second fits)
1221            }
1222
1223let wordMin
1224    : forall (h : A.NatFacts) (x y : Word 256)
1225      -> { first : A.Le (n (Transition.minted x y)) (n x)
1226         , second : A.Le (n (Transition.minted x y)) (n y)
1227         }
1228    = \h x y ->
1229        A.boolCases
1230          (\(b : Bool) ->
1231             let v = n (if b then x else y)
1232             in  { first : A.Le v (n x), second : A.Le v (n y) })
1233          (Word/lt x y)
1234          (\p ->
1235             { first = A.leRefl (n x)
1236             , second = A.leOfLt (n x) (n y) (A.word256LtSound h x y p)
1237             })
1238          (\p -> { first = A.word256LtFalse h x y p, second = A.leRefl (n y) })
1239
1240let floorPrice
1241    : forall (h : A.NatFacts) (a total reserve : Word 256) (shares : Natural)
1242      -> A.Lt (n a * n total) N
1243      -> A.Le shares (n (Transition.sharePrice a total reserve))
1244      -> A.Le (shares * n reserve) (n a * n total)
1245    = \h a total reserve shares fits small ->
1246        let q = sharePriceOf (n a) (n total) (n reserve)
1247        let scaled =
1248              A.leTimesRight
1249                h
1250                shares
1251                q
1252                (n reserve)
1253                (A.leTransEq
1254                   shares
1255                   (n (Transition.sharePrice a total reserve))
1256                   q
1257                   small
1258                   (wordSharePrice h a total reserve fits))
1259        in  A.leTrans
1260              (shares * n reserve)
1261              (q * n reserve)
1262              (n a * n total)
1263              scaled
1264              (A.divTimesLe h (n a * n total) (n reserve))
1265
1266{-  keptProduct: the scaled invariant implies the plain one.  With a positive
1267    product `x * y`, `L² <= x * y` and `L'² * x * y <= L² * x' * y'`
1268    give `L'² <= x' * y'`.
1269-}
1270let KeptProduct =
1271      forall (h : A.NatFacts) (low lowNext x y xNext yNext : Natural)
1272      -> A.Le 1 x
1273      -> A.Le 1 y
1274      -> A.Le lowNext (x * y)
1275      -> A.Le (low * (x * y)) (lowNext * (xNext * yNext))
1276      -> A.Le low (xNext * yNext)
1277
1278let keptProduct
1279    : KeptProduct
1280    = \h low lowNext x y xNext yNext oneX oneY below scaled ->
1281        let product = x * y
1282
1283        -- the product is a successor, so it cancels
1284        let positive : A.Le 1 product = A.leTimes h 1 x 1 y oneX oneY
1285
1286        let succ
1287            : product === Natural/subtract 1 product + 1
1288            = E.sym (A.subtractOfLe h 1 product positive)
1289
1290        let raised
1291            : A.Le (low * product) (product * (xNext * yNext))
1292            = A.leTrans
1293                (low * product)
1294                (lowNext * (xNext * yNext))
1295                (product * (xNext * yNext))
1296                scaled
1297                (A.leTimesRight h lowNext product (xNext * yNext) below)
1298
1299        let ordered
1300            : A.Le (low * product) (xNext * yNext * product)
1301            = A.leTransEq
1302                (low * product)
1303                (product * (xNext * yNext))
1304                (xNext * yNext * product)
1305                raised
1306                (A.timesComm h product (xNext * yNext))
1307
1308        in  A.leTimesCancel
1309              h
1310              low
1311              (xNext * yNext)
1312              (Natural/subtract 1 product)
1313              (E.subst (\(t : Natural) -> A.Le (low * t) (xNext * yNext * t)) succ ordered)
1314
1315-- The pool's invariant bounds an existing total by its two reserves.
1316let totalFits
1317    : forall (h : A.NatFacts) (x y total : Word 256)
1318      -> Small x
1319      -> Small y
1320      -> A.Le (n total * n total) (n x * n y)
1321      -> Small total
1322    = \h x y total sx sy valid ->
1323        let productSmall =
1324              A.leLtTrans
1325                (n x * n y)
1326                (n x * cap)
1327                (cap * cap)
1328                (A.leTimesLeft h (n y) cap (n x) (atMostCap y sy))
1329                (A.ltTimesRight h (n x) cap (Natural/subtract 1 cap) sx)
1330        in  merge
1331              { Le =
1332                  \(large : A.Le cap (n total)) ->
1333                    A.leLtAbsurd
1334                      (cap * cap)
1335                      (n total * n total)
1336                      (A.leTimes h cap (n total) cap (n total) large large)
1337                      (A.leLtTrans (n total * n total) (n x * n y) (cap * cap) valid productSmall)
1338              , Gt = \(small : Small total) -> small
1339              }
1340              (A.leTotal cap (n total))
1341
1342let liveTransition
1343    : forall (h : A.NatFacts) (a0 a1 x y total held : Word 256)
1344      -> Small a0
1345      -> Small a1
1346      -> A.Le (n total * n total) (n x * n y)
1347      -> A.Le 1 (n x)
1348      -> A.Le 1 (n y)
1349      -> A.Le (n held) (n total)
1350      -> (Transition.deposited a0 a1 x y).fits === True
1351      -> Small x
1352      -> Small y
1353      -> Transition.hasMinted (Transition.liveMint a0 a1 x y total).minted === True
1354      -> { positive : A.Lt 0 (n (Transition.liveMint a0 a1 x y total).minted)
1355         , total :
1356             n (Transition.liveMint a0 a1 x y total).total
1357             === n total + n (Transition.liveMint a0 a1 x y total).minted
1358         , credited :
1359             n (Transition.credit held (Transition.liveMint a0 a1 x y total).minted)
1360             === n held + n (Transition.liveMint a0 a1 x y total).minted
1361         , keepsK :
1362             let deposit = Transition.deposited a0 a1 x y
1363             let next = n (Transition.liveMint a0 a1 x y total).total
1364             in  A.Le
1365                   (next * next * (n x * n y))
1366                   (n total * n total * (n deposit.reserve0 * n deposit.reserve1))
1367         }
1368    = \h a0 a1 x y total held sa0 sa1 invariantBefore oneX oneY holds accepted sx sy positive ->
1369        let st = totalFits h x y total sx sy invariantBefore
1370        let next = Transition.liveMint a0 a1 x y total
1371        let deposit = Transition.deposited a0 a1 x y
1372        let minted = n next.minted
1373        let p0 = Transition.sharePrice a0 total x
1374        let p1 = Transition.sharePrice a1 total y
1375        let minimum = wordMin h p0 p1
1376        let first = floorPrice h a0 total x minted (mulFits h a0 total sa0 st) minimum.first
1377        let second = floorPrice h a1 total y minted (mulFits h a1 total sa1 st) minimum.second
1378        let mintBound
1379            : A.Le minted (cap * cap)
1380            = A.leTrans
1381                minted
1382                (minted * n x)
1383                (cap * cap)
1384                (A.eqTransLe
1385                   minted
1386                   (1 * minted)
1387                   (minted * n x)
1388                   (E.sym (A.timesComm h 1 minted))
1389                   (A.leTransEq
1390                      (1 * minted)
1391                      (n x * minted)
1392                      (minted * n x)
1393                      (A.leTimesRight h 1 (n x) minted oneX)
1394                      (A.timesComm h (n x) minted)))
1395                (A.leTrans
1396                   (minted * n x)
1397                   (n a0 * n total)
1398                   (cap * cap)
1399                   first
1400                   (cappedProduct h (n a0) (n total) (atMostCap a0 sa0) (atMostCap total st)))
1401        let addFits
1402            : forall (balance : Word 256) -> A.Le (n balance) cap -> A.Lt (n balance + minted) N
1403            = \balance small ->
1404                A.leLtTrans
1405                  (n balance + minted)
1406                  (cap + cap * cap)
1407                  N
1408                  (A.lePlus (n balance) cap minted (cap * cap) small mintBound)
1409                  capCeil
1410        let sum = A.word256AddExact h total next.minted (addFits total (atMostCap total st))
1411        let credited =
1412              A.word256AddExact
1413                h
1414                held
1415                next.minted
1416                (addFits held (A.leTrans (n held) (n total) cap holds (atMostCap total st)))
1417        let changed = depositReserves h a0 a1 x y sa0 sa1 sx sy accepted
1418        let invariant = depositKeepsK h (n x) (n a0) (n y) (n a1) (n total) minted first second
1419        let exact =
1420              E.subst
1421                (\(v : Natural) ->
1422                   A.Le (v * v * (n x * n y)) (n total * n total * ((n x + n a0) * (n y + n a1))))
1423                (E.sym sum)
1424                invariant
1425        in  { positive = A.word256LtSound h (Transition.lit 0) next.minted positive
1426            , total = sum
1427            , credited
1428            , keepsK =
1429                E.subst
1430                  (\(v : Natural) ->
1431                     A.Le
1432                       (n next.total * n next.total * (n x * n y))
1433                       (n total * n total * (n deposit.reserve0 * v)))
1434                  (E.sym changed.second)
1435                  (E.subst
1436                     (\(v : Natural) ->
1437                        A.Le
1438                          (n next.total * n next.total * (n x * n y))
1439                          (n total * n total * (v * (n y + n a1))))
1440                     (E.sym changed.first)
1441                     exact)
1442            }
1443
1444let lockedSmall : Small (Transition.lit locked) = (Natural/subtract (locked + 1) cap, refl)
1445
1446let burnLimit
1447    : forall (h : A.NatFacts) (amount total : Word 256)
1448      -> Small amount
1449      -> Transition.keepsLock amount total === True
1450      -> A.Le (n amount + locked) (n total)
1451    = \h amount total small allowed ->
1452        let limit = Word/add amount (Transition.lit locked)
1453        in  A.eqTransLe
1454              (n amount + locked)
1455              (n limit)
1456              (n total)
1457              (E.sym (addSmall h amount (Transition.lit locked) small lockedSmall))
1458              (leGuard h limit total allowed)
1459
1460let payout
1461    : forall (h : A.NatFacts) (amount reserve total : Word 256)
1462      -> Small amount
1463      -> Small reserve
1464      -> A.Le 1 (n total)
1465      -> A.Le (n amount) (n total)
1466      -> { quoted :
1467             n (Transition.sharePrice amount reserve total)
1468             === sharePriceOf (n amount) (n reserve) (n total)
1469         , bounded : A.Le (n (Transition.sharePrice amount reserve total)) (n reserve)
1470         }
1471    = \h amount reserve total sh sr positive bound ->
1472        let quote = wordSharePrice h amount reserve total (mulFits h amount reserve sh sr)
1473        let bounded =
1474              A.leElim
1475                1
1476                (n total)
1477                positive
1478                (\d eq ->
1479                   E.subst
1480                     (\(t : Natural) -> A.Le (sharePriceOf (n amount) (n reserve) t) (n reserve))
1481                     eq
1482                     (removalPays
1483                        h
1484                        (n amount)
1485                        (n reserve)
1486                        d
1487                        (A.leTransEq (n amount) (n total) (d + 1) bound (E.sym eq))))
1488        in  { quoted = quote
1489            , bounded =
1490                A.eqTransLe
1491                  (n (Transition.sharePrice amount reserve total))
1492                  (sharePriceOf (n amount) (n reserve) (n total))
1493                  (n reserve)
1494                  quote
1495                  bounded
1496            }
1497
1498let burnTransition
1499    : forall (h : A.NatFacts) (amount x y total held : Word 256)
1500      -> Small amount
1501      -> Small x
1502      -> Small y
1503      -> Transition.keepsLock amount total === True
1504      -> (Transition.burn amount x y total held).covered === True
1505      -> let next = Transition.burn amount x y total held
1506         in  { amount0 : n next.amount0 === sharePriceOf (n amount) (n x) (n total)
1507             , amount1 : n next.amount1 === sharePriceOf (n amount) (n y) (n total)
1508             , reserve0 : n next.reserve0 === Natural/subtract (n next.amount0) (n x)
1509             , reserve1 : n next.reserve1 === Natural/subtract (n next.amount1) (n y)
1510             , firstFits : Small next.reserve0
1511             , secondFits : Small next.reserve1
1512             , held : n next.held + n amount === n held
1513             , total : n next.total === Natural/subtract (n amount) (n total)
1514             , locked : A.Le locked (n next.total)
1515             , keepsK :
1516                 A.Le
1517                   (n next.total * n next.total * (n x * n y))
1518                   (n total * n total * (n next.reserve0 * n next.reserve1))
1519             }
1520    = \h amount x y total held small sx sy allowed covered ->
1521        let next = Transition.burn amount x y total held
1522        let limit = burnLimit h amount total small allowed
1523        let sh =
1524              A.leTrans
1525                (n amount)
1526                (n amount + locked)
1527                (n total)
1528                (A.lePlusRight (n amount) locked)
1529                limit
1530        let positive =
1531              A.leTrans
1532                1
1533                (n amount + locked)
1534                (n total)
1535                (n amount + Natural/subtract 1 locked, refl)
1536                limit
1537        let p0 = payout h amount x total small sx positive sh
1538        let p1 = payout h amount y total small sy positive sh
1539        let r0 = A.word256SubExact h x next.amount0 p0.bounded
1540        let r1 = A.word256SubExact h y next.amount1 p1.bounded
1541        let debit = A.word256SubExact h total amount sh
1542        let heldSize = leGuard h amount held covered
1543        let remains = A.word256SubExact h held amount heldSize
1544        let after =
1545              E.subst
1546                (\(v : Natural) ->
1547                   A.Le
1548                     (v * v * (n x * n y))
1549                     (n total
1550                      * n total
1551                      * (Natural/subtract (sharePriceOf (n amount) (n x) (n total)) (n x)
1552                         * Natural/subtract (sharePriceOf (n amount) (n y) (n total)) (n y))))
1553                (E.sym debit)
1554                (burnKeepsK h (n x) (n y) (n total) (n amount) positive sh)
1555        in  { amount0 = p0.quoted
1556            , amount1 = p1.quoted
1557            , reserve0 = r0
1558            , reserve1 = r1
1559            , firstFits =
1560                A.leLtTrans
1561                  (n next.reserve0)
1562                  (n x)
1563                  cap
1564                  (A.eqTransLe
1565                     (n next.reserve0)
1566                     (Natural/subtract (n next.amount0) (n x))
1567                     (n x)
1568                     r0
1569                     (below h (n next.amount0) (n x) p0.bounded))
1570                  sx
1571            , secondFits =
1572                A.leLtTrans
1573                  (n next.reserve1)
1574                  (n y)
1575                  cap
1576                  (A.eqTransLe
1577                     (n next.reserve1)
1578                     (Natural/subtract (n next.amount1) (n y))
1579                     (n y)
1580                     r1
1581                     (below h (n next.amount1) (n y) p1.bounded))
1582                  sy
1583            , held =
1584                E.trans
1585                  (E.cong (\(v : Natural) -> v + n amount) remains)
1586                  (burnHeld h (n held) (n amount) heldSize)
1587            , total = debit
1588            , locked =
1589                A.leTransEq
1590                  locked
1591                  (Natural/subtract (n amount) (n total))
1592                  (n next.total)
1593                  (burnLocked h (n amount) (n total) limit)
1594                  (E.sym debit)
1595            , keepsK =
1596                E.subst
1597                  (\(v : Natural) ->
1598                     A.Le
1599                       (n next.total * n next.total * (n x * n y))
1600                       (n total * n total * (n next.reserve0 * v)))
1601                  (E.sym
1602                     (E.trans r1 (E.cong (\(q : Natural) -> Natural/subtract q (n y)) p1.quoted)))
1603                  (E.subst
1604                     (\(v : Natural) ->
1605                        A.Le
1606                          (n next.total * n next.total * (n x * n y))
1607                          (n total
1608                           * n total
1609                           * (v
1610                              * Natural/subtract (sharePriceOf (n amount) (n y) (n total)) (n y))))
1611                     (E.sym
1612                        (E.trans
1613                           r0
1614                           (E.cong (\(q : Natural) -> Natural/subtract q (n x)) p0.quoted)))
1615                     after)
1616            }
1617
1618-- Turn the scaled law into the invariant needed by the next mint.
1619let preservesLiquidity
1620    : forall (h : A.NatFacts) (x y total xNext yNext totalNext : Word 256)
1621      -> A.Le 1 (n x)
1622      -> A.Le 1 (n y)
1623      -> A.Le (n total * n total) (n x * n y)
1624      -> A.Le (n totalNext * n totalNext * (n x * n y)) (n total * n total * (n xNext * n yNext))
1625      -> A.Le (n totalNext * n totalNext) (n xNext * n yNext)
1626    = \h x y total xNext yNext totalNext oneX oneY valid scaled ->
1627        keptProduct
1628          h
1629          (n totalNext * n totalNext)
1630          (n total * n total)
1631          (n x)
1632          (n y)
1633          (n xNext)
1634          (n yNext)
1635          oneX
1636          oneY
1637          valid
1638          scaled
1639
1640let initialTransition
1641    : forall (h : A.NatFacts) (a0 a1 : Word 256) (findRoot : Word 256 -> Word 256)
1642      -> Small a0
1643      -> Small a1
1644      -> (Transition.initialMint a0 a1 findRoot).validRoot === True
1645      -> (Transition.initialMint a0 a1 findRoot).aboveLock === True
1646      -> let first = Transition.initialMint a0 a1 findRoot
1647         let total = n first.total
1648         let minted = n first.minted
1649         in  { square : A.Le (total * total) (n a0 * n a1)
1650             , nextSquare : A.Lt (n a0 * n a1) ((total + 1) * (total + 1))
1651             , minted : minted === Natural/subtract locked total
1652             , positive : A.Lt 0 minted
1653             , fits : Small first.total
1654             }
1655    = \h a0 a1 findRoot sa0 sa1 valid above ->
1656        let first = Transition.initialMint a0 a1 findRoot
1657        let root = first.total
1658        let next = Word/add root (Transition.lit 1)
1659        let product = Word/mul a0 a1
1660        let small = Word/lt root Transition.capWord
1661        let lower = std:Bool.not (Word/lt product (Word/mul root root))
1662        let upper = Word/lt product (Word/mul next next)
1663        let smallRoot = belowCap h root (A.andLeft small (lower && upper) valid)
1664        let square = A.andRight small (lower && upper) valid
1665        let rootWord = mulCap h root root (atMostCap root smallRoot) (atMostCap root smallRoot)
1666        let prodWord = mulCap h a0 a1 (atMostCap a0 sa0) (atMostCap a1 sa1)
1667        let nextWord = addSmall h root (Transition.lit 1) smallRoot (Natural/subtract 2 cap, refl)
1668        let nextCap = A.eqTransLe (n next) (n root + 1) cap nextWord smallRoot
1669        let nextSquare = mulCap h next next nextCap nextCap
1670        let beyondLock = A.word256LtSound h (Transition.lit locked) root above
1671        let minted =
1672              A.word256SubExact h root (Transition.lit locked) (A.leOfLt locked (n root) beyondLock)
1673        in  { square =
1674                A.leTransEq
1675                  (n root * n root)
1676                  (n product)
1677                  (n a0 * n a1)
1678                  (A.eqTransLe
1679                     (n root * n root)
1680                     (n (Word/mul root root))
1681                     (n product)
1682                     (E.sym rootWord)
1683                     (leGuard h (Word/mul root root) product (A.andLeft lower upper square)))
1684                  prodWord
1685            , nextSquare =
1686                E.subst
1687                  (\(v : Natural) -> A.Lt (n a0 * n a1) (v * v))
1688                  nextWord
1689                  (E.subst
1690                     (\(v : Natural) -> A.Lt (n a0 * n a1) v)
1691                     nextSquare
1692                     (E.subst
1693                        (\(v : Natural) -> A.Lt v (n (Word/mul next next)))
1694                        prodWord
1695                        (A.word256LtSound
1696                           h
1697                           product
1698                           (Word/mul next next)
1699                           (A.andRight lower upper square))))
1700            , minted
1701            , positive =
1702                E.subst
1703                  (\(v : Natural) -> A.Lt 0 v)
1704                  (E.sym minted)
1705                  (firstMint h (n root) beyondLock)
1706            , fits = smallRoot
1707            }
1708
1709in  { transition =
1710        { low = lowWord
1711        , high = highWord
1712        , pack = packWord
1713        , swap
1714        , deposited
1715        , initialMint = \a0 a1 -> initialMint a0 a1 isqrt
1716        , liveMint
1717        , hasMinted
1718        , credit
1719        , keepsLock
1720        , burn
1721        }
1722    , Small
1723    , swapTransition
1724    , liveTransition
1725    , totalFits
1726    , preservesLiquidity
1727    , initialTransition
1728    , burnTransition
1729    , depositReserves
1730    , packRoundTrip
1731    }
Your result
Complete file: examples/evm/Pool/Foundation.omg · with imports