Skip to content

Commit 63a4fcb

Browse files
committed
🚧 market: implement fixed repay position
1 parent 65c58cf commit 63a4fcb

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

‎src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ export { default as globalUtilization } from "./interest-rate-model/globalUtiliz
3131
export type { default as IRMParameters, IRMFloatingParameters } from "./interest-rate-model/Parameters.ts";
3232

3333
export { default as fixedRepayAssets } from "./market/fixedRepayAssets.js";
34+
export { default as fixedRepayPosition } from "./market/fixedRepayPosition.js";
3435
export { default as floatingDepositRates } from "./market/floatingDepositRates.js";
3536

3637
export { default as abs } from "./vector/abs.js";
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)