evm/Lending/Foundation

examples/evm/Lending/Foundation.omg

examples/evm/Lending/Foundation.omg2831 lines
1{-  The lending market's pure transitions and their kernel-checked laws.
2
3    One market lends a loan token against a collateral token, priced by an
4    oracle, and pays borrowers a reward token. Suppliers and borrowers hold
5    shares of the supplied and borrowed assets; interest compounds by a
6    kinked rate of the utilization and accrues to the suppliers, less a
7    protocol fee paid in supply shares. A position whose debt exceeds the
8    liquidation threshold of its collateral can be liquidated, with an
9    incentive, and a liquidation that takes all the collateral writes the
10    rest of the debt off against the suppliers.
11
12    The contract (../Lending.omg) computes with the functions of
13    `transition`, at Word 256. The theorems below read those very functions
14    through `Word/toNatural`: every word operation they use is exact under
15    the bounds the market keeps (stored totals below 2^127, amounts below
16    2^128, rates and time bounded), except the one product of the rewards
17    that the contract checks at run time.
18-}
19let A = std:Arith
20let E = std:Equal
21let R = std:Ring
22let B = std:Bool
23
24let U256 = Word 256
25let lit = Word/fromNatural 256
26let n = Word/toNatural @256
27
28-- Constants -----------------------------------------------------------------------------
29
30-- Fixed point: rates, fees and the liquidation threshold are fractions of
31-- `wad`; the oracle's price of one collateral unit in loan units is a
32-- fraction of `oracleScale`.
33let wad = 1000000000000000000
34let oracleScale = 1000000000000000000000000000000000000
35
36-- Virtual shares and assets: the first depositor cannot inflate the share
37-- price, and no conversion divides by zero.
38let virtualShares = 1000000
39let virtualAssets = 1
40
41-- Stored totals, positions and rewards stay below `cap`; amounts in calls
42-- are below 2^128; the price is below 2^128.
43let cap = std:Natural.pow2 127
44let amountCap = std:Natural.pow2 128
45let timeCap = std:Natural.pow2 64
46
47-- The largest protocol fee, borrow rate per second and accrued period.
48let maxFee = 250000000000000000
49let maxRate = 1000000000000
50let maxElapsed = std:Natural.pow2 32
51
52-- Rewards per borrow share are counted in units of 1 / rewardScale.
53let rewardScale = wad
54
55-- The liquidation incentive: min (maxIncentive, wad / (wad - cursor * (wad - lltv))).
56let cursor = 300000000000000000
57let maxIncentive = 1150000000000000000
58
59let wadW = lit wad
60let capW = lit cap
61let zero = lit 0
62let maxWord = Word/not zero
63
64-- Word helpers ----------------------------------------------------------------------------
65
66let min = \(x y : U256) -> if Word/lt y x then y else x
67let atLeast = \(x y : U256) -> B.not (Word/lt x y)
68let zeroFloorSub = \(x y : U256) -> if Word/lt x y then zero else Word/sub x y
69
70-- The product `x * y` does not wrap: x = 0, or y <= (2^256 - 1) / x.
71let mulFits = std:Word.productFits @256 maxWord
72
73-- Share conversions -----------------------------------------------------------------------
74
75-- Assets to shares and back, rounded down or up, against totals of assets
76-- and shares offset by the virtual ones. The rounding always favours the
77-- market: a supply mints at most, a withdrawal burns at least, a borrow
78-- owes at least and a repayment pays at least the exact quotient.
79let sharesDown =
80      \(assets total shares : U256) ->
81        Word/div
82          (Word/mul assets (Word/add shares (lit virtualShares)))
83          (Word/add total (lit virtualAssets))
84
85let sharesUp =
86      \(assets total shares : U256) ->
87        Word/div
88          (Word/add (Word/mul assets (Word/add shares (lit virtualShares))) total)
89          (Word/add total (lit virtualAssets))
90
91let assetsDown =
92      \(shares total totalShares : U256) ->
93        Word/div
94          (Word/mul shares (Word/add total (lit virtualAssets)))
95          (Word/add totalShares (lit virtualShares))
96
97let assetsUp =
98      \(shares total totalShares : U256) ->
99        Word/div
100          (Word/add
101             (Word/mul shares (Word/add total (lit virtualAssets)))
102             (Word/add totalShares (lit (Natural/subtract 1 virtualShares))))
103          (Word/add totalShares (lit virtualShares))
104
105-- The market --------------------------------------------------------------------------------
106
107let Market =
108      { borrowAssets : U256
109      , borrowShares : U256
110      , fee : U256
111      , lastUpdate : U256
112      , rewardRate : U256
113      , supplyAssets : U256
114      , supplyShares : U256
115      }
116
117-- The parameters the market is deployed with: the rate model (a base rate
118-- and two slopes per second, the kink of the utilization between them),
119-- the liquidation threshold and the liquidation incentive it implies.
120let Params =
121      { baseRate : U256, slope1 : U256, slope2 : U256, kink : U256, lltv : U256, incentive : U256 }
122
123-- Parameters a deployment accepts: 0 < lltv < wad, kink <= wad, and rates
124-- whose sum is at most maxRate.
125let validParams =
126      \(lltv kink baseRate slope1 slope2 : U256) ->
127        let small = \(r : U256) -> atLeast (lit maxRate) r
128        in  B.not (Word/isZero lltv)
129            && Word/lt lltv wadW
130            && atLeast wadW kink
131            && small baseRate
132            && small slope1
133            && small slope2
134            && small (Word/add (Word/add baseRate slope1) slope2)
135
136let incentiveOf =
137      \(lltv : U256) ->
138        let factor =
139              Word/div
140                (lit (wad * wad))
141                (Word/sub wadW (Word/div (Word/mul (lit cursor) (Word/sub wadW lltv)) wadW))
142        in  min (lit maxIncentive) factor
143
144-- An oracle price is usable when it is positive and below 2^128.
145let priceValid = \(price : U256) -> B.not (Word/isZero price) && Word/lt price (lit amountCap)
146
147-- Interest ----------------------------------------------------------------------------------
148
149-- The utilization, borrowed over supplied assets, at most one.
150let utilization =
151      \(borrow supply : U256) ->
152        if Word/isZero supply then zero else min wadW (Word/div (Word/mul borrow wadW) supply)
153
154-- The borrow rate per second: the base rate and the first slope up to the
155-- kink, then the second slope.
156let rate =
157      \(p : Params) (borrow supply : U256) ->
158        let u = utilization borrow supply
159        in  if Word/lt p.kink u
160            then Word/add
161                   (Word/add p.baseRate (Word/div (Word/mul p.kink p.slope1) wadW))
162                   (Word/div (Word/mul (Word/sub u p.kink) p.slope2) wadW)
163            else Word/add p.baseRate (Word/div (Word/mul u p.slope1) wadW)
164
165-- Continuous compounding by three terms of its Taylor series:
166-- x + x^2 / 2 + x^3 / 6, in wad.
167let growth =
168      \(x : U256) ->
169        let second = Word/div (Word/mul x x) (lit (2 * wad))
170        let third = Word/div (Word/mul second x) (lit (3 * wad))
171        in  Word/add (Word/add x second) third
172
173-- The seconds to accrue since the last update, at most maxElapsed.
174let elapsed =
175      \(lastUpdate now : U256) ->
176        if Word/lt lastUpdate now then min (lit maxElapsed) (Word/sub now lastUpdate) else zero
177
178-- An accrual over `seconds` > 0: the interest the borrowers owe goes to
179-- the suppliers, the protocol takes its fee of it in new supply shares, and
180-- the reward index grows by the rewards per borrow share.
181let accrue =
182      \(p : Params) (m : Market) (seconds now : U256) ->
183        let borrowRate = rate p m.borrowAssets m.supplyAssets
184        let interest =
185              Word/div (Word/mul m.borrowAssets (growth (Word/mul borrowRate seconds))) wadW
186        let feeAssets = Word/div (Word/mul interest m.fee) wadW
187        let supplyAssets = Word/add m.supplyAssets interest
188        let borrowAssets = Word/add m.borrowAssets interest
189        let feeShares = sharesDown feeAssets (Word/sub supplyAssets feeAssets) m.supplyShares
190        let supplyShares = Word/add m.supplyShares feeShares
191        let rewards =
192              Word/div
193                (Word/mul (Word/mul m.rewardRate seconds) (lit rewardScale))
194                (Word/add m.borrowShares (lit virtualShares))
195        in  { market = m // { borrowAssets, supplyAssets, supplyShares, lastUpdate = now }
196            , rate = borrowRate
197            , interest
198            , feeAssets
199            , feeShares
200            , rewards
201            , fits =
202                Word/lt supplyAssets capW
203                && Word/lt borrowAssets capW
204                && Word/lt supplyShares capW
205                && Word/lt now (lit timeCap)
206            }
207
208-- Supplying and withdrawing ---------------------------------------------------------------
209
210let supply =
211      \(m : Market) (assets : U256) ->
212        let shares = sharesDown assets m.supplyAssets m.supplyShares
213        let supplyAssets = Word/add m.supplyAssets assets
214        let supplyShares = Word/add m.supplyShares shares
215        in  { shares
216            , supplyAssets
217            , supplyShares
218            , fits = Word/lt supplyAssets capW && Word/lt supplyShares capW
219            }
220
221let withdraw =
222      \(m : Market) (assets held : U256) ->
223        let shares = sharesUp assets m.supplyAssets m.supplyShares
224        let supplyAssets = Word/sub m.supplyAssets assets
225        in  { shares
226            , covered = atLeast held shares
227            , held = Word/sub held shares
228            , supplyAssets
229            , supplyShares = Word/sub m.supplyShares shares
230            , liquid = atLeast supplyAssets m.borrowAssets
231            }
232
233-- Borrowing and repaying --------------------------------------------------------------------
234
235let borrow =
236      \(m : Market) (assets held : U256) ->
237        let shares = sharesUp assets m.borrowAssets m.borrowShares
238        let borrowAssets = Word/add m.borrowAssets assets
239        let borrowShares = Word/add m.borrowShares shares
240        in  { shares
241            , held = Word/add held shares
242            , borrowAssets
243            , borrowShares
244            , fits = Word/lt borrowAssets capW && Word/lt borrowShares capW
245            , liquid = atLeast m.supplyAssets borrowAssets
246            }
247
248let repay =
249      \(m : Market) (shares held : U256) ->
250        let assets = assetsUp shares m.borrowAssets m.borrowShares
251        in  { assets
252            , covered = atLeast held shares
253            , held = Word/sub held shares
254            , borrowAssets = zeroFloorSub m.borrowAssets assets
255            , borrowShares = Word/sub m.borrowShares shares
256            }
257
258-- Collateral and health -------------------------------------------------------------------
259
260let addCollateral =
261      \(collateral assets : U256) ->
262        let total = Word/add collateral assets in { collateral = total, fits = Word/lt total capW }
263
264let removeCollateral =
265      \(collateral assets : U256) ->
266        { collateral = Word/sub collateral assets, covered = atLeast collateral assets }
267
268-- The most a position may owe: its collateral at the oracle's price, times
269-- the liquidation threshold, rounded down.
270let maxBorrow =
271      \(p : Params) (collateral price : U256) ->
272        Word/div (Word/mul (Word/div (Word/mul collateral price) (lit oracleScale)) p.lltv) wadW
273
274-- A position is healthy when its debt, rounded up, is at most that.
275let healthy =
276      \(p : Params) (m : Market) (borrowShares collateral price : U256) ->
277        atLeast (maxBorrow p collateral price) (assetsUp borrowShares m.borrowAssets m.borrowShares)
278
279-- Liquidation -----------------------------------------------------------------------------
280
281{-  A liquidator seizes `seized` collateral of an unhealthy position and
282    repays its value at the oracle's price, less the incentive, in borrow
283    shares, every quotient rounded up. When no collateral remains, the rest
284    of the debt is bad debt: it leaves the borrowed and the supplied assets
285    alike. A repayment worth more than all the borrowed assets would need
286    more shares than exist, so it is not covered either; refusing it first
287    keeps the products below 2^256.
288-}
289let liquidate =
290      \(p : Params) (m : Market) (borrowShares collateral price seized : U256) ->
291        let quoted =
292              Word/div
293                (Word/add (Word/mul seized price) (lit (Natural/subtract 1 oracleScale)))
294                (lit oracleScale)
295        let value =
296              Word/div (Word/add (Word/mul quoted wadW) (Word/sub p.incentive (lit 1))) p.incentive
297        let repaid = sharesUp value m.borrowAssets m.borrowShares
298        let repaidAssets = assetsUp repaid m.borrowAssets m.borrowShares
299        let remaining = Word/sub borrowShares repaid
300        let left = Word/sub collateral seized
301        let totalShares = Word/sub m.borrowShares repaid
302        let totalAssets = zeroFloorSub m.borrowAssets repaidAssets
303        let bad = Word/isZero left && B.not (Word/isZero remaining)
304        let badDebt =
305              if bad then min totalAssets (assetsUp remaining totalAssets totalShares) else zero
306        let written = if bad then remaining else zero
307        in  { unhealthy = B.not (healthy p m borrowShares collateral price)
308            , collateralized = atLeast collateral seized
309            , covered = atLeast m.borrowAssets value && atLeast borrowShares repaid
310            , quoted
311            , value
312            , repaid
313            , repaidAssets
314            , badDebt
315            , borrowShares = Word/sub remaining written
316            , collateral = left
317            , borrowAssets = Word/sub totalAssets badDebt
318            , totalShares = Word/sub totalShares written
319            , supplyAssets = Word/sub m.supplyAssets badDebt
320            }
321
322-- Rewards ---------------------------------------------------------------------------------
323
324{-  A borrower's rewards since the index they last saw: the index is a
325    wrapping accumulator, so the difference is exact as long as it grew by
326    less than 2^256 in between. The product is checked: `ok` is False when
327    it would wrap, and the contract reverts with a panic then.
328-}
329let settle =
330      \(index seen borrowShares rewards : U256) ->
331        let delta = Word/sub index seen
332        let earned = Word/div (Word/mul borrowShares delta) (lit rewardScale)
333        let total = Word/add rewards earned
334        in  { rewards = total, ok = mulFits borrowShares delta, fits = Word/lt total capW }
335
336let transition =
337      { min
338      , zeroFloorSub
339      , sharesDown
340      , sharesUp
341      , assetsDown
342      , assetsUp
343      , validParams
344      , incentiveOf
345      , priceValid
346      , utilization
347      , rate
348      , growth
349      , elapsed
350      , accrue
351      , supply
352      , withdraw
353      , borrow
354      , repay
355      , addCollateral
356      , removeCollateral
357      , maxBorrow
358      , healthy
359      , liquidate
360      , settle
361      }
362
363-- Laws ----------------------------------------------------------------------------------
364
365{-  The theorems below are about the very functions of `transition`. Each
366    takes `std:Arith.NatFacts` explicitly, the six equations of the kernel's
367    arithmetic it rests on, and the bounds the market keeps as hypotheses:
368    stored totals below `cap` (`Total`), amounts below 2^128 (`Amount`), and
369    the guards a handler checks before it commits an update.
370-}
371let T = transition
372let N = std:Natural.pow2 256
373let VS = virtualShares
374
375let notTrue = std:Word/Law.notTrue
376let atLeastSound = std:Word/Law.atLeastSound
377
378-- Two numbers below bounds whose sum is at most N have a sum below N.
379let sumBelow
380    : forall (x y a b : Natural) -> A.Lt x a -> A.Lt y b -> A.Le (a + b) N -> A.Lt (x + y) N
381    = \x y a b px py bound ->
382        A.leTrans
383          (x + y + 1)
384          (x + 1 + (y + 1))
385          N
386          (1, refl)
387          (A.leTrans (x + 1 + (y + 1)) (a + b) N (A.lePlus (x + 1) a (y + 1) b px py) bound)
388
389-- The same for a product.
390let productBelow
391    : forall (h : A.NatFacts) (x y a b : Natural)
392      -> A.Le x a
393      -> A.Le y b
394      -> A.Lt (a * b) N
395      -> A.Lt (x * y) N
396    = \h x y a b px py bound -> A.leLtTrans (x * y) (a * b) N (A.leTimes h x a y b px py) bound
397
398-- Rounding up: x <= ceil(x / (e + 1)) * (e + 1).
399let ceilGe
400    : forall (h : A.NatFacts) (x e : Natural) -> A.Le x (Natural/div (x + e) (e + 1) * (e + 1))
401    = \h x e ->
402        let q = Natural/div (x + e) (e + 1)
403        let above : A.Lt (x + e) ((q + 1) * (e + 1)) = A.ltDivSucc h (x + e) e
404        let split : (q + 1) * (e + 1) === q * (e + 1) + (e + 1) = h.timesSucc q (e + 1)
405        in  A.lePlusCancel
406              x
407              (q * (e + 1))
408              (e + 1)
409              (A.leTransEq (x + (e + 1)) ((q + 1) * (e + 1)) (q * (e + 1) + (e + 1)) above split)
410
411-- A share price does not fall when a deposit mints at most its value:
412-- q * U <= a * T gives U * (T + q) <= (U + a) * T.
413let grow
414    : forall (h : A.NatFacts) (U T a q : Natural)
415      -> A.Le (q * U) (a * T)
416      -> A.Le (U * (T + q)) ((U + a) * T)
417    = \h U T a q bound ->
418        A.eqTransLe
419          (U * (T + q))
420          (U * T + q * U)
421          ((U + a) * T)
422          (E.trans
423             (A.distribLeft h U T q)
424             (E.cong (\(v : Natural) -> U * T + v) (A.timesComm h U q)))
425          (A.leTransEq
426             (U * T + q * U)
427             (U * T + a * T)
428             ((U + a) * T)
429             (A.lePlus (U * T) (U * T) (q * U) (a * T) (A.leRefl (U * T)) bound)
430             (E.sym (A.distribRight h U a T)))
431
432-- Nor when a withdrawal burns at least its value: a * T <= q * U with
433-- a <= U and q <= T gives U * (T - q) <= (U - a) * T.
434let shrink
435    : forall (h : A.NatFacts) (U T a q : Natural)
436      -> A.Le (a * T) (q * U)
437      -> A.Le a U
438      -> A.Le q T
439      -> A.Le (U * Natural/subtract q T) (Natural/subtract a U * T)
440    = \h U T a q bound smallA smallQ ->
441        let left = U * Natural/subtract q T
442        let right = Natural/subtract a U * T
443        let leftSum
444            : left + q * U === U * T
445            = E.trans
446                (E.cong (\(v : Natural) -> left + v) (A.timesComm h q U))
447                (E.trans
448                   (E.sym (A.distribLeft h U (Natural/subtract q T) q))
449                   (E.cong (\(v : Natural) -> U * v) (A.subtractOfLe h q T smallQ)))
450        let rightSum
451            : right + a * T === U * T
452            = E.trans
453                (E.sym (A.distribRight h (Natural/subtract a U) a T))
454                (E.cong (\(v : Natural) -> v * T) (A.subtractOfLe h a U smallA))
455        in  A.leElim
456              (a * T)
457              (q * U)
458              bound
459              (\d (spent : a * T + d === q * U) ->
460                 let equal
461                     : left + d === right
462                     = A.plusCancelRight
463                         (left + d)
464                         right
465                         (a * T)
466                         (E.trans
467                            (A.plusAssoc left d (a * T))
468                            (E.trans
469                               (E.cong
470                                  (\(v : Natural) -> left + v)
471                                  (E.trans (A.plusComm d (a * T)) spent))
472                               (E.trans leftSum (E.sym rightSum))))
473                 in  (d, equal))
474
475-- Stored totals are below the cap, amounts below 2^128.
476let Total = \(w : U256) -> A.Lt (n w) cap
477let Amount = \(w : U256) -> A.Lt (n w) amountCap
478
479let litLt =
480      \(h : A.NatFacts) (x y : Natural) (p : std:Natural.lessThan x y === True) ->
481        A.decideLtSound h x y p
482let litLe =
483      \(h : A.NatFacts) (x y : Natural) (p : std:Natural.lessThanEqual x y === True) ->
484        A.decideLeSound h x y p
485
486let addBelow
487    : forall (h : A.NatFacts) (x y : U256) (X Y : Natural)
488      -> A.Lt (n x) X
489      -> A.Lt (n y) Y
490      -> A.Le (X + Y) N
491      -> n (Word/add x y) === n x + n y
492    = \h x y X Y px py bound -> A.word256AddExact h x y (sumBelow (n x) (n y) X Y px py bound)
493
494let mulBelow
495    : forall (h : A.NatFacts) (x y : U256) (X Y : Natural)
496      -> A.Le (n x) X
497      -> A.Le (n y) Y
498      -> A.Lt (X * Y) N
499      -> n (Word/mul x y) === n x * n y
500    = \h x y X Y px py bound -> A.word256MulExact h x y (productBelow h (n x) (n y) X Y px py bound)
501
502-- Two numbers below bounds have a sum below any bound of the bounds' sum.
503let sumUnder
504    : forall (x y a b c : Natural) -> A.Lt x a -> A.Lt y b -> A.Le (a + b) c -> A.Lt (x + y) c
505    = \x y a b c px py bound ->
506        A.leTrans
507          (x + y + 1)
508          (x + 1 + (y + 1))
509          c
510          (1, refl)
511          (A.leTrans (x + 1 + (y + 1)) (a + b) c (A.lePlus (x + 1) a (y + 1) b px py) bound)
512
513let totalAmount
514    : forall (h : A.NatFacts) (w : U256) -> Total w -> Amount w
515    = \h w p -> A.ltLeTrans (n w) cap amountCap p (litLe h cap amountCap refl)
516
517-- The share and asset bases: a total plus its virtual offset.
518let shareBase
519    : forall (h : A.NatFacts) (s : U256) -> Total s -> n (Word/add s (lit VS)) === n s + VS
520    = \h s p ->
521        addBelow
522          h
523          s
524          (lit VS)
525          cap
526          amountCap
527          p
528          (litLt h VS amountCap refl)
529          (litLe h (cap + amountCap) N refl)
530
531let assetBase
532    : forall (h : A.NatFacts) (t : U256) -> Total t -> n (Word/add t (lit 1)) === n t + 1
533    = \h t p ->
534        addBelow
535          h
536          t
537          (lit 1)
538          cap
539          amountCap
540          p
541          (litLt h 1 amountCap refl)
542          (litLe h (cap + amountCap) N refl)
543
544let roundBase
545    : forall (h : A.NatFacts) (s : U256) -> Total s -> n (Word/add s (lit 999999)) === n s + 999999
546    = \h s p ->
547        addBelow
548          h
549          s
550          (lit 999999)
551          cap
552          amountCap
553          p
554          (litLt h 999999 amountCap refl)
555          (litLe h (cap + amountCap) N refl)
556
557-- An amount times a base, plus a total, is below 2^256.
558let scaled
559    : forall (h : A.NatFacts) (a b c : Natural)
560      -> A.Lt a amountCap
561      -> A.Lt b (cap + VS)
562      -> A.Lt c amountCap
563      -> A.Lt (a * b + c) N
564    = \h a b c pa pb pc ->
565        let bound
566            : A.Le (a * b) (Natural/subtract 1 amountCap * Natural/subtract 1 (cap + VS))
567            = A.leTimes
568                h
569                a
570                (Natural/subtract 1 amountCap)
571                b
572                (Natural/subtract 1 (cap + VS))
573                (A.leSuccCancel a (Natural/subtract 1 amountCap) pa)
574                (A.leSuccCancel b (Natural/subtract 1 (cap + VS)) pb)
575        in  A.leLtTrans
576              (a * b + c)
577              (Natural/subtract 1 amountCap * Natural/subtract 1 (cap + VS)
578               + Natural/subtract 1 amountCap)
579              N
580              (A.lePlus
581                 (a * b)
582                 (Natural/subtract 1 amountCap * Natural/subtract 1 (cap + VS))
583                 c
584                 (Natural/subtract 1 amountCap)
585                 bound
586                 (A.leSuccCancel c (Natural/subtract 1 amountCap) pc))
587              (litLt
588                 h
589                 (Natural/subtract 1 amountCap * Natural/subtract 1 (cap + VS)
590                  + Natural/subtract 1 amountCap)
591                 N
592                 refl)
593
594let lifted
595    : forall (h : A.NatFacts) (x : Natural) (k : Natural)
596      -> A.Lt x cap
597      -> std:Natural.lessThanEqual k VS === True
598      -> A.Lt (x + k) (cap + VS)
599    = \h x k p small ->
600        A.ltLeTrans
601          (x + k)
602          (cap + k)
603          (cap + VS)
604          (A.lePlus (x + 1) cap k k p (A.leRefl k))
605          (A.lePlus cap cap k VS (A.leRefl cap) (litLe h k VS small))
606
607-- The conversions are exact at the market's bounds.
608let SharesDown = \(a t s : Natural) -> Natural/div (a * (s + VS)) (t + 1)
609let SharesUp = \(a t s : Natural) -> Natural/div (a * (s + VS) + t) (t + 1)
610let AssetsUp = \(x t s : Natural) -> Natural/div (x * (t + 1) + (s + 999999)) (s + VS)
611
612-- The conversions compute their natural-number quotients exactly at the
613-- market's bounds: no product wraps.
614let sharesDownExact
615    : forall (h : A.NatFacts) (a t s : U256)
616      -> Amount a
617      -> Total t
618      -> Total s
619      -> n (T.sharesDown a t s) === SharesDown (n a) (n t) (n s)
620    = \h a t s pa pt ps ->
621        let base = shareBase h s ps
622        let product
623            : n (Word/mul a (Word/add s (lit VS))) === n a * (n s + VS)
624            = E.trans
625                (A.word256MulExact
626                   h
627                   a
628                   (Word/add s (lit VS))
629                   (E.subst
630                      (\(v : Natural) -> A.Lt (n a * v) N)
631                      (E.sym base)
632                      (A.leLtTrans
633                         (n a * (n s + VS))
634                         (n a * (n s + VS) + 0)
635                         N
636                         (A.leRefl (n a * (n s + VS)))
637                         (scaled
638                            h
639                            (n a)
640                            (n s + VS)
641                            0
642                            pa
643                            (lifted h (n s) VS ps refl)
644                            (litLt h 0 amountCap refl)))))
645                (E.cong (\(v : Natural) -> n a * v) base)
646        in  E.trans
647              (E.cong (\(v : Natural) -> Natural/div v (n (Word/add t (lit 1)))) product)
648              (E.cong (\(v : Natural) -> Natural/div (n a * (n s + VS)) v) (assetBase h t pt))
649
650let sharesUpExact
651    : forall (h : A.NatFacts) (a t s : U256)
652      -> Amount a
653      -> Total t
654      -> Total s
655      -> n (T.sharesUp a t s) === SharesUp (n a) (n t) (n s)
656    = \h a t s pa pt ps ->
657        let base = shareBase h s ps
658        let bounded =
659              scaled h (n a) (n s + VS) (n t) pa (lifted h (n s) VS ps refl) (totalAmount h t pt)
660        let product
661            : n (Word/mul a (Word/add s (lit VS))) === n a * (n s + VS)
662            = E.trans
663                (A.word256MulExact
664                   h
665                   a
666                   (Word/add s (lit VS))
667                   (E.subst
668                      (\(v : Natural) -> A.Lt (n a * v) N)
669                      (E.sym base)
670                      (A.leLtTrans
671                         (n a * (n s + VS))
672                         (n a * (n s + VS) + n t)
673                         N
674                         (A.lePlusRight (n a * (n s + VS)) (n t))
675                         bounded)))
676                (E.cong (\(v : Natural) -> n a * v) base)
677        let summed
678            : n (Word/add (Word/mul a (Word/add s (lit VS))) t) === n a * (n s + VS) + n t
679            = E.trans
680                (A.word256AddExact
681                   h
682                   (Word/mul a (Word/add s (lit VS)))
683                   t
684                   (E.subst (\(v : Natural) -> A.Lt (v + n t) N) (E.sym product) bounded))
685                (E.cong (\(v : Natural) -> v + n t) product)
686        in  E.trans
687              (E.cong (\(v : Natural) -> Natural/div v (n (Word/add t (lit 1)))) summed)
688              (E.cong (\(v : Natural) -> Natural/div (n a * (n s + VS) + n t) v) (assetBase h t pt))
689
690let assetsUpExact
691    : forall (h : A.NatFacts) (x t s : U256)
692      -> Amount x
693      -> Total t
694      -> Total s
695      -> n (T.assetsUp x t s) === AssetsUp (n x) (n t) (n s)
696    = \h x t s px pt ps ->
697        let base = assetBase h t pt
698        let bounded =
699              scaled
700                h
701                (n x)
702                (n t + 1)
703                (n s + 999999)
704                px
705                (lifted h (n t) 1 pt refl)
706                (A.ltLeTrans
707                   (n s + 999999)
708                   (cap + 999999)
709                   amountCap
710                   (A.lePlus (n s + 1) cap 999999 999999 ps (A.leRefl 999999))
711                   (litLe h (cap + 999999) amountCap refl))
712        let product
713            : n (Word/mul x (Word/add t (lit 1))) === n x * (n t + 1)
714            = E.trans
715                (A.word256MulExact
716                   h
717                   x
718                   (Word/add t (lit 1))
719                   (E.subst
720                      (\(v : Natural) -> A.Lt (n x * v) N)
721                      (E.sym base)
722                      (A.leLtTrans
723                         (n x * (n t + 1))
724                         (n x * (n t + 1) + (n s + 999999))
725                         N
726                         (A.lePlusRight (n x * (n t + 1)) (n s + 999999))
727                         bounded)))
728                (E.cong (\(v : Natural) -> n x * v) base)
729        let round = roundBase h s ps
730        let summed
731            : n (Word/add (Word/mul x (Word/add t (lit 1))) (Word/add s (lit 999999)))
732              === n x * (n t + 1) + (n s + 999999)
733            = E.trans
734                (A.word256AddExact
735                   h
736                   (Word/mul x (Word/add t (lit 1)))
737                   (Word/add s (lit 999999))
738                   (E.subst
739                      (\(v : Natural) -> A.Lt (n (Word/mul x (Word/add t (lit 1))) + v) N)
740                      (E.sym round)
741                      (E.subst
742                         (\(v : Natural) -> A.Lt (v + (n s + 999999)) N)
743                         (E.sym product)
744                         bounded)))
745                (E.trans
746                   (E.cong (\(v : Natural) -> v + n (Word/add s (lit 999999))) product)
747                   (E.cong (\(v : Natural) -> n x * (n t + 1) + v) round))
748        in  E.trans
749              (E.cong (\(v : Natural) -> Natural/div v (n (Word/add s (lit VS)))) summed)
750              (E.cong
751                 (\(v : Natural) -> Natural/div (n x * (n t + 1) + (n s + 999999)) v)
752                 (shareBase h s ps))
753
754-- A quotient by a positive divisor is at most the dividend.
755let divLe
756    : forall (h : A.NatFacts) (x e : Natural) -> A.Le (Natural/div x (e + 1)) x
757    = \h x e ->
758        A.leTrans
759          (Natural/div x (e + 1))
760          (Natural/div x (e + 1) * (e + 1))
761          x
762          (A.eqTransLe
763             (Natural/div x (e + 1))
764             (Natural/div x (e + 1) * 1)
765             (Natural/div x (e + 1) * (e + 1))
766             refl
767             (A.leTimesLeft h 1 (e + 1) (Natural/div x (e + 1)) (e, refl)))
768          (A.divTimesLe h x (e + 1))
769
770-- A guard `w < cap` makes w a total.
771let fitsTotal
772    : forall (h : A.NatFacts) (w : U256) -> Word/lt w capW === True -> Total w
773    = \h w p -> A.word256LtSound h w capW p
774
775{-  A supply mints the shares of its assets rounded down: the totals grow
776    exactly, fit, and the share price (assets + 1) / (shares + 10^6) does not
777    fall, so no existing supplier is diluted.
778-}
779let supplyTransition
780    : forall (h : A.NatFacts) (m : Market) (assets : U256)
781      -> Amount assets
782      -> Total m.supplyAssets
783      -> Total m.supplyShares
784      -> (T.supply m assets).fits === True
785      -> let next = T.supply m assets
786         in  { shares :
787                 n next.shares === SharesDown (n assets) (n m.supplyAssets) (n m.supplyShares)
788             , assets : n next.supplyAssets === n m.supplyAssets + n assets
789             , total : n next.supplyShares === n m.supplyShares + n next.shares
790             , assetsFit : Total next.supplyAssets
791             , sharesFit : Total next.supplyShares
792             , price :
793                 A.Le
794                   ((n m.supplyAssets + 1) * (n next.supplyShares + VS))
795                   ((n next.supplyAssets + 1) * (n m.supplyShares + VS))
796             }
797    = \h m assets pa pt ps fits ->
798        let next = T.supply m assets
799        let first = Word/lt next.supplyAssets capW
800        let second = Word/lt next.supplyShares capW
801        let shares = sharesDownExact h assets m.supplyAssets m.supplyShares pa pt ps
802        let added =
803              addBelow
804                h
805                m.supplyAssets
806                assets
807                cap
808                amountCap
809                pt
810                pa
811                (litLe h (cap + amountCap) N refl)
812        let minted
813            : A.Le (n next.shares) (n assets * (n m.supplyShares + VS))
814            = A.eqTransLe
815                (n next.shares)
816                (SharesDown (n assets) (n m.supplyAssets) (n m.supplyShares))
817                (n assets * (n m.supplyShares + VS))
818                shares
819                (divLe h (n assets * (n m.supplyShares + VS)) (n m.supplyAssets))
820        let total
821            : n next.supplyShares === n m.supplyShares + n next.shares
822            = A.word256AddExact
823                h
824                m.supplyShares
825                next.shares
826                (A.leLtTrans
827                   (n m.supplyShares + n next.shares)
828                   (n m.supplyShares + n assets * (n m.supplyShares + VS))
829                   N
830                   (A.lePlus
831                      (n m.supplyShares)
832                      (n m.supplyShares)
833                      (n next.shares)
834                      (n assets * (n m.supplyShares + VS))
835                      (A.leRefl (n m.supplyShares))
836                      minted)
837                   (E.subst
838                      (\(v : Natural) -> A.Lt v N)
839                      (A.plusComm (n assets * (n m.supplyShares + VS)) (n m.supplyShares))
840                      (scaled
841                         h
842                         (n assets)
843                         (n m.supplyShares + VS)
844                         (n m.supplyShares)
845                         pa
846                         (lifted h (n m.supplyShares) VS ps refl)
847                         (totalAmount h m.supplyShares ps))))
848        let U = n m.supplyAssets + 1
849        let V = n m.supplyShares + VS
850        let floor
851            : A.Le (n next.shares * U) (n assets * V)
852            = E.subst
853                (\(q : Natural) -> A.Le (q * U) (n assets * V))
854                (E.sym shares)
855                (A.divTimesLe h (n assets * V) U)
856        let grown = grow h U V (n assets) (n next.shares) floor
857        in  { shares
858            , assets = added
859            , total
860            , assetsFit = fitsTotal h next.supplyAssets (A.andLeft first second fits)
861            , sharesFit = fitsTotal h next.supplyShares (A.andRight first second fits)
862            , price =
863                E.subst
864                  (\(v : Natural) -> A.Le (U * (v + VS)) ((n next.supplyAssets + 1) * V))
865                  (E.sym total)
866                  (E.subst
867                     (\(v : Natural) -> A.Le (U * (V + n next.shares)) ((v + 1) * V))
868                     (E.sym added)
869                     grown)
870            }
871
872-- A guard `x >= y` and its exact difference.
873let subGuard
874    : forall (h : A.NatFacts) (x y : U256)
875      -> A.Le (n y) (n x)
876      -> n (Word/sub x y) === Natural/subtract (n y) (n x)
877    = \h x y p -> A.word256SubExact h x y p
878
879-- Subtracting from a sum with an offset: (x + k) - q = (x - q) + k for q <= x.
880let subtractShift
881    : forall (h : A.NatFacts) (q x k : Natural)
882      -> A.Le q x
883      -> Natural/subtract q (x + k) === Natural/subtract q x + k
884    = \h q x k p ->
885        A.plusCancelRight
886          (Natural/subtract q (x + k))
887          (Natural/subtract q x + k)
888          q
889          (E.trans
890             (A.subtractOfLe h q (x + k) (A.leTrans q x (x + k) p (A.lePlusRight x k)))
891             (E.trans
892                (E.cong (\(v : Natural) -> v + k) (E.sym (A.subtractOfLe h q x p)))
893                (A.plusSwapRight (Natural/subtract q x) q k)))
894
895let zeroFloorExact
896    : forall (h : A.NatFacts) (x y : U256)
897      -> n (T.zeroFloorSub x y) === Natural/subtract (n y) (n x)
898    = \h x y ->
899        A.boolCases
900          (\(b : Bool) ->
901             Word/lt x y === b
902             -> n (if b then lit 0 else Word/sub x y) === Natural/subtract (n y) (n x))
903          (Word/lt x y)
904          (\(less : Word/lt x y === True) _ ->
905             E.sym
906               (A.subtractOfGe h (n y) (n x) (A.leOfLt (n x) (n y) (A.word256LtSound h x y less))))
907          (\(more : Word/lt x y === False) _ ->
908             A.word256SubExact h x y (A.word256LtFalse h x y more))
909          refl
910
911{-  An admitted withdrawal burns at least the shares of its assets, from a
912    position that holds them: it takes no more assets than the market has,
913    the share price does not fall, and the market stays liquid.
914-}
915let withdrawTransition
916    : forall (h : A.NatFacts) (m : Market) (assets held : U256)
917      -> Amount assets
918      -> Total m.supplyAssets
919      -> Total m.supplyShares
920      -> A.Le (n held) (n m.supplyShares)
921      -> (T.withdraw m assets held).covered === True
922      -> (T.withdraw m assets held).liquid === True
923      -> let next = T.withdraw m assets held
924         in  { shares : n next.shares === SharesUp (n assets) (n m.supplyAssets) (n m.supplyShares)
925             , held : n next.held === Natural/subtract (n next.shares) (n held)
926             , covered : A.Le (n next.shares) (n held)
927             , total : n next.supplyShares === Natural/subtract (n next.shares) (n m.supplyShares)
928             , assets : n next.supplyAssets === Natural/subtract (n assets) (n m.supplyAssets)
929             , paid : A.Le (n assets) (n m.supplyAssets)
930             , liquid : A.Le (n m.borrowAssets) (n next.supplyAssets)
931             , price :
932                 A.Le
933                   ((n m.supplyAssets + 1) * (n next.supplyShares + VS))
934                   ((n next.supplyAssets + 1) * (n m.supplyShares + VS))
935             }
936    = \h m assets held pa pt ps holds covered liquid ->
937        let next = T.withdraw m assets held
938        let a = n assets
939        let q = n next.shares
940        let U = n m.supplyAssets + 1
941        let V = n m.supplyShares + VS
942        let shares = sharesUpExact h assets m.supplyAssets m.supplyShares pa pt ps
943        let enough : A.Le q (n held) = atLeastSound h held next.shares covered
944        let small : A.Le q (n m.supplyShares) = A.leTrans q (n held) (n m.supplyShares) enough holds
945        let ceiling
946            : A.Le (a * V) (q * U)
947            = E.subst
948                (\(v : Natural) -> A.Le (a * V) (v * U))
949                (E.sym shares)
950                (ceilGe h (a * V) (n m.supplyAssets))
951        let below
952            : A.Le (a * V) (n m.supplyShares * U)
953            = A.leTrans
954                (a * V)
955                (q * U)
956                (n m.supplyShares * U)
957                ceiling
958                (A.leTimesRight h q (n m.supplyShares) U small)
959        let paid
960            : A.Le a (n m.supplyAssets)
961            = merge
962                { Le =
963                    \(large : A.Le U a) ->
964                      A.exFalso
965                        (A.leLtAbsurd
966                           (U * V)
967                           (n m.supplyShares * U)
968                           (A.leTrans
969                              (U * V)
970                              (a * V)
971                              (n m.supplyShares * U)
972                              (A.leTimesRight h U a V large)
973                              below)
974                           (A.ltLeTrans
975                              (n m.supplyShares * U)
976                              (V * U)
977                              (U * V)
978                              (A.ltTimesRight
979                                 h
980                                 (n m.supplyShares)
981                                 V
982                                 (n m.supplyAssets)
983                                 (999999, refl))
984                              (A.leOfEq (V * U) (U * V) (A.timesComm h V U))))
985                , Gt = \(less : A.Lt a U) -> A.leSuccCancel a (n m.supplyAssets) less
986                }
987                (A.leTotal U a)
988        let assetsLeft = subGuard h m.supplyAssets assets paid
989        let sharesLeft = subGuard h m.supplyShares next.shares small
990        let shrunk =
991              shrink
992                h
993                U
994                V
995                a
996                q
997                ceiling
998                (A.leTrans a (n m.supplyAssets) U paid (A.lePlusRight (n m.supplyAssets) 1))
999                (A.leTrans q (n m.supplyShares) V small (A.lePlusRight (n m.supplyShares) VS))
1000        in  { shares
1001            , held = subGuard h held next.shares enough
1002            , covered = enough
1003            , total = sharesLeft
1004            , assets = assetsLeft
1005            , paid
1006            , liquid = atLeastSound h next.supplyAssets m.borrowAssets liquid
1007            , price =
1008                E.subst
1009                  (\(v : Natural) -> A.Le (U * (v + VS)) ((n next.supplyAssets + 1) * V))
1010                  (E.sym sharesLeft)
1011                  (E.subst
1012                     (\(v : Natural) ->
1013                        A.Le (U * (Natural/subtract q (n m.supplyShares) + VS)) ((v + 1) * V))
1014                     (E.sym assetsLeft)
1015                     (E.subst
1016                        (\(v : Natural) ->
1017                           A.Le (U * v) ((Natural/subtract a (n m.supplyAssets) + 1) * V))
1018                        (subtractShift h q (n m.supplyShares) VS small)
1019                        (E.subst
1020                           (\(v : Natural) -> A.Le (U * Natural/subtract q V) (v * V))
1021                           (subtractShift h a (n m.supplyAssets) 1 paid)
1022                           shrunk)))
1023            }
1024
1025{-  An admitted borrow owes at least its assets in debt shares, rounded up:
1026    the debt per share of the other borrowers does not rise, the totals
1027    grow exactly and fit, and the borrowed assets stay within the supply.
1028-}
1029let borrowTransition
1030    : forall (h : A.NatFacts) (m : Market) (assets held : U256)
1031      -> Amount assets
1032      -> Total m.borrowAssets
1033      -> Total m.borrowShares
1034      -> A.Le (n held) (n m.borrowShares)
1035      -> (T.borrow m assets held).fits === True
1036      -> (T.borrow m assets held).liquid === True
1037      -> let next = T.borrow m assets held
1038         in  { shares : n next.shares === SharesUp (n assets) (n m.borrowAssets) (n m.borrowShares)
1039             , assets : n next.borrowAssets === n m.borrowAssets + n assets
1040             , total : n next.borrowShares === n m.borrowShares + n next.shares
1041             , held : n next.held === n held + n next.shares
1042             , assetsFit : Total next.borrowAssets
1043             , sharesFit : Total next.borrowShares
1044             , liquid : A.Le (n next.borrowAssets) (n m.supplyAssets)
1045             , owes :
1046                 A.Le (n assets * (n m.borrowShares + VS)) (n next.shares * (n m.borrowAssets + 1))
1047             , price :
1048                 A.Le
1049                   ((n next.borrowAssets + 1) * (n m.borrowShares + VS))
1050                   ((n m.borrowAssets + 1) * (n next.borrowShares + VS))
1051             }
1052    = \h m assets held pa pt ps holds fits liquid ->
1053        let next = T.borrow m assets held
1054        let first = Word/lt next.borrowAssets capW
1055        let second = Word/lt next.borrowShares capW
1056        let b = n assets
1057        let q = n next.shares
1058        let V = n m.borrowAssets + 1
1059        let D = n m.borrowShares + VS
1060        let shares = sharesUpExact h assets m.borrowAssets m.borrowShares pa pt ps
1061        let minted
1062            : A.Le q (b * D + n m.borrowAssets)
1063            = A.eqTransLe
1064                q
1065                (SharesUp b (n m.borrowAssets) (n m.borrowShares))
1066                (b * D + n m.borrowAssets)
1067                shares
1068                (divLe h (b * D + n m.borrowAssets) (n m.borrowAssets))
1069        let sumFits
1070            : forall (x : U256) -> A.Le (n x) (n m.borrowShares) -> A.Lt (n x + q) N
1071            = \x small ->
1072                A.leLtTrans
1073                  (n x + q)
1074                  (b * D + n m.borrowAssets + n m.borrowShares)
1075                  N
1076                  (E.subst
1077                     (\(v : Natural) -> A.Le (n x + q) v)
1078                     (A.plusComm (n m.borrowShares) (b * D + n m.borrowAssets))
1079                     (A.lePlus (n x) (n m.borrowShares) q (b * D + n m.borrowAssets) small minted))
1080                  (E.subst
1081                     (\(v : Natural) -> A.Lt v N)
1082                     (E.sym (A.plusAssoc (b * D) (n m.borrowAssets) (n m.borrowShares)))
1083                     (scaled
1084                        h
1085                        b
1086                        D
1087                        (n m.borrowAssets + n m.borrowShares)
1088                        pa
1089                        (lifted h (n m.borrowShares) VS ps refl)
1090                        (sumUnder
1091                           (n m.borrowAssets)
1092                           (n m.borrowShares)
1093                           cap
1094                           cap
1095                           amountCap
1096                           pt
1097                           ps
1098                           (litLe h (cap + cap) amountCap refl))))
1099        let total =
1100              A.word256AddExact
1101                h
1102                m.borrowShares
1103                next.shares
1104                (sumFits m.borrowShares (A.leRefl (n m.borrowShares)))
1105        let added =
1106              addBelow
1107                h
1108                m.borrowAssets
1109                assets
1110                cap
1111                amountCap
1112                pt
1113                pa
1114                (litLe h (cap + amountCap) N refl)
1115        let ceiling
1116            : A.Le (b * D) (q * V)
1117            = E.subst
1118                (\(v : Natural) -> A.Le (b * D) (v * V))
1119                (E.sym shares)
1120                (ceilGe h (b * D) (n m.borrowAssets))
1121        let grown
1122            : A.Le (D * (V + b)) ((D + q) * V)
1123            = grow h D V q b ceiling
1124        in  { shares
1125            , assets = added
1126            , total
1127            , held = A.word256AddExact h held next.shares (sumFits held holds)
1128            , assetsFit = fitsTotal h next.borrowAssets (A.andLeft first second fits)
1129            , sharesFit = fitsTotal h next.borrowShares (A.andRight first second fits)
1130            , liquid = atLeastSound h m.supplyAssets next.borrowAssets liquid
1131            , owes = ceiling
1132            , price =
1133                E.subst
1134                  (\(v : Natural) -> A.Le ((v + 1) * D) (V * (n next.borrowShares + VS)))
1135                  (E.sym added)
1136                  (E.subst
1137                     (\(v : Natural) -> A.Le ((V + b) * D) (V * (v + VS)))
1138                     (E.sym total)
1139                     (A.eqTransLe
1140                        ((V + b) * D)
1141                        (D * (V + b))
1142                        (V * (D + q))
1143                        (A.timesComm h (V + b) D)
1144                        (A.leTransEq
1145                           (D * (V + b))
1146                           ((D + q) * V)
1147                           (V * (D + q))
1148                           grown
1149                           (A.timesComm h (D + q) V))))
1150            }
1151
1152{-  An admitted repayment pays, rounded up, at least the value of the shares
1153    it burns; the debt falls by what it pays, never below zero.
1154-}
1155let repayTransition
1156    : forall (h : A.NatFacts) (m : Market) (shares held : U256)
1157      -> Amount shares
1158      -> Total m.borrowAssets
1159      -> Total m.borrowShares
1160      -> A.Le (n held) (n m.borrowShares)
1161      -> (T.repay m shares held).covered === True
1162      -> let next = T.repay m shares held
1163         in  { assets : n next.assets === AssetsUp (n shares) (n m.borrowAssets) (n m.borrowShares)
1164             , covered : A.Le (n shares) (n held)
1165             , held : n next.held === Natural/subtract (n shares) (n held)
1166             , total : n next.borrowShares === Natural/subtract (n shares) (n m.borrowShares)
1167             , debt : n next.borrowAssets === Natural/subtract (n next.assets) (n m.borrowAssets)
1168             , paid :
1169                 A.Le (n shares * (n m.borrowAssets + 1)) (n next.assets * (n m.borrowShares + VS))
1170             }
1171    = \h m shares held px pt ps holds covered ->
1172        let next = T.repay m shares held
1173        let assets = assetsUpExact h shares m.borrowAssets m.borrowShares px pt ps
1174        let enough = atLeastSound h held shares covered
1175        in  { assets
1176            , covered = enough
1177            , held = subGuard h held shares enough
1178            , total =
1179                subGuard
1180                  h
1181                  m.borrowShares
1182                  shares
1183                  (A.leTrans (n shares) (n held) (n m.borrowShares) enough holds)
1184            , debt = zeroFloorExact h m.borrowAssets next.assets
1185            , paid =
1186                E.subst
1187                  (\(v : Natural) ->
1188                     A.Le (n shares * (n m.borrowAssets + 1)) (v * (n m.borrowShares + VS)))
1189                  (E.sym assets)
1190                  (ceilGe h (n shares * (n m.borrowAssets + 1)) (n m.borrowShares + 999999))
1191            }
1192
1193-- A bound on a product bounds the quotient: x * d <= y gives x <= y / d.
1194let quotientBound
1195    : forall (h : A.NatFacts) (x y e : Natural)
1196      -> A.Le (x * (e + 1)) y
1197      -> A.Le x (Natural/div y (e + 1))
1198    = \h x y e p ->
1199        merge
1200          { Le = \(fits : A.Le x (Natural/div y (e + 1))) -> fits
1201          , Gt =
1202              \(over : A.Lt (Natural/div y (e + 1)) x) ->
1203                A.exFalso
1204                  (A.leLtAbsurd
1205                     ((Natural/div y (e + 1) + 1) * (e + 1))
1206                     y
1207                     (A.leTrans
1208                        ((Natural/div y (e + 1) + 1) * (e + 1))
1209                        (x * (e + 1))
1210                        y
1211                        (A.leTimesRight h (Natural/div y (e + 1) + 1) x (e + 1) over)
1212                        p)
1213                     (A.ltDivSucc h y e))
1214          }
1215          (A.leTotal x (Natural/div y (e + 1)))
1216
1217-- A fraction k / (e + 1) <= 1 of s is at most s.
1218let scaleDown
1219    : forall (h : A.NatFacts) (k s e : Natural)
1220      -> A.Le k (e + 1)
1221      -> A.Le (Natural/div (k * s) (e + 1)) s
1222    = \h k s e small ->
1223        let q = Natural/div (k * s) (e + 1)
1224        in  A.leTimesCancel
1225              h
1226              q
1227              s
1228              e
1229              (A.leTrans
1230                 (q * (e + 1))
1231                 (k * s)
1232                 (s * (e + 1))
1233                 (A.divTimesLe h (k * s) (e + 1))
1234                 (A.leTransEq
1235                    (k * s)
1236                    ((e + 1) * s)
1237                    (s * (e + 1))
1238                    (A.leTimesRight h k (e + 1) s small)
1239                    (A.timesComm h (e + 1) s)))
1240
1241let addAtMost
1242    : forall (h : A.NatFacts) (x y : U256) (X Y : Natural)
1243      -> A.Le (n x) X
1244      -> A.Le (n y) Y
1245      -> A.Lt (X + Y) N
1246      -> n (Word/add x y) === n x + n y
1247    = \h x y X Y px py bound ->
1248        A.word256AddExact
1249          h
1250          x
1251          y
1252          (A.leLtTrans (n x + n y) (X + Y) N (A.lePlus (n x) X (n y) Y px py) bound)
1253
1254let minBounds
1255    : forall (h : A.NatFacts) (x y : U256)
1256      -> { left : A.Le (n (T.min x y)) (n x), right : A.Le (n (T.min x y)) (n y) }
1257    = \h x y ->
1258        A.boolCases
1259          (\(b : Bool) ->
1260             Word/lt y x === b
1261             -> { left : A.Le (n (if b then y else x)) (n x)
1262                , right : A.Le (n (if b then y else x)) (n y)
1263                })
1264          (Word/lt y x)
1265          (\(less : Word/lt y x === True) _ ->
1266             { left = A.leOfLt (n y) (n x) (A.word256LtSound h y x less), right = A.leRefl (n y) })
1267          (\(more : Word/lt y x === False) _ ->
1268             { left = A.leRefl (n x), right = A.word256LtFalse h y x more })
1269          refl
1270
1271let utilizationBound
1272    : forall (h : A.NatFacts) (b s : U256) -> A.Le (n (T.utilization b s)) wad
1273    = \h b s ->
1274        A.boolCases
1275          (\(z : Bool) ->
1276             Word/isZero s === z
1277             -> A.Le (n (if z then lit 0 else T.min wadW (Word/div (Word/mul b wadW) s))) wad)
1278          (Word/isZero s)
1279          (\_ _ -> A.leZero wad)
1280          (\_ _ -> (minBounds h wadW (Word/div (Word/mul b wadW) s)).left)
1281          refl
1282
1283-- The rate model's parameters, as the constructor admits them.
1284let Rates =
1285      \(p : Params) ->
1286        { base : A.Le (n p.baseRate) maxRate
1287        , slope1 : A.Le (n p.slope1) maxRate
1288        , slope2 : A.Le (n p.slope2) maxRate
1289        , sum : A.Le (n p.baseRate + n p.slope1 + n p.slope2) maxRate
1290        , kink : A.Le (n p.kink) wad
1291        }
1292
1293-- A slope times a fraction of at most wad, over wad, is exact and at most the slope.
1294let slopeTerm
1295    : forall (h : A.NatFacts) (f slope : U256)
1296      -> A.Le (n f) wad
1297      -> A.Le (n slope) maxRate
1298      -> { exact : n (Word/div (Word/mul f slope) wadW) === Natural/div (n f * n slope) wad
1299         , bound : A.Le (n (Word/div (Word/mul f slope) wadW)) (n slope)
1300         }
1301    = \h f slope pf ps ->
1302        let product = mulBelow h f slope wad maxRate pf ps (litLt h (wad * maxRate) N refl)
1303        let exact = E.cong (\(v : Natural) -> Natural/div v wad) product
1304        in  { exact
1305            , bound =
1306                A.eqTransLe
1307                  (n (Word/div (Word/mul f slope) wadW))
1308                  (Natural/div (n f * n slope) wad)
1309                  (n slope)
1310                  exact
1311                  (scaleDown h (n f) (n slope) (Natural/subtract 1 wad) pf)
1312            }
1313
1314-- The kinked borrow rate never exceeds the sum of its admitted parameters.
1315let rateBound
1316    : forall (h : A.NatFacts) (p : Params) (b s : U256)
1317      -> Rates p
1318      -> A.Le (n (T.rate p b s)) maxRate
1319    = \h p b s rates ->
1320        let u = T.utilization b s
1321        let uw = utilizationBound h b s
1322        let total
1323            : A.Le (n p.baseRate + n p.slope1) maxRate
1324            = A.leTrans
1325                (n p.baseRate + n p.slope1)
1326                (n p.baseRate + n p.slope1 + n p.slope2)
1327                maxRate
1328                (A.lePlusRight (n p.baseRate + n p.slope1) (n p.slope2))
1329                rates.sum
1330        in  A.boolCases
1331              (\(c : Bool) ->
1332                 Word/lt p.kink u === c
1333                 -> A.Le
1334                      (n
1335                         (if c
1336                          then Word/add
1337                                 (Word/add p.baseRate (Word/div (Word/mul p.kink p.slope1) wadW))
1338                                 (Word/div (Word/mul (Word/sub u p.kink) p.slope2) wadW)
1339                          else Word/add p.baseRate (Word/div (Word/mul u p.slope1) wadW)))
1340                      maxRate)
1341              (Word/lt p.kink u)
1342              (\(above : Word/lt p.kink u === True) _ ->
1343                 let first = slopeTerm h p.kink p.slope1 rates.kink rates.slope1
1344                 let below
1345                     : A.Le (n p.kink) (n u)
1346                     = A.leOfLt (n p.kink) (n u) (A.word256LtSound h p.kink u above)
1347                 let diff = subGuard h u p.kink below
1348                 let excess
1349                     : A.Le (n (Word/sub u p.kink)) wad
1350                     = A.eqTransLe
1351                         (n (Word/sub u p.kink))
1352                         (Natural/subtract (n p.kink) (n u))
1353                         wad
1354                         diff
1355                         (A.leTrans
1356                            (Natural/subtract (n p.kink) (n u))
1357                            (n u)
1358                            wad
1359                            (n p.kink, A.subtractOfLe h (n p.kink) (n u) below)
1360                            uw)
1361                 let second = slopeTerm h (Word/sub u p.kink) p.slope2 excess rates.slope2
1362                 let inner =
1363                       addAtMost
1364                         h
1365                         p.baseRate
1366                         (Word/div (Word/mul p.kink p.slope1) wadW)
1367                         maxRate
1368                         maxRate
1369                         rates.base
1370                         (A.leTrans
1371                            (n (Word/div (Word/mul p.kink p.slope1) wadW))
1372                            (n p.slope1)
1373                            maxRate
1374                            first.bound
1375                            rates.slope1)
1376                         (litLt h (maxRate + maxRate) N refl)
1377                 let innerBound
1378                     : A.Le
1379                         (n (Word/add p.baseRate (Word/div (Word/mul p.kink p.slope1) wadW)))
1380                         (n p.baseRate + n p.slope1)
1381                     = A.eqTransLe
1382                         _
1383                         _
1384                         _
1385                         inner
1386                         (A.lePlus
1387                            (n p.baseRate)
1388                            (n p.baseRate)
1389                            _
1390                            (n p.slope1)
1391                            (A.leRefl (n p.baseRate))
1392                            first.bound)
1393                 let outer =
1394                       addAtMost
1395                         h
1396                         (Word/add p.baseRate (Word/div (Word/mul p.kink p.slope1) wadW))
1397                         (Word/div (Word/mul (Word/sub u p.kink) p.slope2) wadW)
1398                         maxRate
1399                         maxRate
1400                         (A.leTrans _ (n p.baseRate + n p.slope1) maxRate innerBound total)
1401                         (A.leTrans _ (n p.slope2) maxRate second.bound rates.slope2)
1402                         (litLt h (maxRate + maxRate) N refl)
1403                 in  A.eqTransLe
1404                       _
1405                       _
1406                       maxRate
1407                       outer
1408                       (A.leTrans
1409                          _
1410                          (n p.baseRate + n p.slope1 + n p.slope2)
1411                          maxRate
1412                          (A.lePlus
1413                             _
1414                             (n p.baseRate + n p.slope1)
1415                             _
1416                             (n p.slope2)
1417                             innerBound
1418                             second.bound)
1419                          rates.sum))
1420              (\(_ : Word/lt p.kink u === False) _ ->
1421                 let first = slopeTerm h u p.slope1 uw rates.slope1
1422                 let sum =
1423                       addAtMost
1424                         h
1425                         p.baseRate
1426                         (Word/div (Word/mul u p.slope1) wadW)
1427                         maxRate
1428                         maxRate
1429                         rates.base
1430                         (A.leTrans _ (n p.slope1) maxRate first.bound rates.slope1)
1431                         (litLt h (maxRate + maxRate) N refl)
1432                 in  A.eqTransLe
1433                       _
1434                       _
1435                       maxRate
1436                       sum
1437                       (A.leTrans
1438                          _
1439                          (n p.baseRate + n p.slope1)
1440                          maxRate
1441                          (A.lePlus
1442                             (n p.baseRate)
1443                             (n p.baseRate)
1444                             _
1445                             (n p.slope1)
1446                             (A.leRefl (n p.baseRate))
1447                             first.bound)
1448                          total))
1449              refl
1450
1451-- Compounding over at most maxElapsed seconds at most maxRate a second.
1452let X = maxRate * maxElapsed
1453let S2 = Natural/div (X * X) (2 * wad)
1454let S3 = Natural/div (S2 * X) (3 * wad)
1455let GMax = X + S2 + S3
1456let Growth =
1457      \(y : Natural) ->
1458        let second = Natural/div (y * y) (2 * wad)
1459        in  y + second + Natural/div (second * y) (3 * wad)
1460
1461-- Three Taylor terms of compounding are exact and bounded over at most
1462-- 2^32 seconds at most `maxRate` a second.
1463let growthExact
1464    : forall (h : A.NatFacts) (x : U256)
1465      -> A.Le (n x) X
1466      -> { exact : n (T.growth x) === Growth (n x), bound : A.Le (Growth (n x)) GMax }
1467    = \h x px ->
1468        let y = n x
1469        let square = mulBelow h x x X X px px (litLt h (X * X) N refl)
1470        let secondWord = Word/div (Word/mul x x) (lit (2 * wad))
1471        let second = Natural/div (y * y) (2 * wad)
1472        let secondExact
1473            : n secondWord === second
1474            = E.cong (\(v : Natural) -> Natural/div v (2 * wad)) square
1475        let secondBound
1476            : A.Le second S2
1477            = quotientBound
1478                h
1479                second
1480                (X * X)
1481                (Natural/subtract 1 (2 * wad))
1482                (A.leTrans
1483                   (second * (2 * wad))
1484                   (y * y)
1485                   (X * X)
1486                   (A.divTimesLe h (y * y) (2 * wad))
1487                   (A.leTimes h y X y X px px))
1488        let secondWordBound
1489            : A.Le (n secondWord) S2
1490            = A.eqTransLe (n secondWord) second S2 secondExact secondBound
1491        let cubic = mulBelow h secondWord x S2 X secondWordBound px (litLt h (S2 * X) N refl)
1492        let thirdWord = Word/div (Word/mul secondWord x) (lit (3 * wad))
1493        let third = Natural/div (second * y) (3 * wad)
1494        let thirdExact
1495            : n thirdWord === third
1496            = E.trans
1497                (E.cong (\(v : Natural) -> Natural/div v (3 * wad)) cubic)
1498                (E.cong (\(v : Natural) -> Natural/div (v * y) (3 * wad)) secondExact)
1499        let thirdBound
1500            : A.Le third S3
1501            = quotientBound
1502                h
1503                third
1504                (S2 * X)
1505                (Natural/subtract 1 (3 * wad))
1506                (A.leTrans
1507                   (third * (3 * wad))
1508                   (second * y)
1509                   (S2 * X)
1510                   (A.divTimesLe h (second * y) (3 * wad))
1511                   (A.leTimes h second S2 y X secondBound px))
1512        let inner = addAtMost h x secondWord X S2 px secondWordBound (litLt h (X + S2) N refl)
1513        let innerBound
1514            : A.Le (n (Word/add x secondWord)) (X + S2)
1515            = A.eqTransLe
1516                _
1517                (y + n secondWord)
1518                (X + S2)
1519                inner
1520                (A.lePlus y X (n secondWord) S2 px secondWordBound)
1521        let outer =
1522              addAtMost
1523                h
1524                (Word/add x secondWord)
1525                thirdWord
1526                (X + S2)
1527                S3
1528                innerBound
1529                (A.eqTransLe (n thirdWord) third S3 thirdExact thirdBound)
1530                (litLt h GMax N refl)
1531        let exact
1532            : n (T.growth x) === Growth y
1533            = E.trans
1534                outer
1535                (E.trans
1536                   (E.cong
1537                      (\(v : Natural) -> v + n thirdWord)
1538                      (E.trans inner (E.cong (\(v : Natural) -> y + v) secondExact)))
1539                   (E.cong (\(v : Natural) -> y + second + v) thirdExact))
1540        in  { exact
1541            , bound =
1542                A.lePlus
1543                  (y + second)
1544                  (X + S2)
1545                  third
1546                  S3
1547                  (A.lePlus y X second S2 px secondBound)
1548                  thirdBound
1549            }
1550
1551-- The bounds the market keeps on its totals and settings.
1552let Bounded =
1553      \(m : Market) ->
1554        { borrowAssets : Total m.borrowAssets
1555        , borrowShares : Total m.borrowShares
1556        , supplyAssets : Total m.supplyAssets
1557        , supplyShares : Total m.supplyShares
1558        , fee : A.Le (n m.fee) maxFee
1559        , rewardRate : Amount m.rewardRate
1560        , liquid : A.Le (n m.borrowAssets) (n m.supplyAssets)
1561        }
1562
1563let below1 = \(w : U256) (p : Total w) -> A.leSuccCancel (n w) (Natural/subtract 1 cap) p
1564
1565-- The period an accrual covers is at most 2^32 seconds.
1566let elapsedBound
1567    : forall (h : A.NatFacts) (lastUpdate now : U256)
1568      -> A.Le (n (T.elapsed lastUpdate now)) maxElapsed
1569    = \h lastUpdate now ->
1570        A.boolCases
1571          (\(c : Bool) ->
1572             Word/lt lastUpdate now === c
1573             -> A.Le
1574                  (n (if c then T.min (lit maxElapsed) (Word/sub now lastUpdate) else lit 0))
1575                  maxElapsed)
1576          (Word/lt lastUpdate now)
1577          (\_ _ -> (minBounds h (lit maxElapsed) (Word/sub now lastUpdate)).left)
1578          (\_ _ -> A.leZero maxElapsed)
1579          refl
1580
1581{-  An accrual adds the same interest to the borrowed and the supplied
1582    assets, so the market stays liquid; the protocol's fee is at most the
1583    interest, and the fee shares it mints are worth at most the fee, at the
1584    price after the fee; the rewards per borrow share times the shares never
1585    exceed what the reward rate emits over the period.
1586-}
1587let accrueTransition
1588    : forall (h : A.NatFacts) (p : Params) (m : Market) (seconds now : U256)
1589      -> Rates p
1590      -> Bounded m
1591      -> A.Le (n seconds) maxElapsed
1592      -> (T.accrue p m seconds now).fits === True
1593      -> let next = T.accrue p m seconds now
1594         in  { rate : A.Le (n next.rate) maxRate
1595             , interest :
1596                 n next.interest
1597                 === Natural/div (n m.borrowAssets * Growth (n next.rate * n seconds)) wad
1598             , supplyAssets : n next.market.supplyAssets === n m.supplyAssets + n next.interest
1599             , borrowAssets : n next.market.borrowAssets === n m.borrowAssets + n next.interest
1600             , liquid : A.Le (n next.market.borrowAssets) (n next.market.supplyAssets)
1601             , fee : A.Le (n next.feeAssets) (n next.interest)
1602             , feeShares :
1603                 n next.feeShares
1604                 === SharesDown
1605                       (n next.feeAssets)
1606                       (Natural/subtract (n next.feeAssets) (n next.market.supplyAssets))
1607                       (n m.supplyShares)
1608             , supplyShares : n next.market.supplyShares === n m.supplyShares + n next.feeShares
1609             , dilution :
1610                 A.Le
1611                   ((Natural/subtract (n next.feeAssets) (n next.market.supplyAssets) + 1)
1612                    * (n next.market.supplyShares + VS))
1613                   ((n next.market.supplyAssets + 1) * (n m.supplyShares + VS))
1614             , rewards :
1615                 A.Le
1616                   (n next.rewards * (n m.borrowShares + VS))
1617                   (n m.rewardRate * n seconds * rewardScale)
1618             , supplyAssetsFit : Total next.market.supplyAssets
1619             , borrowAssetsFit : Total next.market.borrowAssets
1620             , supplySharesFit : Total next.market.supplyShares
1621             }
1622    = \h p m seconds now rates bounded passed fits ->
1623        let next = T.accrue p m seconds now
1624        let rateWord = T.rate p m.borrowAssets m.supplyAssets
1625        let rated = rateBound h p m.borrowAssets m.supplyAssets rates
1626        let exponent = Word/mul rateWord seconds
1627        let exponentExact =
1628              mulBelow h rateWord seconds maxRate maxElapsed rated passed (litLt h X N refl)
1629        let exponentBound
1630            : A.Le (n exponent) X
1631            = A.eqTransLe
1632                (n exponent)
1633                (n rateWord * n seconds)
1634                X
1635                exponentExact
1636                (A.leTimes h (n rateWord) maxRate (n seconds) maxElapsed rated passed)
1637        let grown = growthExact h exponent exponentBound
1638        let factor = T.growth exponent
1639        let factorBound
1640            : A.Le (n factor) GMax
1641            = A.eqTransLe (n factor) (Growth (n exponent)) GMax grown.exact grown.bound
1642        let product =
1643              mulBelow
1644                h
1645                m.borrowAssets
1646                factor
1647                (Natural/subtract 1 cap)
1648                GMax
1649                (below1 m.borrowAssets bounded.borrowAssets)
1650                factorBound
1651                (litLt h (Natural/subtract 1 cap * GMax) N refl)
1652        let interest
1653            : n next.interest
1654              === Natural/div (n m.borrowAssets * Growth (n rateWord * n seconds)) wad
1655            = E.trans
1656                (E.cong (\(v : Natural) -> Natural/div v wad) product)
1657                (E.cong
1658                   (\(v : Natural) -> Natural/div (n m.borrowAssets * v) wad)
1659                   (E.trans grown.exact (E.cong Growth exponentExact)))
1660        let interestBound
1661            : A.Le (n next.interest) (Natural/subtract 1 cap * GMax)
1662            = A.leTrans
1663                (n next.interest)
1664                (n m.borrowAssets * n factor)
1665                (Natural/subtract 1 cap * GMax)
1666                (A.eqTransLe
1667                   (n next.interest)
1668                   (Natural/div (n m.borrowAssets * n factor) wad)
1669                   (n m.borrowAssets * n factor)
1670                   (E.cong (\(v : Natural) -> Natural/div v wad) product)
1671                   (divLe h (n m.borrowAssets * n factor) (Natural/subtract 1 wad)))
1672                (A.leTimes
1673                   h
1674                   (n m.borrowAssets)
1675                   (Natural/subtract 1 cap)
1676                   (n factor)
1677                   GMax
1678                   (below1 m.borrowAssets bounded.borrowAssets)
1679                   factorBound)
1680        let grownTotal
1681            : forall (t : U256) -> Total t -> n (Word/add t next.interest) === n t + n next.interest
1682            = \t pt ->
1683                addAtMost
1684                  h
1685                  t
1686                  next.interest
1687                  (Natural/subtract 1 cap)
1688                  (Natural/subtract 1 cap * GMax)
1689                  (below1 t pt)
1690                  interestBound
1691                  (litLt h (Natural/subtract 1 cap + Natural/subtract 1 cap * GMax) N refl)
1692        let supplyAssets = grownTotal m.supplyAssets bounded.supplyAssets
1693        let borrowAssets = grownTotal m.borrowAssets bounded.borrowAssets
1694        let sA = Word/lt next.market.supplyAssets capW
1695        let bA = Word/lt next.market.borrowAssets capW
1696        let sS = Word/lt next.market.supplyShares capW
1697        let tC = Word/lt now (lit (std:Natural.pow2 64))
1698        let three = A.andLeft (sA && bA && sS) tC fits
1699        let two = A.andLeft (sA && bA) sS three
1700        let supplyAssetsFit = fitsTotal h next.market.supplyAssets (A.andLeft sA bA two)
1701        let borrowAssetsFit = fitsTotal h next.market.borrowAssets (A.andRight sA bA two)
1702        let supplySharesFit = fitsTotal h next.market.supplyShares (A.andRight (sA && bA) sS three)
1703        let interestTotal
1704            : A.Le (n next.interest) (n next.market.supplyAssets)
1705            = A.eqTransLe
1706                (n next.interest)
1707                (n next.interest + 0)
1708                (n next.market.supplyAssets)
1709                refl
1710                (A.leTransEq
1711                   (n next.interest)
1712                   (n m.supplyAssets + n next.interest)
1713                   (n next.market.supplyAssets)
1714                   (A.lePlusLeft (n m.supplyAssets) (n next.interest))
1715                   (E.sym supplyAssets))
1716        let interestSmall
1717            : A.Le (n next.interest) (Natural/subtract 1 cap)
1718            = A.leTrans
1719                (n next.interest)
1720                (n next.market.supplyAssets)
1721                (Natural/subtract 1 cap)
1722                interestTotal
1723                (below1 next.market.supplyAssets supplyAssetsFit)
1724        let feeProduct =
1725              mulBelow
1726                h
1727                next.interest
1728                m.fee
1729                (Natural/subtract 1 cap)
1730                maxFee
1731                interestSmall
1732                bounded.fee
1733                (litLt h (Natural/subtract 1 cap * maxFee) N refl)
1734        let feeExact
1735            : n next.feeAssets === Natural/div (n next.interest * n m.fee) wad
1736            = E.cong (\(v : Natural) -> Natural/div v wad) feeProduct
1737        let fee
1738            : A.Le (n next.feeAssets) (n next.interest)
1739            = A.eqTransLe
1740                (n next.feeAssets)
1741                (Natural/div (n m.fee * n next.interest) wad)
1742                (n next.interest)
1743                (E.trans
1744                   feeExact
1745                   (E.cong
1746                      (\(v : Natural) -> Natural/div v wad)
1747                      (A.timesComm h (n next.interest) (n m.fee))))
1748                (scaleDown
1749                   h
1750                   (n m.fee)
1751                   (n next.interest)
1752                   (Natural/subtract 1 wad)
1753                   (A.leTrans (n m.fee) maxFee wad bounded.fee (litLe h maxFee wad refl)))
1754        let feeTotal
1755            : A.Le (n next.feeAssets) (n next.market.supplyAssets)
1756            = A.leTrans
1757                (n next.feeAssets)
1758                (n next.interest)
1759                (n next.market.supplyAssets)
1760                fee
1761                interestTotal
1762        let base = Word/sub next.market.supplyAssets next.feeAssets
1763        let baseExact = subGuard h next.market.supplyAssets next.feeAssets feeTotal
1764        let baseTotal
1765            : Total base
1766            = A.leLtTrans
1767                (n base)
1768                (n next.market.supplyAssets)
1769                cap
1770                (A.eqTransLe
1771                   (n base)
1772                   (Natural/subtract (n next.feeAssets) (n next.market.supplyAssets))
1773                   (n next.market.supplyAssets)
1774                   baseExact
1775                   (n next.feeAssets,
1776                   A.subtractOfLe h (n next.feeAssets) (n next.market.supplyAssets) feeTotal))
1777                supplyAssetsFit
1778        let feeAmount
1779            : Amount next.feeAssets
1780            = totalAmount
1781                h
1782                next.feeAssets
1783                (A.leLtTrans
1784                   (n next.feeAssets)
1785                   (n next.market.supplyAssets)
1786                   cap
1787                   feeTotal
1788                   supplyAssetsFit)
1789        let feeShares
1790            : n next.feeShares
1791              === SharesDown
1792                    (n next.feeAssets)
1793                    (Natural/subtract (n next.feeAssets) (n next.market.supplyAssets))
1794                    (n m.supplyShares)
1795            = E.trans
1796                (sharesDownExact
1797                   h
1798                   next.feeAssets
1799                   base
1800                   m.supplyShares
1801                   feeAmount
1802                   baseTotal
1803                   bounded.supplyShares)
1804                (E.cong
1805                   (\(v : Natural) -> SharesDown (n next.feeAssets) v (n m.supplyShares))
1806                   baseExact)
1807        let minted
1808            : A.Le (n next.feeShares) (n next.feeAssets * (n m.supplyShares + VS))
1809            = A.eqTransLe
1810                (n next.feeShares)
1811                _
1812                _
1813                feeShares
1814                (divLe
1815                   h
1816                   (n next.feeAssets * (n m.supplyShares + VS))
1817                   (Natural/subtract (n next.feeAssets) (n next.market.supplyAssets)))
1818        let supplyShares
1819            : n next.market.supplyShares === n m.supplyShares + n next.feeShares
1820            = A.word256AddExact
1821                h
1822                m.supplyShares
1823                next.feeShares
1824                (A.leLtTrans
1825                   (n m.supplyShares + n next.feeShares)
1826                   (n m.supplyShares + n next.feeAssets * (n m.supplyShares + VS))
1827                   N
1828                   (A.lePlus
1829                      (n m.supplyShares)
1830                      (n m.supplyShares)
1831                      (n next.feeShares)
1832                      _
1833                      (A.leRefl (n m.supplyShares))
1834                      minted)
1835                   (E.subst
1836                      (\(v : Natural) -> A.Lt v N)
1837                      (A.plusComm (n next.feeAssets * (n m.supplyShares + VS)) (n m.supplyShares))
1838                      (scaled
1839                         h
1840                         (n next.feeAssets)
1841                         (n m.supplyShares + VS)
1842                         (n m.supplyShares)
1843                         feeAmount
1844                         (lifted h (n m.supplyShares) VS bounded.supplyShares refl)
1845                         (totalAmount h m.supplyShares bounded.supplyShares))))
1846        let U = Natural/subtract (n next.feeAssets) (n next.market.supplyAssets) + 1
1847        let V = n m.supplyShares + VS
1848        let floor
1849            : A.Le (n next.feeShares * U) (n next.feeAssets * V)
1850            = E.subst
1851                (\(q : Natural) -> A.Le (q * U) (n next.feeAssets * V))
1852                (E.sym feeShares)
1853                (A.divTimesLe h (n next.feeAssets * V) U)
1854        let grownShares = grow h U V (n next.feeAssets) (n next.feeShares) floor
1855        let restored
1856            : U + n next.feeAssets === n next.market.supplyAssets + 1
1857            = E.trans
1858                (A.plusSwapRight
1859                   (Natural/subtract (n next.feeAssets) (n next.market.supplyAssets))
1860                   1
1861                   (n next.feeAssets))
1862                (E.cong
1863                   (\(v : Natural) -> v + 1)
1864                   (A.subtractOfLe h (n next.feeAssets) (n next.market.supplyAssets) feeTotal))
1865        let rr = Word/mul m.rewardRate seconds
1866        let rrExact =
1867              mulBelow
1868                h
1869                m.rewardRate
1870                seconds
1871                (Natural/subtract 1 amountCap)
1872                maxElapsed
1873                (A.leSuccCancel (n m.rewardRate) (Natural/subtract 1 amountCap) bounded.rewardRate)
1874                passed
1875                (litLt h (Natural/subtract 1 amountCap * maxElapsed) N refl)
1876        let rrBound
1877            : A.Le (n rr) (Natural/subtract 1 amountCap * maxElapsed)
1878            = A.eqTransLe
1879                (n rr)
1880                _
1881                _
1882                rrExact
1883                (A.leTimes
1884                   h
1885                   (n m.rewardRate)
1886                   (Natural/subtract 1 amountCap)
1887                   (n seconds)
1888                   maxElapsed
1889                   (A.leSuccCancel
1890                      (n m.rewardRate)
1891                      (Natural/subtract 1 amountCap)
1892                      bounded.rewardRate)
1893                   passed)
1894        let emitted =
1895              mulBelow
1896                h
1897                rr
1898                (lit rewardScale)
1899                (Natural/subtract 1 amountCap * maxElapsed)
1900                rewardScale
1901                rrBound
1902                (A.leRefl rewardScale)
1903                (litLt h (Natural/subtract 1 amountCap * maxElapsed * rewardScale) N refl)
1904        let rewardsExact
1905            : n next.rewards
1906              === Natural/div (n m.rewardRate * n seconds * rewardScale) (n m.borrowShares + VS)
1907            = E.trans
1908                (E.cong
1909                   (\(v : Natural) -> Natural/div v (n (Word/add m.borrowShares (lit VS))))
1910                   (E.trans emitted (E.cong (\(v : Natural) -> v * rewardScale) rrExact)))
1911                (E.cong
1912                   (\(v : Natural) -> Natural/div (n m.rewardRate * n seconds * rewardScale) v)
1913                   (shareBase h m.borrowShares bounded.borrowShares))
1914        in  { rate = rated
1915            , interest
1916            , supplyAssets
1917            , borrowAssets
1918            , liquid =
1919                E.subst
1920                  (\(v : Natural) -> A.Le (n next.market.borrowAssets) v)
1921                  (E.sym supplyAssets)
1922                  (E.subst
1923                     (\(v : Natural) -> A.Le v (n m.supplyAssets + n next.interest))
1924                     (E.sym borrowAssets)
1925                     (A.lePlus
1926                        (n m.borrowAssets)
1927                        (n m.supplyAssets)
1928                        (n next.interest)
1929                        (n next.interest)
1930                        bounded.liquid
1931                        (A.leRefl (n next.interest))))
1932            , fee
1933            , feeShares
1934            , supplyShares
1935            , dilution =
1936                E.subst
1937                  (\(v : Natural) -> A.Le (U * (v + VS)) ((n next.market.supplyAssets + 1) * V))
1938                  (E.sym supplyShares)
1939                  (E.subst
1940                     (\(v : Natural) -> A.Le (U * (V + n next.feeShares)) (v * V))
1941                     restored
1942                     grownShares)
1943            , rewards =
1944                E.subst
1945                  (\(v : Natural) ->
1946                     A.Le (v * (n m.borrowShares + VS)) (n m.rewardRate * n seconds * rewardScale))
1947                  (E.sym rewardsExact)
1948                  (A.divTimesLe
1949                     h
1950                     (n m.rewardRate * n seconds * rewardScale)
1951                     (n m.borrowShares + VS))
1952            , supplyAssetsFit
1953            , borrowAssetsFit
1954            , supplySharesFit
1955            }
1956
1957-- A checked reward settlement credits exactly the borrower's share of the
1958-- reward index's growth since they last saw it.
1959let settleTransition
1960    : forall (h : A.NatFacts) (index seen borrowShares rewards : U256)
1961      -> Total rewards
1962      -> (T.settle index seen borrowShares rewards).ok === True
1963      -> (T.settle index seen borrowShares rewards).fits === True
1964      -> let next = T.settle index seen borrowShares rewards
1965         in  { rewards :
1966                 n next.rewards
1967                 === n rewards + Natural/div (n borrowShares * n (Word/sub index seen)) rewardScale
1968             , fits : Total next.rewards
1969             }
1970    = \h index seen borrowShares rewards pr ok fits ->
1971        let delta = Word/sub index seen
1972        let product = std:Word/Law.mulFitsSound h borrowShares delta ok
1973        let earnedWord = Word/div (Word/mul borrowShares delta) (lit rewardScale)
1974        let earned
1975            : n earnedWord === Natural/div (n borrowShares * n delta) rewardScale
1976            = E.cong (\(v : Natural) -> Natural/div v rewardScale) product
1977        let earnedBound
1978            : A.Le (n earnedWord) (Natural/div (Natural/subtract 1 N) rewardScale)
1979            = quotientBound
1980                h
1981                (n earnedWord)
1982                (Natural/subtract 1 N)
1983                (Natural/subtract 1 rewardScale)
1984                (A.leTrans
1985                   (n earnedWord * rewardScale)
1986                   (n (Word/mul borrowShares delta))
1987                   (Natural/subtract 1 N)
1988                   (A.divTimesLe h (n (Word/mul borrowShares delta)) rewardScale)
1989                   (A.leSuccCancel
1990                      (n (Word/mul borrowShares delta))
1991                      (Natural/subtract 1 N)
1992                      (A.word256Bound h (Word/mul borrowShares delta))))
1993        in  { rewards =
1994                E.trans
1995                  (addAtMost
1996                     h
1997                     rewards
1998                     earnedWord
1999                     (Natural/subtract 1 cap)
2000                     (Natural/div (Natural/subtract 1 N) rewardScale)
2001                     (below1 rewards pr)
2002                     earnedBound
2003                     (litLt
2004                        h
2005                        (Natural/subtract 1 cap + Natural/div (Natural/subtract 1 N) rewardScale)
2006                        N
2007                        refl))
2008                  (E.cong (\(v : Natural) -> n rewards + v) earned)
2009            , fits = fitsTotal h (T.settle index seen borrowShares rewards).rewards fits
2010            }
2011
2012let addCollateralTransition
2013    : forall (h : A.NatFacts) (collateral assets : U256)
2014      -> Total collateral
2015      -> Amount assets
2016      -> (T.addCollateral collateral assets).fits === True
2017      -> { collateral : n (T.addCollateral collateral assets).collateral === n collateral + n assets
2018         , fits : Total (T.addCollateral collateral assets).collateral
2019         }
2020    = \h collateral assets pc pa fits ->
2021        { collateral =
2022            addBelow h collateral assets cap amountCap pc pa (litLe h (cap + amountCap) N refl)
2023        , fits = fitsTotal h (T.addCollateral collateral assets).collateral fits
2024        }
2025
2026let removeCollateralTransition
2027    : forall (h : A.NatFacts) (collateral assets : U256)
2028      -> (T.removeCollateral collateral assets).covered === True
2029      -> { collateral :
2030             n (T.removeCollateral collateral assets).collateral
2031             === Natural/subtract (n assets) (n collateral)
2032         , covered : A.Le (n assets) (n collateral)
2033         }
2034    = \h collateral assets covered ->
2035        let enough = atLeastSound h collateral assets covered
2036        in  { collateral = subGuard h collateral assets enough, covered = enough }
2037
2038-- A usable price is positive and below 2^128.
2039let priceSound
2040    : forall (h : A.NatFacts) (price : U256)
2041      -> T.priceValid price === True
2042      -> { positive : A.Lt 0 (n price), small : Amount price }
2043    = \h price ok ->
2044        let nonzero = B.not (Word/isZero price)
2045        let below = Word/lt price (lit amountCap)
2046        let notZero
2047            : Natural/isZero (n price) === False
2048            = notTrue (Natural/isZero (n price)) (A.andLeft nonzero below ok)
2049        in  { positive =
2050                A.natCases
2051                  (\(v : Natural) -> Natural/isZero v === False -> A.Lt 0 v)
2052                  (\(p : True === False) -> A.exFalso (A.falseNotTrue (E.sym p)))
2053                  (\(k : Natural) (_ : False === False) -> (k, refl))
2054                  (n price)
2055                  notZero
2056            , small = A.word256LtSound h price (lit amountCap) (A.andRight nonzero below ok)
2057            }
2058
2059let VMax = Natural/div (Natural/subtract 1 cap * Natural/subtract 1 amountCap) oracleScale
2060
2061-- A healthy position owes, rounded up, at most its collateral's value times
2062-- the threshold: debt * oracleScale * wad <= collateral * price * lltv.
2063let healthySound
2064    : forall (h : A.NatFacts) (p : Params) (m : Market) (borrowShares collateral price : U256)
2065      -> Amount borrowShares
2066      -> Total m.borrowAssets
2067      -> Total m.borrowShares
2068      -> Total collateral
2069      -> Amount price
2070      -> A.Lt (n p.lltv) wad
2071      -> T.healthy p m borrowShares collateral price === True
2072      -> A.Le
2073           (AssetsUp (n borrowShares) (n m.borrowAssets) (n m.borrowShares) * (oracleScale * wad))
2074           (n collateral * n price * n p.lltv)
2075    = \h p m borrowShares collateral price pb pt ps pc pp lltv ok ->
2076        let debt = AssetsUp (n borrowShares) (n m.borrowAssets) (n m.borrowShares)
2077        let debtExact = assetsUpExact h borrowShares m.borrowAssets m.borrowShares pb pt ps
2078        let worth = Word/mul collateral price
2079        let worthExact =
2080              mulBelow
2081                h
2082                collateral
2083                price
2084                (Natural/subtract 1 cap)
2085                (Natural/subtract 1 amountCap)
2086                (below1 collateral pc)
2087                (A.leSuccCancel (n price) (Natural/subtract 1 amountCap) pp)
2088                (litLt h (Natural/subtract 1 cap * Natural/subtract 1 amountCap) N refl)
2089        let valueWord = Word/div worth (lit oracleScale)
2090        let value = Natural/div (n collateral * n price) oracleScale
2091        let valueExact
2092            : n valueWord === value
2093            = E.cong (\(v : Natural) -> Natural/div v oracleScale) worthExact
2094        let valueBound
2095            : A.Le value VMax
2096            = quotientBound
2097                h
2098                value
2099                (Natural/subtract 1 cap * Natural/subtract 1 amountCap)
2100                (Natural/subtract 1 oracleScale)
2101                (A.leTrans
2102                   (value * oracleScale)
2103                   (n collateral * n price)
2104                   (Natural/subtract 1 cap * Natural/subtract 1 amountCap)
2105                   (A.divTimesLe h (n collateral * n price) oracleScale)
2106                   (A.leTimes
2107                      h
2108                      (n collateral)
2109                      (Natural/subtract 1 cap)
2110                      (n price)
2111                      (Natural/subtract 1 amountCap)
2112                      (below1 collateral pc)
2113                      (A.leSuccCancel (n price) (Natural/subtract 1 amountCap) pp)))
2114        let scaledExact =
2115              mulBelow
2116                h
2117                valueWord
2118                p.lltv
2119                VMax
2120                (Natural/subtract 1 wad)
2121                (A.eqTransLe (n valueWord) value VMax valueExact valueBound)
2122                (A.leSuccCancel (n p.lltv) (Natural/subtract 1 wad) lltv)
2123                (litLt h (VMax * Natural/subtract 1 wad) N refl)
2124        let most = Natural/div (value * n p.lltv) wad
2125        let mostExact
2126            : n (T.maxBorrow p collateral price) === most
2127            = E.trans
2128                (E.cong (\(v : Natural) -> Natural/div v wad) scaledExact)
2129                (E.cong (\(v : Natural) -> Natural/div (v * n p.lltv) wad) valueExact)
2130        let owes
2131            : A.Le debt most
2132            = E.subst
2133                (\(v : Natural) -> A.Le v most)
2134                debtExact
2135                (E.subst
2136                   (\(v : Natural) ->
2137                      A.Le (n (T.assetsUp borrowShares m.borrowAssets m.borrowShares)) v)
2138                   mostExact
2139                   (atLeastSound
2140                      h
2141                      (T.maxBorrow p collateral price)
2142                      (T.assetsUp borrowShares m.borrowAssets m.borrowShares)
2143                      ok))
2144        let first
2145            : A.Le (debt * wad) (value * n p.lltv)
2146            = A.leTrans
2147                (debt * wad)
2148                (most * wad)
2149                (value * n p.lltv)
2150                (A.leTimesRight h debt most wad owes)
2151                (A.divTimesLe h (value * n p.lltv) wad)
2152        let vars = [ debt, value, n p.lltv ]
2153        in  A.eqTransLe
2154              (debt * (oracleScale * wad))
2155              (debt * wad * oracleScale)
2156              (n collateral * n price * n p.lltv)
2157              (R.ring
2158                 h
2159                 vars
2160                 (R.mul (R.var 0) (R.mul (R.const oracleScale) (R.const wad)))
2161                 (R.mul (R.mul (R.var 0) (R.const wad)) (R.const oracleScale))
2162                 refl)
2163              (A.leTrans
2164                 (debt * wad * oracleScale)
2165                 (value * n p.lltv * oracleScale)
2166                 (n collateral * n price * n p.lltv)
2167                 (A.leTimesRight h (debt * wad) (value * n p.lltv) oracleScale first)
2168                 (A.eqTransLe
2169                    (value * n p.lltv * oracleScale)
2170                    (value * oracleScale * n p.lltv)
2171                    (n collateral * n price * n p.lltv)
2172                    (R.ring
2173                       h
2174                       vars
2175                       (R.mul (R.mul (R.var 1) (R.var 2)) (R.const oracleScale))
2176                       (R.mul (R.mul (R.var 1) (R.const oracleScale)) (R.var 2))
2177                       refl)
2178                    (A.leTimesRight
2179                       h
2180                       (value * oracleScale)
2181                       (n collateral * n price)
2182                       (n p.lltv)
2183                       (A.divTimesLe h (n collateral * n price) oracleScale))))
2184
2185-- What the constructor's check admits: a threshold strictly between 0 and
2186-- wad, and the rate model's bounds.
2187let paramsSound
2188    : forall (h : A.NatFacts) (p : Params)
2189      -> T.validParams p.lltv p.kink p.baseRate p.slope1 p.slope2 === True
2190      -> { rates : Rates p, positive : A.Lt 0 (n p.lltv), lltv : A.Lt (n p.lltv) wad }
2191    = \h p ok ->
2192        let small = \(r : U256) -> B.not (Word/lt (lit maxRate) r)
2193        let a = B.not (Word/isZero p.lltv)
2194        let b = Word/lt p.lltv wadW
2195        let c = B.not (Word/lt wadW p.kink)
2196        let d = small p.baseRate
2197        let e = small p.slope1
2198        let f = small p.slope2
2199        let g = small (Word/add (Word/add p.baseRate p.slope1) p.slope2)
2200        let six = A.andLeft (a && b && c && d && e && f) g ok
2201        let five = A.andLeft (a && b && c && d && e) f six
2202        let four = A.andLeft (a && b && c && d) e five
2203        let three = A.andLeft (a && b && c) d four
2204        let two = A.andLeft (a && b) c three
2205        let base = atLeastSound h (lit maxRate) p.baseRate (A.andRight (a && b && c) d four)
2206        let slope1 = atLeastSound h (lit maxRate) p.slope1 (A.andRight (a && b && c && d) e five)
2207        let slope2 =
2208              atLeastSound h (lit maxRate) p.slope2 (A.andRight (a && b && c && d && e) f six)
2209        let inner =
2210              addAtMost
2211                h
2212                p.baseRate
2213                p.slope1
2214                maxRate
2215                maxRate
2216                base
2217                slope1
2218                (litLt h (maxRate + maxRate) N refl)
2219        let outer =
2220              addAtMost
2221                h
2222                (Word/add p.baseRate p.slope1)
2223                p.slope2
2224                (maxRate + maxRate)
2225                maxRate
2226                (A.eqTransLe
2227                   _
2228                   _
2229                   _
2230                   inner
2231                   (A.lePlus (n p.baseRate) maxRate (n p.slope1) maxRate base slope1))
2232                slope2
2233                (litLt h (maxRate + maxRate + maxRate) N refl)
2234        let summed =
2235              atLeastSound
2236                h
2237                (lit maxRate)
2238                (Word/add (Word/add p.baseRate p.slope1) p.slope2)
2239                (A.andRight (a && b && c && d && e && f) g ok)
2240        let positive = priceSound h p.lltv
2241        in  { rates =
2242                { base
2243                , slope1
2244                , slope2
2245                , sum =
2246                    E.subst
2247                      (\(v : Natural) -> A.Le v maxRate)
2248                      (E.trans outer (E.cong (\(v : Natural) -> v + n p.slope2) inner))
2249                      summed
2250                , kink = atLeastSound h wadW p.kink (A.andRight (a && b) c three)
2251                }
2252            , positive =
2253                A.natCases
2254                  (\(v : Natural) -> Natural/isZero v === False -> A.Lt 0 v)
2255                  (\(q : True === False) -> A.exFalso (A.falseNotTrue (E.sym q)))
2256                  (\(k : Natural) (_ : False === False) -> (k, refl))
2257                  (n p.lltv)
2258                  (notTrue (Natural/isZero (n p.lltv)) (A.andLeft a b two))
2259            , lltv = A.word256LtSound h p.lltv wadW (A.andRight a b two)
2260            }
2261
2262-- Subtracting less leaves more: a <= b <= c gives c - b <= c - a.
2263let subAnti
2264    : forall (h : A.NatFacts) (a b c : Natural)
2265      -> A.Le a b
2266      -> A.Le b c
2267      -> A.Le (Natural/subtract b c) (Natural/subtract a c)
2268    = \h a b c ab bc ->
2269        A.leElim
2270          a
2271          b
2272          ab
2273          (\d (eq : a + d === b) ->
2274             (d,
2275             A.plusCancelRight
2276               (Natural/subtract b c + d)
2277               (Natural/subtract a c)
2278               a
2279               (E.trans
2280                  (A.plusAssoc (Natural/subtract b c) d a)
2281                  (E.trans
2282                     (E.cong
2283                        (\(v : Natural) -> Natural/subtract b c + v)
2284                        (E.trans (A.plusComm d a) eq))
2285                     (E.trans
2286                        (A.subtractOfLe h b c bc)
2287                        (E.sym (A.subtractOfLe h a c (A.leTrans a b c ab bc))))))))
2288
2289-- The incentive of an admitted threshold is between 1 and 1.15, in wad.
2290let incentiveSound
2291    : forall (h : A.NatFacts) (lltv : U256)
2292      -> A.Lt (n lltv) wad
2293      -> { atLeast : A.Le wad (n (T.incentiveOf lltv))
2294         , atMost : A.Le (n (T.incentiveOf lltv)) maxIncentive
2295         }
2296    = \h lltv below ->
2297        let gap = Word/sub wadW lltv
2298        let gapExact = subGuard h wadW lltv (A.leOfLt (n lltv) wad below)
2299        let gapBound
2300            : A.Le (n gap) wad
2301            = A.eqTransLe
2302                (n gap)
2303                (Natural/subtract (n lltv) wad)
2304                wad
2305                gapExact
2306                (n lltv, A.subtractOfLe h (n lltv) wad (A.leOfLt (n lltv) wad below))
2307        let cut = Word/div (Word/mul (lit cursor) gap) wadW
2308        let cutExact
2309            : n cut === Natural/div (cursor * n gap) wad
2310            = E.cong
2311                (\(v : Natural) -> Natural/div v wad)
2312                (mulBelow
2313                   h
2314                   (lit cursor)
2315                   gap
2316                   cursor
2317                   wad
2318                   (A.leRefl cursor)
2319                   gapBound
2320                   (litLt h (cursor * wad) N refl))
2321        let cutBound
2322            : A.Le (n cut) cursor
2323            = A.eqTransLe
2324                (n cut)
2325                (Natural/div (cursor * n gap) wad)
2326                cursor
2327                cutExact
2328                (A.eqTransLe
2329                   (Natural/div (cursor * n gap) wad)
2330                   (Natural/div (n gap * cursor) wad)
2331                   cursor
2332                   (E.cong (\(v : Natural) -> Natural/div v wad) (A.timesComm h cursor (n gap)))
2333                   (scaleDown h (n gap) cursor (Natural/subtract 1 wad) gapBound))
2334        let denominator = Word/sub wadW cut
2335        let denominatorExact =
2336              subGuard h wadW cut (A.leTrans (n cut) cursor wad cutBound (litLe h cursor wad refl))
2337        let lowest = Natural/subtract cursor wad
2338        -- wad - cut is at least wad - cursor, and at most wad
2339        let denominatorLow
2340            : A.Le lowest (n denominator)
2341            = E.subst
2342                (\(v : Natural) -> A.Le lowest v)
2343                (E.sym denominatorExact)
2344                (subAnti h (n cut) cursor wad cutBound (litLe h cursor wad refl))
2345        let denominatorHigh
2346            : A.Le (n denominator) wad
2347            = A.eqTransLe
2348                (n denominator)
2349                (Natural/subtract (n cut) wad)
2350                wad
2351                denominatorExact
2352                (n cut,
2353                A.subtractOfLe
2354                  h
2355                  (n cut)
2356                  wad
2357                  (A.leTrans (n cut) cursor wad cutBound (litLe h cursor wad refl)))
2358        let positive
2359            : A.Lt 0 (n denominator)
2360            = A.leTrans 1 lowest (n denominator) (litLe h 1 lowest refl) denominatorLow
2361        let factor = Word/div (lit (wad * wad)) denominator
2362        let factorLow
2363            : A.Le wad (n factor)
2364            = A.leElim
2365                1
2366                (n denominator)
2367                positive
2368                (\k (eq : 1 + k === n denominator) ->
2369                   E.subst
2370                     (\(v : Natural) -> A.Le wad (Natural/div (wad * wad) v))
2371                     eq
2372                     (quotientBound
2373                        h
2374                        wad
2375                        (wad * wad)
2376                        k
2377                        (A.eqTransLe
2378                           (wad * (1 + k))
2379                           (wad * n denominator)
2380                           (wad * wad)
2381                           (E.cong (\(v : Natural) -> wad * v) eq)
2382                           (A.leTimesLeft h (n denominator) wad wad denominatorHigh))))
2383        let choose = minBounds h (lit maxIncentive) factor
2384        in  { atLeast =
2385                A.boolCases
2386                  (\(c : Bool) ->
2387                     Word/lt factor (lit maxIncentive) === c
2388                     -> A.Le wad (n (if c then factor else lit maxIncentive)))
2389                  (Word/lt factor (lit maxIncentive))
2390                  (\_ _ -> factorLow)
2391                  (\_ _ -> litLe h wad maxIncentive refl)
2392                  refl
2393            , atMost = choose.left
2394            }
2395
2396-- A truncated difference is at most the minuend.
2397let subLe
2398    : forall (h : A.NatFacts) (a b : Natural) -> A.Le (Natural/subtract a b) b
2399    = \h a b ->
2400        merge
2401          { Le = \(p : A.Le a b) -> (a, A.subtractOfLe h a b p)
2402          , Gt =
2403              \(p : A.Lt b a) ->
2404                A.eqTransLe
2405                  (Natural/subtract a b)
2406                  0
2407                  b
2408                  (A.subtractOfGe h a b (A.leOfLt b a p))
2409                  (A.leZero b)
2410          }
2411          (A.leTotal a b)
2412
2413-- x <= y and z <= x give x - z <= y - z.
2414let subMono
2415    : forall (h : A.NatFacts) (x y z : Natural)
2416      -> A.Le x y
2417      -> A.Le z x
2418      -> A.Le (Natural/subtract z x) (Natural/subtract z y)
2419    = \h x y z xy zx ->
2420        A.leElim
2421          x
2422          y
2423          xy
2424          (\d (eq : x + d === y) ->
2425             (d,
2426             A.plusCancelRight
2427               (Natural/subtract z x + d)
2428               (Natural/subtract z y)
2429               z
2430               (E.trans
2431                  (A.plusSwapRight (Natural/subtract z x) d z)
2432                  (E.trans
2433                     (E.cong (\(v : Natural) -> v + d) (A.subtractOfLe h z x zx))
2434                     (E.trans eq (E.sym (A.subtractOfLe h z y (A.leTrans z x y zx xy))))))))
2435
2436let QMax =
2437      Natural/div
2438        (Natural/subtract 1 cap * Natural/subtract 1 amountCap + Natural/subtract 1 oracleScale)
2439        oracleScale
2440
2441{-  A liquidation that the guards admit: it seizes at most the collateral,
2442    the liquidator repays at least the seized collateral's value at the
2443    oracle's price divided by the incentive (every rounding up), in at most
2444    the borrower's shares, and paying for those shares at least their value;
2445    the totals stay liquid after any bad debt is written off.
2446-}
2447let liquidateTransition
2448    : forall (h : A.NatFacts) (p : Params) (m : Market) (owed collateral price seized : U256)
2449      -> Total m.borrowAssets
2450      -> Total m.borrowShares
2451      -> Total m.supplyAssets
2452      -> A.Le (n m.borrowAssets) (n m.supplyAssets)
2453      -> A.Le (n owed) (n m.borrowShares)
2454      -> Total collateral
2455      -> Amount price
2456      -> A.Le wad (n p.incentive)
2457      -> A.Le (n p.incentive) maxIncentive
2458      -> (T.liquidate p m owed collateral price seized).collateralized === True
2459      -> (T.liquidate p m owed collateral price seized).covered === True
2460      -> let next = T.liquidate p m owed collateral price seized
2461         in  { seized : A.Le (n seized) (n collateral)
2462             , collateral : n next.collateral === Natural/subtract (n seized) (n collateral)
2463             , quoted : A.Le (n seized * n price) (n next.quoted * oracleScale)
2464             , value : A.Le (n next.quoted * wad) (n next.value * n p.incentive)
2465             , repaid :
2466                 n next.repaid === SharesUp (n next.value) (n m.borrowAssets) (n m.borrowShares)
2467             , covered : A.Le (n next.repaid) (n owed)
2468             , shares :
2469                 A.Le
2470                   (n next.value * (n m.borrowShares + VS))
2471                   (n next.repaid * (n m.borrowAssets + 1))
2472             , repaidAssets :
2473                 n next.repaidAssets
2474                 === AssetsUp (n next.repaid) (n m.borrowAssets) (n m.borrowShares)
2475             , paid :
2476                 A.Le
2477                   (n next.repaid * (n m.borrowAssets + 1))
2478                   (n next.repaidAssets * (n m.borrowShares + VS))
2479             , supplyAssets :
2480                 n next.supplyAssets === Natural/subtract (n next.badDebt) (n m.supplyAssets)
2481             , liquid : A.Le (n next.borrowAssets) (n next.supplyAssets)
2482             }
2483    = \h
2484       p
2485       m
2486       owed
2487       collateral
2488       price
2489       seized
2490       pbA
2491       pbS
2492       psA
2493       liquid
2494       holds
2495       pc
2496       pp
2497       atLeastWad
2498       atMostMax
2499       collateralized
2500       covered ->
2501        let next = T.liquidate p m owed collateral price seized
2502        let small : A.Le (n seized) (n collateral) = atLeastSound h collateral seized collateralized
2503        let seizedSmall
2504            : A.Le (n seized) (Natural/subtract 1 cap)
2505            = A.leTrans
2506                (n seized)
2507                (n collateral)
2508                (Natural/subtract 1 cap)
2509                small
2510                (below1 collateral pc)
2511        let priceSmall = A.leSuccCancel (n price) (Natural/subtract 1 amountCap) pp
2512        let worth =
2513              mulBelow
2514                h
2515                seized
2516                price
2517                (Natural/subtract 1 cap)
2518                (Natural/subtract 1 amountCap)
2519                seizedSmall
2520                priceSmall
2521                (litLt h (Natural/subtract 1 cap * Natural/subtract 1 amountCap) N refl)
2522        let worthBound
2523            : A.Le
2524                (n (Word/mul seized price))
2525                (Natural/subtract 1 cap * Natural/subtract 1 amountCap)
2526            = A.eqTransLe
2527                _
2528                _
2529                _
2530                worth
2531                (A.leTimes
2532                   h
2533                   (n seized)
2534                   (Natural/subtract 1 cap)
2535                   (n price)
2536                   (Natural/subtract 1 amountCap)
2537                   seizedSmall
2538                   priceSmall)
2539        let rounded =
2540              addAtMost
2541                h
2542                (Word/mul seized price)
2543                (lit (Natural/subtract 1 oracleScale))
2544                (Natural/subtract 1 cap * Natural/subtract 1 amountCap)
2545                (Natural/subtract 1 oracleScale)
2546                worthBound
2547                (A.leRefl (Natural/subtract 1 oracleScale))
2548                (litLt
2549                   h
2550                   (Natural/subtract 1 cap * Natural/subtract 1 amountCap
2551                    + Natural/subtract 1 oracleScale)
2552                   N
2553                   refl)
2554        let quotedExact
2555            : n next.quoted
2556              === Natural/div (n seized * n price + Natural/subtract 1 oracleScale) oracleScale
2557            = E.cong
2558                (\(v : Natural) -> Natural/div v oracleScale)
2559                (E.trans
2560                   rounded
2561                   (E.cong (\(v : Natural) -> v + Natural/subtract 1 oracleScale) worth))
2562        let quotedBound
2563            : A.Le (n next.quoted) QMax
2564            = A.eqTransLe
2565                (n next.quoted)
2566                _
2567                QMax
2568                quotedExact
2569                (quotientBound
2570                   h
2571                   (Natural/div (n seized * n price + Natural/subtract 1 oracleScale) oracleScale)
2572                   (Natural/subtract 1 cap * Natural/subtract 1 amountCap
2573                    + Natural/subtract 1 oracleScale)
2574                   (Natural/subtract 1 oracleScale)
2575                   (A.leTrans
2576                      _
2577                      (n seized * n price + Natural/subtract 1 oracleScale)
2578                      _
2579                      (A.divTimesLe
2580                         h
2581                         (n seized * n price + Natural/subtract 1 oracleScale)
2582                         oracleScale)
2583                      (A.lePlus
2584                         (n seized * n price)
2585                         (Natural/subtract 1 cap * Natural/subtract 1 amountCap)
2586                         (Natural/subtract 1 oracleScale)
2587                         (Natural/subtract 1 oracleScale)
2588                         (A.eqTransLe _ _ _ (E.sym worth) worthBound)
2589                         (A.leRefl (Natural/subtract 1 oracleScale)))))
2590        let incentiveLess =
2591              subGuard
2592                h
2593                p.incentive
2594                (lit 1)
2595                (A.leTrans 1 wad (n p.incentive) (litLe h 1 wad refl) atLeastWad)
2596        let incentiveLessBound
2597            : A.Le (n (Word/sub p.incentive (lit 1))) maxIncentive
2598            = A.eqTransLe
2599                _
2600                (Natural/subtract 1 (n p.incentive))
2601                maxIncentive
2602                incentiveLess
2603                (A.leTrans
2604                   (Natural/subtract 1 (n p.incentive))
2605                   (n p.incentive)
2606                   maxIncentive
2607                   (1,
2608                   A.subtractOfLe
2609                     h
2610                     1
2611                     (n p.incentive)
2612                     (A.leTrans 1 wad (n p.incentive) (litLe h 1 wad refl) atLeastWad))
2613                   atMostMax)
2614        let scaledQuote =
2615              mulBelow
2616                h
2617                next.quoted
2618                wadW
2619                QMax
2620                wad
2621                quotedBound
2622                (A.leRefl wad)
2623                (litLt h (QMax * wad) N refl)
2624        let numerator =
2625              addAtMost
2626                h
2627                (Word/mul next.quoted wadW)
2628                (Word/sub p.incentive (lit 1))
2629                (QMax * wad)
2630                maxIncentive
2631                (A.eqTransLe
2632                   _
2633                   _
2634                   _
2635                   scaledQuote
2636                   (A.leTimesRight h (n next.quoted) QMax wad quotedBound))
2637                incentiveLessBound
2638                (litLt h (QMax * wad + maxIncentive) N refl)
2639        let incentiveSplit
2640            : n p.incentive === Natural/subtract 1 (n p.incentive) + 1
2641            = E.sym
2642                (A.subtractOfLe
2643                   h
2644                   1
2645                   (n p.incentive)
2646                   (A.leTrans 1 wad (n p.incentive) (litLe h 1 wad refl) atLeastWad))
2647        let valueExact
2648            : n next.value
2649              === Natural/div
2650                    (n next.quoted * wad + Natural/subtract 1 (n p.incentive))
2651                    (n p.incentive)
2652            = E.cong
2653                (\(v : Natural) -> Natural/div v (n p.incentive))
2654                (E.trans
2655                   numerator
2656                   (E.trans
2657                      (E.cong (\(v : Natural) -> v + n (Word/sub p.incentive (lit 1))) scaledQuote)
2658                      (E.cong (\(v : Natural) -> n next.quoted * wad + v) incentiveLess)))
2659        let valueLaw
2660            : A.Le (n next.quoted * wad) (n next.value * n p.incentive)
2661            = E.subst
2662                (\(v : Natural) -> A.Le (n next.quoted * wad) (v * n p.incentive))
2663                (E.sym valueExact)
2664                (E.subst
2665                   (\(d : Natural) ->
2666                      A.Le
2667                        (n next.quoted * wad)
2668                        (Natural/div (n next.quoted * wad + Natural/subtract 1 (n p.incentive)) d
2669                         * d))
2670                   (E.sym incentiveSplit)
2671                   (ceilGe h (n next.quoted * wad) (Natural/subtract 1 (n p.incentive))))
2672        let enoughAssets = B.not (Word/lt m.borrowAssets next.value)
2673        let enoughShares = B.not (Word/lt owed next.repaid)
2674        let valueSmall
2675            : A.Le (n next.value) (n m.borrowAssets)
2676            = atLeastSound h m.borrowAssets next.value (A.andLeft enoughAssets enoughShares covered)
2677        let valueAmount
2678            : Amount next.value
2679            = totalAmount
2680                h
2681                next.value
2682                (A.leLtTrans (n next.value) (n m.borrowAssets) cap valueSmall pbA)
2683        let repaidExact =
2684              sharesUpExact h next.value m.borrowAssets m.borrowShares valueAmount pbA pbS
2685        let coveredShares
2686            : A.Le (n next.repaid) (n owed)
2687            = atLeastSound h owed next.repaid (A.andRight enoughAssets enoughShares covered)
2688        let repaidSmall
2689            : A.Le (n next.repaid) (n m.borrowShares)
2690            = A.leTrans (n next.repaid) (n owed) (n m.borrowShares) coveredShares holds
2691        let repaidAmount
2692            : Amount next.repaid
2693            = totalAmount
2694                h
2695                next.repaid
2696                (A.leLtTrans (n next.repaid) (n m.borrowShares) cap repaidSmall pbS)
2697        let repaidAssetsExact =
2698              assetsUpExact h next.repaid m.borrowAssets m.borrowShares repaidAmount pbA pbS
2699        let totalAssets = T.zeroFloorSub m.borrowAssets next.repaidAssets
2700        let totalAssetsExact = zeroFloorExact h m.borrowAssets next.repaidAssets
2701        let totalAssetsSmall
2702            : A.Le (n totalAssets) (n m.borrowAssets)
2703            = A.eqTransLe
2704                (n totalAssets)
2705                (Natural/subtract (n next.repaidAssets) (n m.borrowAssets))
2706                (n m.borrowAssets)
2707                totalAssetsExact
2708                (A.leTrans
2709                   _
2710                   (Natural/subtract (n next.repaidAssets) (n m.borrowAssets))
2711                   _
2712                   (A.leRefl _)
2713                   (subLe h (n next.repaidAssets) (n m.borrowAssets)))
2714        let remaining = Word/sub owed next.repaid
2715        let totalShares = Word/sub m.borrowShares next.repaid
2716        let bad = Word/isZero (Word/sub collateral seized) && B.not (Word/isZero remaining)
2717        let badDebtSmall
2718            : A.Le (n next.badDebt) (n totalAssets)
2719            = A.boolCases
2720                (\(c : Bool) ->
2721                   bad === c
2722                   -> A.Le
2723                        (n
2724                           (if c
2725                            then T.min totalAssets (T.assetsUp remaining totalAssets totalShares)
2726                            else lit 0))
2727                        (n totalAssets))
2728                bad
2729                (\_ _ ->
2730                   (minBounds h totalAssets (T.assetsUp remaining totalAssets totalShares)).left)
2731                (\_ _ -> A.leZero (n totalAssets))
2732                refl
2733        let badDebtSupply
2734            : A.Le (n next.badDebt) (n m.supplyAssets)
2735            = A.leTrans
2736                _
2737                (n totalAssets)
2738                _
2739                badDebtSmall
2740                (A.leTrans
2741                   (n totalAssets)
2742                   (n m.borrowAssets)
2743                   (n m.supplyAssets)
2744                   totalAssetsSmall
2745                   liquid)
2746        let supplyAssets = subGuard h m.supplyAssets next.badDebt badDebtSupply
2747        let borrowAssets = subGuard h totalAssets next.badDebt badDebtSmall
2748        in  { seized = small
2749            , collateral = subGuard h collateral seized small
2750            , quoted =
2751                E.subst
2752                  (\(v : Natural) -> A.Le (n seized * n price) (v * oracleScale))
2753                  (E.sym quotedExact)
2754                  (ceilGe h (n seized * n price) (Natural/subtract 1 oracleScale))
2755            , value = valueLaw
2756            , repaid = repaidExact
2757            , covered = coveredShares
2758            , shares =
2759                E.subst
2760                  (\(v : Natural) ->
2761                     A.Le (n next.value * (n m.borrowShares + VS)) (v * (n m.borrowAssets + 1)))
2762                  (E.sym repaidExact)
2763                  (ceilGe h (n next.value * (n m.borrowShares + VS)) (n m.borrowAssets))
2764            , repaidAssets = repaidAssetsExact
2765            , paid =
2766                E.subst
2767                  (\(v : Natural) ->
2768                     A.Le (n next.repaid * (n m.borrowAssets + 1)) (v * (n m.borrowShares + VS)))
2769                  (E.sym repaidAssetsExact)
2770                  (ceilGe h (n next.repaid * (n m.borrowAssets + 1)) (n m.borrowShares + 999999))
2771            , supplyAssets
2772            , liquid =
2773                E.subst
2774                  (\(v : Natural) -> A.Le v (n next.supplyAssets))
2775                  (E.sym borrowAssets)
2776                  (E.subst
2777                     (\(v : Natural) -> A.Le (Natural/subtract (n next.badDebt) (n totalAssets)) v)
2778                     (E.sym supplyAssets)
2779                     (subMono
2780                        h
2781                        (n totalAssets)
2782                        (n m.supplyAssets)
2783                        (n next.badDebt)
2784                        (A.leTrans
2785                           (n totalAssets)
2786                           (n m.borrowAssets)
2787                           (n m.supplyAssets)
2788                           totalAssetsSmall
2789                           liquid)
2790                        badDebtSmall))
2791            }
2792
2793in  { Market
2794    , Params
2795    , cap
2796    , maxFee
2797    , maxRate
2798    , wad
2799    , oracleScale
2800    , virtualShares
2801    , virtualAssets
2802    , rewardScale
2803    , transition
2804    , Total
2805    , Amount
2806    , Bounded
2807    , Rates
2808    , SharesDown
2809    , SharesUp
2810    , AssetsUp
2811    , Growth
2812    , sharesDownExact
2813    , sharesUpExact
2814    , assetsUpExact
2815    , supplyTransition
2816    , withdrawTransition
2817    , borrowTransition
2818    , repayTransition
2819    , rateBound
2820    , growthExact
2821    , elapsedBound
2822    , accrueTransition
2823    , settleTransition
2824    , addCollateralTransition
2825    , removeCollateralTransition
2826    , priceSound
2827    , healthySound
2828    , paramsSound
2829    , incentiveSound
2830    , liquidateTransition
2831    }
Your result
Complete file: examples/evm/Lending/Foundation.omg · with imports