@coffer_so/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +283 -0
  3. package/dist/clients/AdminClient.d.ts +194 -0
  4. package/dist/clients/AdminClient.d.ts.map +1 -0
  5. package/dist/clients/AdminClient.js +482 -0
  6. package/dist/clients/AdminClient.js.map +1 -0
  7. package/dist/clients/CofferBackendClient.d.ts +877 -0
  8. package/dist/clients/CofferBackendClient.d.ts.map +1 -0
  9. package/dist/clients/CofferBackendClient.js +536 -0
  10. package/dist/clients/CofferBackendClient.js.map +1 -0
  11. package/dist/clients/CubeBackendClient.d.ts +877 -0
  12. package/dist/clients/CubeBackendClient.d.ts.map +1 -0
  13. package/dist/clients/CubeBackendClient.js +536 -0
  14. package/dist/clients/CubeBackendClient.js.map +1 -0
  15. package/dist/clients/CubicPoolClient.d.ts +120 -0
  16. package/dist/clients/CubicPoolClient.d.ts.map +1 -0
  17. package/dist/clients/CubicPoolClient.js +687 -0
  18. package/dist/clients/CubicPoolClient.js.map +1 -0
  19. package/dist/clients/PoolFactoryClient.d.ts +53 -0
  20. package/dist/clients/PoolFactoryClient.d.ts.map +1 -0
  21. package/dist/clients/PoolFactoryClient.js +91 -0
  22. package/dist/clients/PoolFactoryClient.js.map +1 -0
  23. package/dist/clients/RpcClient.d.ts +49 -0
  24. package/dist/clients/RpcClient.d.ts.map +1 -0
  25. package/dist/clients/RpcClient.js +135 -0
  26. package/dist/clients/RpcClient.js.map +1 -0
  27. package/dist/clients/SingleTokenDepositClient.d.ts +67 -0
  28. package/dist/clients/SingleTokenDepositClient.d.ts.map +1 -0
  29. package/dist/clients/SingleTokenDepositClient.js +105 -0
  30. package/dist/clients/SingleTokenDepositClient.js.map +1 -0
  31. package/dist/clients/contract-instructions.d.ts +24 -0
  32. package/dist/clients/contract-instructions.d.ts.map +1 -0
  33. package/dist/clients/contract-instructions.js +130 -0
  34. package/dist/clients/contract-instructions.js.map +1 -0
  35. package/dist/clients/index.d.ts +10 -0
  36. package/dist/clients/index.d.ts.map +1 -0
  37. package/dist/clients/index.js +26 -0
  38. package/dist/clients/index.js.map +1 -0
  39. package/dist/clients/quote-math.d.ts +15 -0
  40. package/dist/clients/quote-math.d.ts.map +1 -0
  41. package/dist/clients/quote-math.js +98 -0
  42. package/dist/clients/quote-math.js.map +1 -0
  43. package/dist/clients/tx-builders.d.ts +231 -0
  44. package/dist/clients/tx-builders.d.ts.map +1 -0
  45. package/dist/clients/tx-builders.js +861 -0
  46. package/dist/clients/tx-builders.js.map +1 -0
  47. package/dist/clients/versioned.d.ts +34 -0
  48. package/dist/clients/versioned.d.ts.map +1 -0
  49. package/dist/clients/versioned.js +55 -0
  50. package/dist/clients/versioned.js.map +1 -0
  51. package/dist/config/index.d.ts +65 -0
  52. package/dist/config/index.d.ts.map +1 -0
  53. package/dist/config/index.js +75 -0
  54. package/dist/config/index.js.map +1 -0
  55. package/dist/config/networks.d.ts +12 -0
  56. package/dist/config/networks.d.ts.map +1 -0
  57. package/dist/config/networks.js +51 -0
  58. package/dist/config/networks.js.map +1 -0
  59. package/dist/config/tokens.d.ts +19 -0
  60. package/dist/config/tokens.d.ts.map +1 -0
  61. package/dist/config/tokens.js +43 -0
  62. package/dist/config/tokens.js.map +1 -0
  63. package/dist/idl/cubic_pool.json +4203 -0
  64. package/dist/idl/index.d.ts +1769 -0
  65. package/dist/idl/index.d.ts.map +1 -0
  66. package/dist/idl/index.js +18 -0
  67. package/dist/idl/index.js.map +1 -0
  68. package/dist/idl/protocol_admin.json +2615 -0
  69. package/dist/idl/single_token_liquidity.json +1121 -0
  70. package/dist/index.d.ts +75 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +206 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/math/cubicMath.d.ts +40 -0
  75. package/dist/math/cubicMath.d.ts.map +1 -0
  76. package/dist/math/cubicMath.js +82 -0
  77. package/dist/math/cubicMath.js.map +1 -0
  78. package/dist/math/fixedPoint.d.ts +19 -0
  79. package/dist/math/fixedPoint.d.ts.map +1 -0
  80. package/dist/math/fixedPoint.js +86 -0
  81. package/dist/math/fixedPoint.js.map +1 -0
  82. package/dist/math/index.d.ts +9 -0
  83. package/dist/math/index.d.ts.map +1 -0
  84. package/dist/math/index.js +30 -0
  85. package/dist/math/index.js.map +1 -0
  86. package/dist/math/logExp.d.ts +6 -0
  87. package/dist/math/logExp.d.ts.map +1 -0
  88. package/dist/math/logExp.js +68 -0
  89. package/dist/math/logExp.js.map +1 -0
  90. package/dist/math/lpLoss.d.ts +44 -0
  91. package/dist/math/lpLoss.d.ts.map +1 -0
  92. package/dist/math/lpLoss.js +103 -0
  93. package/dist/math/lpLoss.js.map +1 -0
  94. package/dist/math/maxSelloff.d.ts +164 -0
  95. package/dist/math/maxSelloff.d.ts.map +1 -0
  96. package/dist/math/maxSelloff.js +397 -0
  97. package/dist/math/maxSelloff.js.map +1 -0
  98. package/dist/math/singleToken.d.ts +54 -0
  99. package/dist/math/singleToken.d.ts.map +1 -0
  100. package/dist/math/singleToken.js +188 -0
  101. package/dist/math/singleToken.js.map +1 -0
  102. package/dist/math/slippage.d.ts +13 -0
  103. package/dist/math/slippage.d.ts.map +1 -0
  104. package/dist/math/slippage.js +44 -0
  105. package/dist/math/slippage.js.map +1 -0
  106. package/dist/math/surgeFee.d.ts +24 -0
  107. package/dist/math/surgeFee.d.ts.map +1 -0
  108. package/dist/math/surgeFee.js +85 -0
  109. package/dist/math/surgeFee.js.map +1 -0
  110. package/dist/math/weightedMath.d.ts +20 -0
  111. package/dist/math/weightedMath.d.ts.map +1 -0
  112. package/dist/math/weightedMath.js +66 -0
  113. package/dist/math/weightedMath.js.map +1 -0
  114. package/dist/parsers/borsh.d.ts +28 -0
  115. package/dist/parsers/borsh.d.ts.map +1 -0
  116. package/dist/parsers/borsh.js +104 -0
  117. package/dist/parsers/borsh.js.map +1 -0
  118. package/dist/parsers/contracts.d.ts +26 -0
  119. package/dist/parsers/contracts.d.ts.map +1 -0
  120. package/dist/parsers/contracts.js +62 -0
  121. package/dist/parsers/contracts.js.map +1 -0
  122. package/dist/parsers/events.d.ts +3 -0
  123. package/dist/parsers/events.d.ts.map +1 -0
  124. package/dist/parsers/events.js +281 -0
  125. package/dist/parsers/events.js.map +1 -0
  126. package/dist/parsers/index.d.ts +6 -0
  127. package/dist/parsers/index.d.ts.map +1 -0
  128. package/dist/parsers/index.js +22 -0
  129. package/dist/parsers/index.js.map +1 -0
  130. package/dist/parsers/mintAccount.d.ts +24 -0
  131. package/dist/parsers/mintAccount.d.ts.map +1 -0
  132. package/dist/parsers/mintAccount.js +27 -0
  133. package/dist/parsers/mintAccount.js.map +1 -0
  134. package/dist/parsers/poolAccount.d.ts +141 -0
  135. package/dist/parsers/poolAccount.d.ts.map +1 -0
  136. package/dist/parsers/poolAccount.js +224 -0
  137. package/dist/parsers/poolAccount.js.map +1 -0
  138. package/dist/types/contracts.d.ts +1340 -0
  139. package/dist/types/contracts.d.ts.map +1 -0
  140. package/dist/types/contracts.js +3 -0
  141. package/dist/types/contracts.js.map +1 -0
  142. package/dist/types/events.d.ts +172 -0
  143. package/dist/types/events.d.ts.map +1 -0
  144. package/dist/types/events.js +3 -0
  145. package/dist/types/events.js.map +1 -0
  146. package/dist/types/index.d.ts +6 -0
  147. package/dist/types/index.d.ts.map +1 -0
  148. package/dist/types/index.js +22 -0
  149. package/dist/types/index.js.map +1 -0
  150. package/dist/types/pool.d.ts +149 -0
  151. package/dist/types/pool.d.ts.map +1 -0
  152. package/dist/types/pool.js +3 -0
  153. package/dist/types/pool.js.map +1 -0
  154. package/dist/types/result.d.ts +24 -0
  155. package/dist/types/result.d.ts.map +1 -0
  156. package/dist/types/result.js +11 -0
  157. package/dist/types/result.js.map +1 -0
  158. package/dist/types/tx.d.ts +261 -0
  159. package/dist/types/tx.d.ts.map +1 -0
  160. package/dist/types/tx.js +3 -0
  161. package/dist/types/tx.js.map +1 -0
  162. package/dist/utils/errors.d.ts +44 -0
  163. package/dist/utils/errors.d.ts.map +1 -0
  164. package/dist/utils/errors.js +192 -0
  165. package/dist/utils/errors.js.map +1 -0
  166. package/dist/utils/extensions.d.ts +98 -0
  167. package/dist/utils/extensions.d.ts.map +1 -0
  168. package/dist/utils/extensions.js +187 -0
  169. package/dist/utils/extensions.js.map +1 -0
  170. package/dist/utils/index.d.ts +5 -0
  171. package/dist/utils/index.d.ts.map +1 -0
  172. package/dist/utils/index.js +21 -0
  173. package/dist/utils/index.js.map +1 -0
  174. package/dist/utils/pda.d.ts +8 -0
  175. package/dist/utils/pda.d.ts.map +1 -0
  176. package/dist/utils/pda.js +27 -0
  177. package/dist/utils/pda.js.map +1 -0
  178. package/dist/utils/retry.d.ts +22 -0
  179. package/dist/utils/retry.d.ts.map +1 -0
  180. package/dist/utils/retry.js +62 -0
  181. package/dist/utils/retry.js.map +1 -0
  182. package/package.json +54 -0
  183. package/src/clients/AdminClient.ts +608 -0
  184. package/src/clients/CofferBackendClient.ts +1413 -0
  185. package/src/clients/CubicPoolClient.ts +719 -0
  186. package/src/clients/PoolFactoryClient.ts +110 -0
  187. package/src/clients/RpcClient.ts +195 -0
  188. package/src/clients/SingleTokenDepositClient.ts +143 -0
  189. package/src/clients/contract-instructions.ts +115 -0
  190. package/src/clients/index.ts +9 -0
  191. package/src/clients/quote-math.ts +81 -0
  192. package/src/clients/tx-builders.ts +1096 -0
  193. package/src/clients/versioned.ts +80 -0
  194. package/src/config/index.ts +111 -0
  195. package/src/config/networks.ts +71 -0
  196. package/src/config/tokens.ts +52 -0
  197. package/src/idl/cubic_pool.json +4203 -0
  198. package/src/idl/index.ts +13 -0
  199. package/src/idl/protocol_admin.json +2615 -0
  200. package/src/idl/single_token_liquidity.json +1121 -0
  201. package/src/index.ts +262 -0
  202. package/src/math/cubicMath.ts +92 -0
  203. package/src/math/fixedPoint.ts +71 -0
  204. package/src/math/index.ts +13 -0
  205. package/src/math/logExp.ts +61 -0
  206. package/src/math/lpLoss.ts +160 -0
  207. package/src/math/maxSelloff.ts +564 -0
  208. package/src/math/singleToken.ts +251 -0
  209. package/src/math/slippage.ts +38 -0
  210. package/src/math/surgeFee.ts +101 -0
  211. package/src/math/weightedMath.ts +64 -0
  212. package/src/parsers/borsh.ts +106 -0
  213. package/src/parsers/contracts.ts +64 -0
  214. package/src/parsers/events.ts +275 -0
  215. package/src/parsers/index.ts +5 -0
  216. package/src/parsers/mintAccount.ts +44 -0
  217. package/src/parsers/poolAccount.ts +372 -0
  218. package/src/types/contracts.ts +238 -0
  219. package/src/types/events.ts +198 -0
  220. package/src/types/index.ts +5 -0
  221. package/src/types/pool.ts +147 -0
  222. package/src/types/result.ts +51 -0
  223. package/src/types/tx.ts +278 -0
  224. package/src/utils/errors.ts +210 -0
  225. package/src/utils/extensions.ts +196 -0
  226. package/src/utils/index.ts +4 -0
  227. package/src/utils/pda.ts +58 -0
  228. package/src/utils/retry.ts +85 -0
@@ -0,0 +1,564 @@
1
+ /**
2
+ * Sliding-window cumulative-sell rate limiter + variable sell-off surge fee.
3
+ *
4
+ * Port of the v5.1 (post-audit) contracts:
5
+ * `programs/cubic-pool/src/math/max_selloff.rs` (`check_and_advance`)
6
+ * `programs/cubic-pool/src/math/surge_fee.rs` (`calc_surge_fee_pct`)
7
+ * `programs/cubic-pool/src/instructions/user/swap.rs` (segmented charge)
8
+ *
9
+ * All arithmetic is bigint, mirroring the Rust u128 intermediates INCLUDING
10
+ * integer-division order — do not "simplify" a `a*b/c` into a different
11
+ * association, parity with the on-chain result depends on it. BN appears
12
+ * only at the SDK boundary.
13
+ *
14
+ * v5.1 curve model: the fee RATE is piecewise-LINEAR in the normalized
15
+ * window-fill coordinate `t ∈ [0, 1]` (threshold → 100% fill):
16
+ * - no kink: low → high over [0, 1]
17
+ * - kinked: low → mid over [0, k], mid → high over [k, 1]
18
+ * and a swap is charged the AVERAGE rate over the span it crosses
19
+ * (integral / width), which makes the fee path-independent — splitting a
20
+ * sell into parts cannot cheapen it (audit M-05). The old exponential
21
+ * convexity curve (A^t) is gone.
22
+ */
23
+
24
+ import BN from "bn.js";
25
+ import { PERCENT_SCALE } from "../config";
26
+ import { ONE, assertInteger, assertU64, assertU128, mulDown } from "./fixedPoint";
27
+
28
+ const SCALE = BigInt(PERCENT_SCALE); // 10_000
29
+
30
+ /** Mirrors cubic-pool::constants::SURGE_FEE_SEGMENTS. */
31
+ export const SURGE_FEE_SEGMENTS = 4;
32
+
33
+ export interface SelloffWindowInputs {
34
+ maxSelloffPct: number;
35
+ periodLength: number;
36
+ previousSelloff: BN;
37
+ currentSelloff: BN;
38
+ windowStartTimestamp: BN;
39
+ selloffVbSnapshot: BN;
40
+ /** Current pre-trade virtual balance of the token. */
41
+ virtualBalance: BN;
42
+ /** Unix seconds. */
43
+ now: number;
44
+ }
45
+
46
+ export interface SelloffWindowStatus {
47
+ /** True when the limiter is configured (`maxSelloffPct > 0`). */
48
+ enabled: boolean;
49
+ cap: BN;
50
+ /** Effective decayed usage WITHOUT a hypothetical trade. */
51
+ used: BN;
52
+ /** `max(0, cap - used)`. */
53
+ remaining: BN;
54
+ /** `used/cap` in PERCENT_SCALE units (0..10_000+); 0 when disabled/cap=0. */
55
+ fillPct: number;
56
+ windowStartTimestamp: BN;
57
+ periodLength: number;
58
+ /** Whether the projection at `now` rotated the window vs stored state. */
59
+ rotated: boolean;
60
+ /** Snapshot the cap was resolved against (post-projection). */
61
+ vbSnapshot: BN;
62
+ }
63
+
64
+ /** Result of the pure bigint window projection. */
65
+ export interface WindowProjection {
66
+ opened: boolean;
67
+ windowStart: bigint;
68
+ elapsedInWindow: bigint;
69
+ /** Carried-over previous usage, POST v5.1 snapshot rescale. */
70
+ previous: bigint;
71
+ current: bigint;
72
+ vbSnapshot: bigint;
73
+ cap: bigint;
74
+ weightedPrev: bigint;
75
+ /** weightedPrev + current (decayed effective, WITHOUT a hypothetical trade). */
76
+ usedWithoutTrade: bigint;
77
+ }
78
+
79
+ /**
80
+ * Pure bigint projection of the sliding window at `now`. Mirrors v5.1
81
+ * `check_and_advance`'s rotation + snapshot logic (read-only, no
82
+ * `amount_in`), including the audit addition: when the projection OPENS a
83
+ * window against a new vb snapshot, the carried-over `previous` usage is
84
+ * rescaled by `newSnapshot / oldSnapshot` so a liquidity change between
85
+ * windows doesn't distort the carried percentage.
86
+ */
87
+ export function projectSelloffWindow(params: {
88
+ maxSelloffPct: number;
89
+ periodLength: number;
90
+ previousSelloff: bigint;
91
+ currentSelloff: bigint;
92
+ windowStartTimestamp: bigint;
93
+ selloffVbSnapshot: bigint;
94
+ virtualBalance: bigint;
95
+ now: number;
96
+ }): WindowProjection {
97
+ const period = BigInt(params.periodLength);
98
+ const storedWs = params.windowStartTimestamp;
99
+ const nowBI = BigInt(Math.trunc(params.now));
100
+
101
+ const rawElapsed = nowBI - storedWs;
102
+ const elapsed = rawElapsed < 0n ? 0n : rawElapsed;
103
+
104
+ let prev: bigint;
105
+ let cur: bigint;
106
+ let ws: bigint;
107
+ let eiw: bigint;
108
+ let opened: boolean;
109
+
110
+ if (period > 0n && elapsed >= 2n * period) {
111
+ prev = 0n;
112
+ cur = 0n;
113
+ ws = nowBI;
114
+ eiw = 0n;
115
+ opened = true;
116
+ } else if (period > 0n && elapsed >= period) {
117
+ ws = storedWs + period;
118
+ const e = nowBI - ws;
119
+ eiw = e < 0n ? 0n : e;
120
+ prev = params.currentSelloff;
121
+ cur = 0n;
122
+ opened = true;
123
+ } else if (period <= 0n) {
124
+ // Degenerate config (rejected on-chain by `require!(period > 0)`);
125
+ // treat as a fresh reset so callers never divide by zero.
126
+ prev = 0n;
127
+ cur = 0n;
128
+ ws = nowBI;
129
+ eiw = 0n;
130
+ opened = true;
131
+ } else {
132
+ prev = params.previousSelloff;
133
+ cur = params.currentSelloff;
134
+ ws = storedWs;
135
+ eiw = elapsed;
136
+ opened = false;
137
+ }
138
+
139
+ const oldSnapshot = params.selloffVbSnapshot;
140
+ const vbSnapshot =
141
+ opened || oldSnapshot === 0n ? params.virtualBalance : oldSnapshot;
142
+
143
+ // v5.1: rescale the carried previous when the window opened against a
144
+ // DIFFERENT snapshot (mirrors max_selloff.rs — integer division order!).
145
+ if (opened && oldSnapshot > 0n && vbSnapshot !== oldSnapshot) {
146
+ prev = (prev * vbSnapshot) / oldSnapshot;
147
+ }
148
+
149
+ const cap = (BigInt(params.maxSelloffPct) * vbSnapshot) / SCALE;
150
+ const weightedPrev = period > 0n ? (prev * (period - eiw)) / period : 0n;
151
+ const usedWithoutTrade = weightedPrev + cur;
152
+
153
+ return {
154
+ opened,
155
+ windowStart: ws,
156
+ elapsedInWindow: eiw,
157
+ previous: prev,
158
+ current: cur,
159
+ vbSnapshot,
160
+ cap,
161
+ weightedPrev,
162
+ usedWithoutTrade,
163
+ };
164
+ }
165
+
166
+ /** Read-only status of a token's max-selloff window at `now`. */
167
+ export function computeSelloffWindow(inputs: SelloffWindowInputs): SelloffWindowStatus {
168
+ const enabled = inputs.maxSelloffPct > 0;
169
+ if (!enabled) {
170
+ return {
171
+ enabled: false,
172
+ cap: new BN(0),
173
+ used: new BN(0),
174
+ remaining: new BN(0),
175
+ fillPct: 0,
176
+ windowStartTimestamp: inputs.windowStartTimestamp,
177
+ periodLength: inputs.periodLength,
178
+ rotated: false,
179
+ vbSnapshot: new BN(0),
180
+ };
181
+ }
182
+
183
+ const proj = projectSelloffWindow({
184
+ maxSelloffPct: inputs.maxSelloffPct,
185
+ periodLength: inputs.periodLength,
186
+ previousSelloff: BigInt(inputs.previousSelloff.toString()),
187
+ currentSelloff: BigInt(inputs.currentSelloff.toString()),
188
+ windowStartTimestamp: BigInt(inputs.windowStartTimestamp.toString()),
189
+ selloffVbSnapshot: BigInt(inputs.selloffVbSnapshot.toString()),
190
+ virtualBalance: BigInt(inputs.virtualBalance.toString()),
191
+ now: inputs.now,
192
+ });
193
+
194
+ const used = proj.usedWithoutTrade;
195
+ const remaining = proj.cap > used ? proj.cap - used : 0n;
196
+ const fillPct = proj.cap === 0n ? 0 : Number((used * SCALE) / proj.cap);
197
+
198
+ return {
199
+ enabled: true,
200
+ cap: new BN(proj.cap.toString()),
201
+ used: new BN(used.toString()),
202
+ remaining: new BN(remaining.toString()),
203
+ fillPct,
204
+ windowStartTimestamp: new BN(proj.windowStart.toString()),
205
+ periodLength: inputs.periodLength,
206
+ rotated: proj.opened,
207
+ vbSnapshot: new BN(proj.vbSnapshot.toString()),
208
+ };
209
+ }
210
+
211
+ // ── v5.1 piecewise-linear surge curve ───────────────────────────────────────
212
+
213
+ /**
214
+ * Kink position in normalized-t space. `kinkPct` is WHOLE percent of window
215
+ * fill (0..=100, u8 on-chain); 0 (or a kink at/outside the [threshold, 100%]
216
+ * band) disables the kink and the curve degenerates to low → high.
217
+ * Port of `surge_fee.rs::kink_t`.
218
+ */
219
+ function kinkT(kinkPct: number, thresholdPct: number): bigint {
220
+ const thr = BigInt(thresholdPct);
221
+ if (kinkPct === 0 || thr >= SCALE) return 0n;
222
+ const kinkFill = BigInt(kinkPct) * (SCALE / 100n);
223
+ if (kinkFill <= thr || kinkFill >= SCALE) return 0n;
224
+ return ((kinkFill - thr) * ONE) / (SCALE - thr);
225
+ }
226
+
227
+ /** Point rate at `t` (CEIL on the ramp, clamped to SCALE). Port of `rate_at`. */
228
+ function rateAt(
229
+ tFp: bigint,
230
+ slopeLowPct: number,
231
+ slopeMidPct: number,
232
+ slopeHighPct: number,
233
+ kFp: bigint,
234
+ ): bigint {
235
+ const t = tFp < ONE ? tFp : ONE;
236
+ const low = BigInt(slopeLowPct);
237
+ const mid = BigInt(slopeMidPct);
238
+ const high = BigInt(slopeHighPct);
239
+
240
+ let base: bigint;
241
+ let span: bigint;
242
+ let num: bigint;
243
+ let den: bigint;
244
+ if (kFp === 0n) {
245
+ base = low;
246
+ span = high > low ? high - low : 0n;
247
+ num = t;
248
+ den = ONE;
249
+ } else if (t <= kFp) {
250
+ base = low;
251
+ span = mid > low ? mid - low : 0n;
252
+ num = t;
253
+ den = kFp;
254
+ } else {
255
+ base = mid;
256
+ span = high > mid ? high - mid : 0n;
257
+ num = t - kFp;
258
+ den = ONE - kFp;
259
+ }
260
+
261
+ const prod = span * num;
262
+ const add = prod / den + (prod % den !== 0n ? 1n : 0n);
263
+ const rate = base + add;
264
+ return rate < SCALE ? rate : SCALE;
265
+ }
266
+
267
+ /**
268
+ * ∫ rate over [0, t] (1e18-scaled area). Port of `integral_to` — keep the
269
+ * `x*x/(2*den)` before the span multiply, exactly like the contract.
270
+ */
271
+ function integralTo(
272
+ tFp: bigint,
273
+ slopeLowPct: number,
274
+ slopeMidPct: number,
275
+ slopeHighPct: number,
276
+ kFp: bigint,
277
+ ): bigint {
278
+ const t = tFp < ONE ? tFp : ONE;
279
+ const low = BigInt(slopeLowPct);
280
+ const mid = BigInt(slopeMidPct);
281
+ const high = BigInt(slopeHighPct);
282
+
283
+ const ramp = (x: bigint, span: bigint, den: bigint): bigint => {
284
+ if (den === 0n || span === 0n || x === 0n) return 0n;
285
+ const halfSq = (x * x) / (2n * den);
286
+ return span * halfSq;
287
+ };
288
+
289
+ if (kFp === 0n) {
290
+ const span = high > low ? high - low : 0n;
291
+ return low * t + ramp(t, span, ONE);
292
+ }
293
+
294
+ if (t <= kFp) {
295
+ const span = mid > low ? mid - low : 0n;
296
+ return low * t + ramp(t, span, kFp);
297
+ }
298
+
299
+ const first = (kFp * (low + mid)) / 2n;
300
+ const rest = t - kFp;
301
+ const span = high > mid ? high - mid : 0n;
302
+ return first + mid * rest + ramp(rest, span, ONE - kFp);
303
+ }
304
+
305
+ /**
306
+ * Average surge-fee percentage (PERCENT_SCALE units, 0..=10_000) charged for
307
+ * moving the window fill from `effectiveSelloffBefore` to
308
+ * `effectiveSelloffAfter` against `cap`. Port of v5.1 `calc_surge_fee_pct`:
309
+ * the rate is INTEGRATED over the crossed span (CEIL), so the charge is
310
+ * path-independent. When the span is empty (`after <= before`) the point
311
+ * rate at `after` is returned.
312
+ */
313
+ export function calcSurgeFeePct(
314
+ effectiveSelloffBefore: bigint,
315
+ effectiveSelloffAfter: bigint,
316
+ cap: bigint,
317
+ thresholdPct: number,
318
+ slopeLowPct: number,
319
+ slopeMidPct: number,
320
+ slopeHighPct: number,
321
+ kinkPct: number,
322
+ ): number {
323
+ if (cap === 0n || slopeHighPct === 0) return 0;
324
+ const thr = BigInt(thresholdPct);
325
+ if (thr >= SCALE) return 0;
326
+
327
+ const kFp = kinkT(kinkPct, thresholdPct);
328
+
329
+ const fill = (x: bigint): bigint => {
330
+ const raw = (x * SCALE) / cap;
331
+ return raw < SCALE ? raw : SCALE;
332
+ };
333
+ const f0 = fill(effectiveSelloffBefore);
334
+ const f1 = fill(effectiveSelloffAfter);
335
+
336
+ if (f1 <= thr) return 0;
337
+
338
+ const denom = SCALE - thr;
339
+ const t1 = ((f1 - thr) * ONE) / denom;
340
+
341
+ if (f1 <= f0) {
342
+ return Number(rateAt(t1, slopeLowPct, slopeMidPct, slopeHighPct, kFp));
343
+ }
344
+
345
+ const f0Clamped = f0 > thr ? f0 : thr;
346
+ const t0 = ((f0Clamped - thr) * ONE) / denom;
347
+
348
+ const integral =
349
+ integralTo(t1, slopeLowPct, slopeMidPct, slopeHighPct, kFp) -
350
+ integralTo(t0, slopeLowPct, slopeMidPct, slopeHighPct, kFp);
351
+ const integralClamped = integral > 0n ? integral : 0n;
352
+
353
+ const numerator = denom * integralClamped;
354
+ const width = f1 - f0Clamped;
355
+ const scaledDen = width * ONE;
356
+ const avg = numerator / scaledDen + (numerator % scaledDen !== 0n ? 1n : 0n);
357
+
358
+ return Number(avg < SCALE ? avg : SCALE);
359
+ }
360
+
361
+ /**
362
+ * CEIL fee application of a known percentage on `amount`, clamped to
363
+ * `amount`. NOTE: the contract does NOT charge the whole output at one
364
+ * rate — use {@link calcSegmentedSurgeFeeAmount} to mirror an actual swap.
365
+ * This helper remains for coarse display math only.
366
+ */
367
+ export function calcSurgeFeeAmount(amountOut: bigint, surgePct: number): bigint {
368
+ if (surgePct <= 0 || amountOut <= 0n) return 0n;
369
+ const num = amountOut * BigInt(surgePct);
370
+ const fee = num / SCALE + (num % SCALE !== 0n ? 1n : 0n);
371
+ return fee < amountOut ? fee : amountOut;
372
+ }
373
+
374
+ export interface SegmentedSurgeFeeParams {
375
+ /** Window fill before the trade (`usedWithoutTrade`). */
376
+ effectiveSelloffBefore: bigint;
377
+ /** Window fill after the trade (`before + amountInNet`). */
378
+ effectiveSelloffAfter: bigint;
379
+ cap: bigint;
380
+ thresholdPct: number;
381
+ slopeLowPct: number;
382
+ slopeMidPct: number;
383
+ slopeHighPct: number;
384
+ kinkPct: number;
385
+ /** Post-swap-fee input driving the AMM curve (`amount_in_after_fee`). */
386
+ amountInAfterFee: bigint;
387
+ /** Full curve output of the trade (gross, pre-surge). */
388
+ amountOut: bigint;
389
+ /**
390
+ * Cumulative AMM output for an input slice `x ∈ [0, amountInAfterFee]`
391
+ * against the PRE-TRADE balances (i.e. `calc_out_given_in` with the same
392
+ * arguments that produced `amountOut`).
393
+ */
394
+ curveOut: (amountInSlice: bigint) => bigint;
395
+ /** Defaults to the contract's SURGE_FEE_SEGMENTS (= 4). */
396
+ segments?: number;
397
+ }
398
+
399
+ /**
400
+ * Surge fee in OUTPUT-token units for one swap — the exact v5.1 on-chain
401
+ * charge (swap.rs): only the output produced ABOVE the threshold is taxed,
402
+ * segment by segment across the taxed span, each segment's REAL curve
403
+ * output at that segment's average rate (CEIL per segment), total clamped
404
+ * to `amountOut`. Charging one average rate on the whole output would
405
+ * re-open the audit M-05 split dodge on asymmetric pools.
406
+ */
407
+ export function calcSegmentedSurgeFeeAmount(p: SegmentedSurgeFeeParams): bigint {
408
+ const {
409
+ effectiveSelloffBefore: before,
410
+ effectiveSelloffAfter: after,
411
+ cap,
412
+ thresholdPct,
413
+ slopeLowPct,
414
+ slopeMidPct,
415
+ slopeHighPct,
416
+ kinkPct,
417
+ amountInAfterFee,
418
+ amountOut,
419
+ } = p;
420
+
421
+ // Same precheck as swap.rs: whole-span average of 0 ⇒ nothing to charge.
422
+ const wholeSpanPct = calcSurgeFeePct(
423
+ before,
424
+ after,
425
+ cap,
426
+ thresholdPct,
427
+ slopeLowPct,
428
+ slopeMidPct,
429
+ slopeHighPct,
430
+ kinkPct,
431
+ );
432
+ if (wholeSpanPct === 0) return 0n;
433
+
434
+ const thrUnits = (cap * BigInt(thresholdPct)) / SCALE;
435
+ const span = after > before ? after - before : 0n;
436
+ const taxedLo = before > thrUnits ? before : thrUnits;
437
+ if (span === 0n || after <= taxedLo) return 0n;
438
+
439
+ const segments = BigInt(p.segments ?? SURGE_FEE_SEGMENTS);
440
+
441
+ // Flooring the input slice understates the output, which overstates the
442
+ // taxed remainder — the safe (conservative) direction, as on-chain.
443
+ const cumulativeOut = (u: bigint): bigint => {
444
+ if (u <= before) return 0n;
445
+ if (u >= after) return amountOut;
446
+ const x = (amountInAfterFee * (u - before)) / span;
447
+ return p.curveOut(x);
448
+ };
449
+
450
+ const taxedWidth = after - taxedLo;
451
+ let feeAcc = 0n;
452
+ let prevU = taxedLo;
453
+ let prevY = cumulativeOut(taxedLo);
454
+ for (let k = 1n; k <= segments; k++) {
455
+ const u = k === segments ? after : taxedLo + (taxedWidth * k) / segments;
456
+ const y = cumulativeOut(u);
457
+ const segOut = y > prevY ? y - prevY : 0n;
458
+ if (segOut > 0n && u > prevU) {
459
+ const segPct = BigInt(
460
+ calcSurgeFeePct(
461
+ prevU,
462
+ u,
463
+ cap,
464
+ thresholdPct,
465
+ slopeLowPct,
466
+ slopeMidPct,
467
+ slopeHighPct,
468
+ kinkPct,
469
+ ),
470
+ );
471
+ const num = segOut * segPct;
472
+ feeAcc += num / SCALE + (num % SCALE !== 0n ? 1n : 0n);
473
+ }
474
+ prevU = u;
475
+ prevY = y;
476
+ }
477
+
478
+ return feeAcc < amountOut ? feeAcc : amountOut;
479
+ }
480
+
481
+ // ── Contract-exact window state machine (max_selloff.rs mirror) ────────
482
+ // Companion API used by the quote engine (`quote-math.ts`): advances the
483
+ // rotating window like the deployed program (throws MaxSelloffExceeded)
484
+ // and rescales it after proportional liquidity changes. The projection
485
+ // API above serves display/UX; this one drives simulation.
486
+ export interface SelloffState {
487
+ previousSelloff: bigint;
488
+ currentSelloff: bigint;
489
+ windowStartTimestamp: bigint;
490
+ selloffVbSnapshot: bigint;
491
+ }
492
+ export interface SelloffResult {
493
+ effectiveSelloffBefore: bigint;
494
+ effectiveSelloff: bigint;
495
+ maxSelloffCap: bigint;
496
+ vbSnapshot: bigint;
497
+ previousSelloff: bigint;
498
+ currentSelloff: bigint;
499
+ windowStartTimestamp: bigint;
500
+ }
501
+ const I64_MIN = -(1n << 63n), I64_MAX = (1n << 63n) - 1n;
502
+ function i64(v: bigint): bigint { if (v < I64_MIN || v > I64_MAX)
503
+ throw new Error("timestamp: outside i64"); return v; }
504
+ function saturatingSubI64(a: bigint, b: bigint): bigint { const v = a - b; return v < I64_MIN ? I64_MIN : v > I64_MAX ? I64_MAX : v; }
505
+ /** Pure: does not modify its input, including on rejection. */
506
+ export function checkAndAdvanceSelloff(params: {
507
+ state: SelloffState;
508
+ maxSelloffPct: number;
509
+ period: number;
510
+ amountIn: bigint;
511
+ virtualBalance: bigint;
512
+ now: bigint;
513
+ }): SelloffResult | null {
514
+ const { state, maxSelloffPct, period, amountIn, virtualBalance, now } = params;
515
+ assertInteger(maxSelloffPct, 0, 10000, "max selloff percent");
516
+ if (maxSelloffPct === 0)
517
+ return null;
518
+ assertInteger(period, 1, 0xffffffff, "selloff period");
519
+ assertU64(amountIn);
520
+ assertU64(virtualBalance);
521
+ assertU64(state.previousSelloff);
522
+ assertU64(state.currentSelloff);
523
+ assertU64(state.selloffVbSnapshot);
524
+ i64(now);
525
+ i64(state.windowStartTimestamp);
526
+ const p = BigInt(period), rawElapsed = saturatingSubI64(now, state.windowStartTimestamp);
527
+ let elapsed = rawElapsed < 0n ? 0n : rawElapsed;
528
+ let previous = state.previousSelloff, current = state.currentSelloff, windowStart = state.windowStartTimestamp, opened = false;
529
+ if (elapsed >= 2n * p) {
530
+ previous = 0n;
531
+ current = 0n;
532
+ windowStart = now;
533
+ elapsed = 0n;
534
+ opened = true;
535
+ }
536
+ else if (elapsed >= p) {
537
+ previous = current;
538
+ current = 0n;
539
+ windowStart = i64(windowStart + p);
540
+ elapsed = saturatingSubI64(now, windowStart);
541
+ if (elapsed < 0n)
542
+ elapsed = 0n;
543
+ opened = true;
544
+ }
545
+ const snapshot = opened || state.selloffVbSnapshot === 0n ? virtualBalance : state.selloffVbSnapshot;
546
+ if (opened && state.selloffVbSnapshot > 0n && snapshot !== state.selloffVbSnapshot)
547
+ previous = assertU64(assertU128(previous * snapshot) / state.selloffVbSnapshot);
548
+ const cap = assertU64(BigInt(maxSelloffPct) * snapshot / 10000n);
549
+ const before = previous * (p - elapsed) / p + current;
550
+ const effective = before + amountIn;
551
+ if (effective > cap)
552
+ throw new Error("MaxSelloffExceeded");
553
+ return { effectiveSelloffBefore: before, effectiveSelloff: effective, maxSelloffCap: cap, vbSnapshot: snapshot, previousSelloff: previous, currentSelloff: assertU64(current + amountIn), windowStartTimestamp: windowStart };
554
+ }
555
+ /** Mirror of window rescaling after proportional add/remove liquidity. */
556
+ export function rescaleSelloffWindow(state: SelloffState, ratio: bigint, isIncrease: boolean, maxSelloffPct: number): SelloffState {
557
+ assertU128(ratio);
558
+ assertInteger(maxSelloffPct, 0, 10000, "max selloff percent");
559
+ if (ratio === 0n || maxSelloffPct === 0)
560
+ return { ...state };
561
+ const scale = (value: bigint): bigint => { assertU64(value); if (value === 0n)
562
+ return 0n; const delta = mulDown(value, ratio); return isIncrease ? assertU64(value + delta) : value > delta ? value - delta : 0n; };
563
+ return { ...state, previousSelloff: scale(state.previousSelloff), currentSelloff: scale(state.currentSelloff), selloffVbSnapshot: scale(state.selloffVbSnapshot) };
564
+ }