|
| 1 | +import type { FixedRepaySnapshot } from "./fixedRepayAssets.js"; |
| 2 | +import WAD from "../fixed-point-math/WAD.js"; |
| 3 | +import divWad from "../fixed-point-math/divWad.js"; |
| 4 | +import min from "../fixed-point-math/min.js"; |
| 5 | +import mulDiv from "../fixed-point-math/mulDiv.js"; |
| 6 | +import mulWad from "../fixed-point-math/mulWad.js"; |
| 7 | + |
| 8 | +export default function fixedRepayPosition( |
| 9 | + { |
| 10 | + penaltyRate, |
| 11 | + backupFeeRate, |
| 12 | + borrowed, |
| 13 | + supplied, |
| 14 | + unassignedEarnings, |
| 15 | + lastAccrual, |
| 16 | + principal, |
| 17 | + fee, |
| 18 | + }: FixedRepaySnapshot, |
| 19 | + maturity: number, |
| 20 | + assets: bigint, |
| 21 | + timestamp = Math.floor(Date.now() / 1000), |
| 22 | +) { |
| 23 | + const totalPosition = principal + fee; |
| 24 | + if (totalPosition === 0n) return 0n; |
| 25 | + if (timestamp >= lastAccrual) { |
| 26 | + return min(divWad(assets, WAD + BigInt(timestamp - maturity) * penaltyRate), totalPosition); |
| 27 | + } |
| 28 | + if (assets >= totalPosition) return totalPosition; |
| 29 | + if (maturity > lastAccrual) { |
| 30 | + unassignedEarnings -= mulDiv(unassignedEarnings, BigInt(timestamp) - lastAccrual, BigInt(maturity) - lastAccrual); |
| 31 | + } |
| 32 | + if (unassignedEarnings === 0n) return assets; |
| 33 | + const backupSupplied = borrowed - min(borrowed, supplied); |
| 34 | + if (backupSupplied === 0n) return assets; |
| 35 | + const k = divWad(principal, totalPosition); |
| 36 | + if (k === 0n) return assets; |
| 37 | + const netUnassignedEarnings = mulWad(unassignedEarnings, WAD - backupFeeRate); |
| 38 | + if (netUnassignedEarnings === 0n) return assets; |
| 39 | + const r = mulDiv(netUnassignedEarnings, k, backupSupplied); |
| 40 | + if (r >= WAD) return min(assets + netUnassignedEarnings, totalPosition); |
| 41 | + const x = divWad(assets, WAD - r); |
| 42 | + if (mulWad(k, x) <= backupSupplied && x <= totalPosition) return x; |
| 43 | + return min(assets + netUnassignedEarnings, totalPosition); |
| 44 | +} |
0 commit comments