@morpho-org/midnight-sdk 1.1.1 → 1.2.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 (41) hide show
  1. package/lib/cjs/fetch/Position.d.ts +1 -1
  2. package/lib/cjs/fetch/Position.js +5 -1
  3. package/lib/cjs/index.d.ts +1 -0
  4. package/lib/cjs/index.js +1 -0
  5. package/lib/cjs/market/index.d.ts +0 -2
  6. package/lib/cjs/market/index.js +0 -2
  7. package/lib/cjs/offers/OfferChainUtils.d.ts +179 -0
  8. package/lib/cjs/offers/OfferChainUtils.js +446 -0
  9. package/lib/cjs/offers/index.d.ts +1 -0
  10. package/lib/cjs/offers/index.js +1 -0
  11. package/lib/cjs/{market → position}/Position.d.ts +83 -6
  12. package/lib/cjs/{market → position}/Position.js +83 -5
  13. package/lib/{esm/market → cjs/position}/PositionUtils.d.ts +26 -1
  14. package/lib/cjs/{market → position}/PositionUtils.js +27 -0
  15. package/lib/cjs/position/index.d.ts +2 -0
  16. package/lib/cjs/position/index.js +18 -0
  17. package/lib/cjs/signatures/RatifierUtils.js +2 -1
  18. package/lib/cjs/signatures/Tree.js +3 -1
  19. package/lib/cjs/signatures/TreeUtils.d.ts +2 -2
  20. package/lib/cjs/signatures/TreeUtils.js +17 -8
  21. package/lib/esm/fetch/Position.d.ts +1 -1
  22. package/lib/esm/fetch/Position.js +5 -1
  23. package/lib/esm/index.d.ts +1 -0
  24. package/lib/esm/index.js +1 -0
  25. package/lib/esm/market/index.d.ts +0 -2
  26. package/lib/esm/market/index.js +0 -2
  27. package/lib/esm/offers/OfferChainUtils.d.ts +179 -0
  28. package/lib/esm/offers/OfferChainUtils.js +443 -0
  29. package/lib/esm/offers/index.d.ts +1 -0
  30. package/lib/esm/offers/index.js +1 -0
  31. package/lib/esm/{market → position}/Position.d.ts +83 -6
  32. package/lib/esm/{market → position}/Position.js +83 -5
  33. package/lib/{cjs/market → esm/position}/PositionUtils.d.ts +26 -1
  34. package/lib/esm/{market → position}/PositionUtils.js +27 -0
  35. package/lib/esm/position/index.d.ts +2 -0
  36. package/lib/esm/position/index.js +2 -0
  37. package/lib/esm/signatures/RatifierUtils.js +2 -1
  38. package/lib/esm/signatures/Tree.js +3 -1
  39. package/lib/esm/signatures/TreeUtils.d.ts +2 -2
  40. package/lib/esm/signatures/TreeUtils.js +17 -8
  41. package/package.json +2 -2
@@ -0,0 +1,446 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OfferChainUtils = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const viem_1 = require("viem");
6
+ const constants_js_1 = require("../constants.js");
7
+ const errors_js_1 = require("../errors.js");
8
+ const index_js_1 = require("../math/index.js");
9
+ const FAVORABLE_RATE_DRIFT = 0.1;
10
+ const MAX_EXPIRY_TTM_NUMERATOR = 75n;
11
+ const MAX_EXPIRY_TTM_DENOMINATOR = 100n;
12
+ const MAX_CHAIN_LEGS = Number(constants_js_1.MAX_TICK) + 1;
13
+ const SECONDS_PER_YEAR = Number(morpho_ts_1.Time.s.from.y(1n));
14
+ /**
15
+ * Utilities for building time-bounded Midnight offer chains.
16
+ *
17
+ * A Midnight offer has one fixed price, so its displayed yearly rate changes
18
+ * as maturity approaches. The markets app uses these helpers when a maker wants
19
+ * to post, for example, a 5% order for several months: the app builds several
20
+ * adjacent offers sharing the same reserve, each with a different tick and time
21
+ * window, so the order reviews and renders as a stable 5% order across the
22
+ * selected window instead of drifting upward as time passes.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
27
+ *
28
+ * const legs = OfferChainUtils.buildLendFixedRateOfferChain({
29
+ * targetRate: 0.05,
30
+ * tickSpacing: 4n,
31
+ * maturityTimestamp: 1_798_761_600n,
32
+ * chainStartTimestamp: 1_767_225_600n,
33
+ * chainEndTimestamp: 1_791_153_600n,
34
+ * });
35
+ * console.log(legs[0]?.tick);
36
+ * ```
37
+ */
38
+ var OfferChainUtils;
39
+ (function (OfferChainUtils) {
40
+ /**
41
+ * Maximum fraction of the initial time-to-maturity covered by a fixed-rate offer chain.
42
+ *
43
+ * Use this cap before displaying an expiry picker for a fixed-rate maker
44
+ * order. The last part of the maturity window is intentionally excluded
45
+ * because tiny time changes cause large displayed-rate drift.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
50
+ *
51
+ * console.log(OfferChainUtils.MAX_EXPIRY_TTM_FRACTION);
52
+ * ```
53
+ */
54
+ OfferChainUtils.MAX_EXPIRY_TTM_FRACTION = 0.75;
55
+ /**
56
+ * Builds borrow-side sell-offer legs that approximate one fixed maker rate over time.
57
+ *
58
+ * Use before a make-borrow or supply-collateral-and-make-borrow flow when a
59
+ * borrower wants one displayed fixed borrow rate across a longer window. Map
60
+ * the returned legs to `Offer.create({ buy: false, ... })`, then group and
61
+ * submit them through the maker flow.
62
+ *
63
+ * Borrow chains read their target rate at each leg's expiry edge. If a leg
64
+ * would need to extend past `chainEndTimestamp`, it is dropped rather than
65
+ * clamped so the expiry edge remains the recoverable target-rate edge.
66
+ *
67
+ * @param params - Fixed-rate offer-chain parameters without a side field.
68
+ * @param params.targetRate - Target yearly fixed rate expressed as a decimal number.
69
+ * @param params.tickSpacing - Tick spacing enforced by the market.
70
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
71
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
72
+ * @param params.chainEndTimestamp - Latest timestamp the chain may cover.
73
+ * @returns Borrow-side offer legs that can be mapped to `Offer.create({ buy: false, ... })`.
74
+ * @throws {InvalidOfferParameterError} when an input is invalid or the end timestamp exceeds the supported horizon.
75
+ * @example
76
+ * ```ts
77
+ * import { Offer, OfferChainUtils } from "@morpho-org/midnight-sdk";
78
+ *
79
+ * const legs = OfferChainUtils.buildBorrowFixedRateOfferChain({
80
+ * targetRate: 0.08,
81
+ * tickSpacing: market.tickSpacing,
82
+ * maturityTimestamp: market.params.maturity,
83
+ * chainStartTimestamp: now,
84
+ * chainEndTimestamp: expiry,
85
+ * });
86
+ * const offers = legs.map((leg) =>
87
+ * Offer.create({
88
+ * ...baseOffer,
89
+ * buy: false,
90
+ * tick: leg.tick,
91
+ * start: leg.startTimestamp,
92
+ * expiry: leg.expiryTimestamp,
93
+ * }),
94
+ * );
95
+ * ```
96
+ */
97
+ function buildBorrowFixedRateOfferChain(params) {
98
+ if (!Number.isFinite(params.targetRate)) {
99
+ throw new errors_js_1.InvalidOfferParameterError({
100
+ parameter: "targetRate",
101
+ value: params.targetRate,
102
+ instruction: "Use a finite positive yearly rate.",
103
+ });
104
+ }
105
+ if (params.targetRate <= 0) {
106
+ throw new errors_js_1.InvalidOfferParameterError({
107
+ parameter: "targetRate",
108
+ value: params.targetRate,
109
+ instruction: "Use a positive yearly rate.",
110
+ });
111
+ }
112
+ const tickSpacing = normalizeSafeInteger("tickSpacing", params.tickSpacing);
113
+ if (tickSpacing <= 0n || constants_js_1.DEFAULT_TICK_SPACING % tickSpacing !== 0n) {
114
+ throw new errors_js_1.InvalidOfferParameterError({
115
+ parameter: "tickSpacing",
116
+ value: tickSpacing,
117
+ instruction: `Use a positive tick spacing that divides "${constants_js_1.DEFAULT_TICK_SPACING}".`,
118
+ });
119
+ }
120
+ const maturityTimestamp = normalizeTimestamp("maturityTimestamp", params.maturityTimestamp);
121
+ const chainStartTimestamp = normalizeTimestamp("chainStartTimestamp", params.chainStartTimestamp);
122
+ const chainEndTimestamp = normalizeTimestamp("chainEndTimestamp", params.chainEndTimestamp);
123
+ if (maturityTimestamp <= chainStartTimestamp) {
124
+ throw new errors_js_1.InvalidOfferParameterError({
125
+ parameter: "maturityTimestamp",
126
+ value: maturityTimestamp,
127
+ instruction: "Use a timestamp greater than chainStartTimestamp.",
128
+ });
129
+ }
130
+ if (chainEndTimestamp <= chainStartTimestamp) {
131
+ throw new errors_js_1.InvalidOfferParameterError({
132
+ parameter: "chainEndTimestamp",
133
+ value: chainEndTimestamp,
134
+ instruction: "Use a timestamp greater than chainStartTimestamp.",
135
+ });
136
+ }
137
+ const maxChainEndTimestamp = getMaxFixedRateOfferChainEndTimestamp({
138
+ maturityTimestamp,
139
+ chainStartTimestamp,
140
+ });
141
+ if (chainEndTimestamp > maxChainEndTimestamp) {
142
+ throw new errors_js_1.InvalidOfferParameterError({
143
+ parameter: "chainEndTimestamp",
144
+ value: chainEndTimestamp,
145
+ instruction: `Use a timestamp no greater than "${maxChainEndTimestamp}".`,
146
+ });
147
+ }
148
+ const tauInitial = Number(maturityTimestamp - chainStartTimestamp) / SECONDS_PER_YEAR;
149
+ const tauStop = Number(maturityTimestamp - chainEndTimestamp) / SECONDS_PER_YEAR;
150
+ const lowerRate = params.targetRate * (1 - FAVORABLE_RATE_DRIFT);
151
+ /* v8 ignore next: positive finite targetRate validation keeps lowerRate positive for practical JS numbers. */
152
+ if (lowerRate <= 0)
153
+ return [];
154
+ const legs = [];
155
+ let tauTop = tauInitial;
156
+ let iteration = 0;
157
+ for (; iteration < MAX_CHAIN_LEGS; iteration++) {
158
+ const price = 1 / (1 + lowerRate * tauTop);
159
+ let priceInput;
160
+ if (!Number.isFinite(price) || price <= 0) {
161
+ priceInput = 0n;
162
+ }
163
+ else if (price >= 1) {
164
+ priceInput = morpho_ts_1.MathLib.WAD;
165
+ }
166
+ else {
167
+ priceInput = (0, viem_1.parseUnits)(price.toFixed(18), 18);
168
+ }
169
+ const rawTick = index_js_1.TickLib.priceToTick(priceInput, 1n) - 1n;
170
+ if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK)
171
+ break;
172
+ const tick = floorTickToSpacing(rawTick, tickSpacing);
173
+ if (legs.at(-1)?.tick === tick)
174
+ break;
175
+ const tauMax = rateTau(tick, lowerRate);
176
+ const tauMin = rateTau(tick, params.targetRate);
177
+ if (tauMin >= tauTop)
178
+ break;
179
+ if (tauMin < tauStop)
180
+ break;
181
+ const startTimestamp = maturityTimestamp -
182
+ BigInt(Math.round(Math.min(tauMax, tauTop) * SECONDS_PER_YEAR));
183
+ const expiryTimestamp = maturityTimestamp - BigInt(Math.round(tauMin * SECONDS_PER_YEAR));
184
+ /* v8 ignore next: tests cover positive legs; zero-width legs are skipped only on rounding ties. */
185
+ if (expiryTimestamp > startTimestamp) {
186
+ legs.push({ tick, startTimestamp, expiryTimestamp });
187
+ }
188
+ tauTop = tauMin;
189
+ }
190
+ /* v8 ignore next: the monotonic tick walk exits before exhausting the finite tick range. */
191
+ if (iteration >= MAX_CHAIN_LEGS) {
192
+ throw new errors_js_1.InvalidOfferParameterError({
193
+ parameter: "tickSpacing",
194
+ value: tickSpacing,
195
+ instruction: `Borrow chain exceeded "${MAX_CHAIN_LEGS}" legs.`,
196
+ });
197
+ }
198
+ return legs;
199
+ }
200
+ OfferChainUtils.buildBorrowFixedRateOfferChain = buildBorrowFixedRateOfferChain;
201
+ /**
202
+ * Builds lend-side buy-offer legs that approximate one fixed maker rate over time.
203
+ *
204
+ * Use before a make-lend flow when a lender wants one displayed fixed lend
205
+ * rate across a longer window. Map the returned legs to
206
+ * `Offer.create({ buy: true, ... })`, then group and submit them through the
207
+ * maker flow.
208
+ *
209
+ * Lend chains read their target rate at each leg's start edge. The first leg
210
+ * may start before `chainStartTimestamp`; clamping that edge would move the
211
+ * recoverable display rate below the maker's target.
212
+ *
213
+ * @param params - Fixed-rate offer-chain parameters without a side field.
214
+ * @param params.targetRate - Target yearly fixed rate expressed as a decimal number.
215
+ * @param params.tickSpacing - Tick spacing enforced by the market.
216
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
217
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
218
+ * @param params.chainEndTimestamp - Latest timestamp the chain may cover.
219
+ * @returns Lend-side offer legs that can be mapped to `Offer.create({ buy: true, ... })`.
220
+ * @throws {InvalidOfferParameterError} when an input is invalid or the end timestamp exceeds the supported horizon.
221
+ * @example
222
+ * ```ts
223
+ * import { Offer, OfferChainUtils } from "@morpho-org/midnight-sdk";
224
+ *
225
+ * const legs = OfferChainUtils.buildLendFixedRateOfferChain({
226
+ * targetRate: 0.05,
227
+ * tickSpacing: market.tickSpacing,
228
+ * maturityTimestamp: market.params.maturity,
229
+ * chainStartTimestamp: now,
230
+ * chainEndTimestamp: expiry,
231
+ * });
232
+ * const offers = legs.map((leg) =>
233
+ * Offer.create({
234
+ * ...baseOffer,
235
+ * buy: true,
236
+ * tick: leg.tick,
237
+ * start: leg.startTimestamp,
238
+ * expiry: leg.expiryTimestamp,
239
+ * }),
240
+ * );
241
+ * ```
242
+ */
243
+ function buildLendFixedRateOfferChain(params) {
244
+ if (!Number.isFinite(params.targetRate)) {
245
+ throw new errors_js_1.InvalidOfferParameterError({
246
+ parameter: "targetRate",
247
+ value: params.targetRate,
248
+ instruction: "Use a finite positive yearly rate.",
249
+ });
250
+ }
251
+ if (params.targetRate <= 0) {
252
+ throw new errors_js_1.InvalidOfferParameterError({
253
+ parameter: "targetRate",
254
+ value: params.targetRate,
255
+ instruction: "Use a positive yearly rate.",
256
+ });
257
+ }
258
+ const tickSpacing = normalizeSafeInteger("tickSpacing", params.tickSpacing);
259
+ if (tickSpacing <= 0n || constants_js_1.DEFAULT_TICK_SPACING % tickSpacing !== 0n) {
260
+ throw new errors_js_1.InvalidOfferParameterError({
261
+ parameter: "tickSpacing",
262
+ value: tickSpacing,
263
+ instruction: `Use a positive tick spacing that divides "${constants_js_1.DEFAULT_TICK_SPACING}".`,
264
+ });
265
+ }
266
+ const maturityTimestamp = normalizeTimestamp("maturityTimestamp", params.maturityTimestamp);
267
+ const chainStartTimestamp = normalizeTimestamp("chainStartTimestamp", params.chainStartTimestamp);
268
+ const chainEndTimestamp = normalizeTimestamp("chainEndTimestamp", params.chainEndTimestamp);
269
+ if (maturityTimestamp <= chainStartTimestamp) {
270
+ throw new errors_js_1.InvalidOfferParameterError({
271
+ parameter: "maturityTimestamp",
272
+ value: maturityTimestamp,
273
+ instruction: "Use a timestamp greater than chainStartTimestamp.",
274
+ });
275
+ }
276
+ if (chainEndTimestamp <= chainStartTimestamp) {
277
+ throw new errors_js_1.InvalidOfferParameterError({
278
+ parameter: "chainEndTimestamp",
279
+ value: chainEndTimestamp,
280
+ instruction: "Use a timestamp greater than chainStartTimestamp.",
281
+ });
282
+ }
283
+ const maxChainEndTimestamp = getMaxFixedRateOfferChainEndTimestamp({
284
+ maturityTimestamp,
285
+ chainStartTimestamp,
286
+ });
287
+ if (chainEndTimestamp > maxChainEndTimestamp) {
288
+ throw new errors_js_1.InvalidOfferParameterError({
289
+ parameter: "chainEndTimestamp",
290
+ value: chainEndTimestamp,
291
+ instruction: `Use a timestamp no greater than "${maxChainEndTimestamp}".`,
292
+ });
293
+ }
294
+ const tauInitial = Number(maturityTimestamp - chainStartTimestamp) / SECONDS_PER_YEAR;
295
+ const tauStop = Number(maturityTimestamp - chainEndTimestamp) / SECONDS_PER_YEAR;
296
+ const upperRate = params.targetRate * (1 + FAVORABLE_RATE_DRIFT);
297
+ const maxAlignedTick = floorTickToSpacing(constants_js_1.MAX_TICK, tickSpacing);
298
+ const highestDiscountTick = floorTickToSpacing(index_js_1.TickLib.priceToTick(morpho_ts_1.MathLib.WAD, 1n) - 1n, tickSpacing);
299
+ const ceilingTick = highestDiscountTick < maxAlignedTick
300
+ ? highestDiscountTick
301
+ : maxAlignedTick;
302
+ const tauCeiling = rateTau(ceilingTick, upperRate);
303
+ let tauBottom = Math.max(tauStop, tauCeiling);
304
+ if (tauBottom >= tauInitial)
305
+ return [];
306
+ const tauLegs = [];
307
+ let iteration = 0;
308
+ for (; iteration < MAX_CHAIN_LEGS; iteration++) {
309
+ const price = 1 / (1 + upperRate * tauBottom);
310
+ let priceInput;
311
+ if (!Number.isFinite(price) || price <= 0) {
312
+ priceInput = 0n;
313
+ }
314
+ else {
315
+ /* v8 ignore next: positive rates that survive the grid-floor check keep lend-chain prices below one. */
316
+ if (price >= 1) {
317
+ priceInput = morpho_ts_1.MathLib.WAD;
318
+ }
319
+ else {
320
+ priceInput = (0, viem_1.parseUnits)(price.toFixed(18), 18);
321
+ }
322
+ }
323
+ const rawTick = index_js_1.TickLib.priceToTick(priceInput, 1n);
324
+ /* v8 ignore next: priceToTick returns in-range ticks; maxAlignedTick only tightens non-dividing spacing. */
325
+ if (rawTick < 0n || rawTick > constants_js_1.MAX_TICK || rawTick > maxAlignedTick)
326
+ break;
327
+ const alignedTick = ((rawTick + tickSpacing - 1n) / tickSpacing) * tickSpacing;
328
+ /* v8 ignore next: non-dividing spacing boundary clamp is defensive; normal alignment is covered. */
329
+ const tick = alignedTick < maxAlignedTick ? alignedTick : maxAlignedTick;
330
+ if (tauLegs.at(-1)?.tick === tick)
331
+ break;
332
+ const tauMax = rateTau(tick, params.targetRate);
333
+ const tauMin = rateTau(tick, upperRate);
334
+ if (tauMax <= tauBottom)
335
+ break;
336
+ tauLegs.push({ tick, tauMax, tauMin: Math.max(tauMin, tauBottom) });
337
+ if (tauMax >= tauInitial)
338
+ break;
339
+ tauBottom = tauMax;
340
+ }
341
+ /* v8 ignore next: the monotonic tick walk exits before exhausting the finite tick range. */
342
+ if (iteration >= MAX_CHAIN_LEGS) {
343
+ throw new errors_js_1.InvalidOfferParameterError({
344
+ parameter: "tickSpacing",
345
+ value: tickSpacing,
346
+ instruction: `Lend chain exceeded "${MAX_CHAIN_LEGS}" legs.`,
347
+ });
348
+ }
349
+ const leftmostLeg = tauLegs.at(-1);
350
+ if (leftmostLeg && leftmostLeg.tauMax < tauInitial)
351
+ return [];
352
+ return tauLegs
353
+ .reverse()
354
+ .map((leg) => ({
355
+ tick: leg.tick,
356
+ startTimestamp: maturityTimestamp - BigInt(Math.round(leg.tauMax * SECONDS_PER_YEAR)),
357
+ expiryTimestamp: maturityTimestamp - BigInt(Math.round(leg.tauMin * SECONDS_PER_YEAR)),
358
+ }))
359
+ .filter((leg) => leg.expiryTimestamp > leg.startTimestamp);
360
+ }
361
+ OfferChainUtils.buildLendFixedRateOfferChain = buildLendFixedRateOfferChain;
362
+ /**
363
+ * Returns the latest supported end timestamp for a fixed-rate offer chain.
364
+ *
365
+ * Chains intentionally stop before the final part of the maturity window
366
+ * because rate sensitivity accelerates near maturity and would require too
367
+ * many short-lived offers for a stable maker quote.
368
+ * Call this when constraining a make-offer expiry selector, then pass the
369
+ * selected timestamp to the lend-only or borrow-only chain builder.
370
+ *
371
+ * @param params - Maturity and chain-start timestamps.
372
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
373
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
374
+ * @returns Latest accepted chain end timestamp.
375
+ * @throws {InvalidOfferParameterError} when a timestamp is invalid.
376
+ * @example
377
+ * ```ts
378
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
379
+ *
380
+ * const maxExpiry = OfferChainUtils.getMaxFixedRateOfferChainEndTimestamp({
381
+ * maturityTimestamp: market.params.maturity,
382
+ * chainStartTimestamp: now,
383
+ * });
384
+ * console.log(maxExpiry);
385
+ * ```
386
+ */
387
+ function getMaxFixedRateOfferChainEndTimestamp(params) {
388
+ const maturityTimestamp = normalizeTimestamp("maturityTimestamp", params.maturityTimestamp);
389
+ const chainStartTimestamp = normalizeTimestamp("chainStartTimestamp", params.chainStartTimestamp);
390
+ if (maturityTimestamp <= chainStartTimestamp) {
391
+ throw new errors_js_1.InvalidOfferParameterError({
392
+ parameter: "maturityTimestamp",
393
+ value: maturityTimestamp,
394
+ instruction: "Use a maturity timestamp greater than chainStartTimestamp.",
395
+ });
396
+ }
397
+ return (chainStartTimestamp +
398
+ ((maturityTimestamp - chainStartTimestamp) * MAX_EXPIRY_TTM_NUMERATOR) /
399
+ MAX_EXPIRY_TTM_DENOMINATOR);
400
+ }
401
+ OfferChainUtils.getMaxFixedRateOfferChainEndTimestamp = getMaxFixedRateOfferChainEndTimestamp;
402
+ })(OfferChainUtils || (exports.OfferChainUtils = OfferChainUtils = {}));
403
+ function normalizeSafeInteger(parameter, value) {
404
+ let normalized;
405
+ try {
406
+ normalized = BigInt(value);
407
+ }
408
+ catch (cause) {
409
+ throw new errors_js_1.InvalidOfferParameterError({
410
+ parameter,
411
+ value,
412
+ instruction: "Use a safe integer value.",
413
+ cause,
414
+ });
415
+ }
416
+ const numberValue = Number(normalized);
417
+ if (!Number.isSafeInteger(numberValue)) {
418
+ throw new errors_js_1.InvalidOfferParameterError({
419
+ parameter,
420
+ value,
421
+ instruction: "Use a JavaScript-safe integer value.",
422
+ });
423
+ }
424
+ return normalized;
425
+ }
426
+ function normalizeTimestamp(parameter, value) {
427
+ const normalized = normalizeSafeInteger(parameter, value);
428
+ if (normalized < 0n) {
429
+ throw new errors_js_1.InvalidOfferParameterError({
430
+ parameter,
431
+ value,
432
+ instruction: "Use a non-negative timestamp.",
433
+ });
434
+ }
435
+ return normalized;
436
+ }
437
+ function rateTau(tick, rate) {
438
+ const price = Number((0, viem_1.formatUnits)(index_js_1.TickLib.tickToPrice(tick), 18));
439
+ /* v8 ignore next: builders pass positive rates and discount ticks; this guards direct internal misuse. */
440
+ if (price <= 0 || price >= 1 || rate <= 0)
441
+ return 0;
442
+ return (1 / price - 1) / rate;
443
+ }
444
+ function floorTickToSpacing(tick, spacing) {
445
+ return tick - (tick % spacing);
446
+ }
@@ -1,2 +1,3 @@
1
1
  export * from "./Offer.js";
2
+ export * from "./OfferChainUtils.js";
2
3
  export * from "./OfferUtils.js";
@@ -15,4 +15,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./Offer.js"), exports);
18
+ __exportStar(require("./OfferChainUtils.js"), exports);
18
19
  __exportStar(require("./OfferUtils.js"), exports);
@@ -1,6 +1,6 @@
1
1
  import { type BigIntish } from "@morpho-org/morpho-ts";
2
- import type { Address } from "viem";
3
- import { type IMarket, Market } from "./Market.js";
2
+ import type { Address, Hash } from "viem";
3
+ import { type IMarket, Market } from "../market/Market.js";
4
4
  /**
5
5
  * Plain input accepted by {@link Position}.
6
6
  *
@@ -9,6 +9,8 @@ import { type IMarket, Market } from "./Market.js";
9
9
  * import type { IPosition } from "@morpho-org/midnight-sdk";
10
10
  *
11
11
  * const position: IPosition = {
12
+ * user: "0x0000000000000000000000000000000000009000",
13
+ * marketId: "0x0000000000000000000000000000000000000000000000000000000000000001",
12
14
  * credit: 0n,
13
15
  * pendingFee: 0n,
14
16
  * lastLossFactor: 0n,
@@ -20,6 +22,10 @@ import { type IMarket, Market } from "./Market.js";
20
22
  * ```
21
23
  */
22
24
  export interface IPosition {
25
+ /** User holding this position. */
26
+ readonly user: Address;
27
+ /** Id of the market on which this position is held. */
28
+ readonly marketId: Hash;
23
29
  /** User credit. */
24
30
  readonly credit: BigIntish;
25
31
  /** Pending continuous fee. */
@@ -43,6 +49,8 @@ export interface IPosition {
43
49
  * import { Position } from "@morpho-org/midnight-sdk";
44
50
  *
45
51
  * const position = new Position({
52
+ * user: "0x0000000000000000000000000000000000009000",
53
+ * marketId: "0x0000000000000000000000000000000000000000000000000000000000000001",
46
54
  * credit: 0n,
47
55
  * pendingFee: 0n,
48
56
  * lastLossFactor: 0n,
@@ -54,7 +62,11 @@ export interface IPosition {
54
62
  * console.log(position.debt);
55
63
  * ```
56
64
  */
57
- export declare class Position {
65
+ export declare class Position implements IPosition {
66
+ /** User holding this position. */
67
+ readonly user: Address;
68
+ /** Id of the market on which this position is held. */
69
+ readonly marketId: Hash;
58
70
  /** User credit. */
59
71
  readonly credit: bigint;
60
72
  /** Pending continuous fee. */
@@ -79,6 +91,8 @@ export declare class Position {
79
91
  * import { Position } from "@morpho-org/midnight-sdk";
80
92
  *
81
93
  * const position = new Position({
94
+ * user: "0x0000000000000000000000000000000000009000",
95
+ * marketId: "0x0000000000000000000000000000000000000000000000000000000000000001",
82
96
  * credit: 1_000n,
83
97
  * pendingFee: 100n,
84
98
  * lastLossFactor: 0n,
@@ -92,6 +106,9 @@ export declare class Position {
92
106
  */
93
107
  get faceValue(): bigint;
94
108
  }
109
+ /** Plain input shape for a Midnight position paired with hydrated market state. */
110
+ export interface IAccrualPosition extends Omit<IPosition, "marketId"> {
111
+ }
95
112
  /**
96
113
  * Midnight position paired with its hydrated market.
97
114
  *
@@ -116,6 +133,7 @@ export declare class Position {
116
133
  *
117
134
  * const position = new AccrualPosition(
118
135
  * {
136
+ * user: "0x0000000000000000000000000000000000009000",
119
137
  * credit: 1_000n,
120
138
  * pendingFee: 100n,
121
139
  * lastLossFactor: 0n,
@@ -154,10 +172,65 @@ export declare class Position {
154
172
  * console.log(position.market.id);
155
173
  * ```
156
174
  */
157
- export declare class AccrualPosition extends Position {
175
+ export declare class AccrualPosition extends Position implements IAccrualPosition {
176
+ protected readonly _market: Market;
177
+ constructor(position: IAccrualPosition, market: IMarket | Market);
158
178
  /** Hydrated market for this position. */
159
- readonly market: Market;
160
- constructor(position: IPosition, market: IMarket | Market);
179
+ get market(): Market;
180
+ /**
181
+ * Returns the maximum credit units currently withdrawable from this position.
182
+ *
183
+ * The protocol capacity is limited by both the accrued position credit and
184
+ * the market's currently withdrawable liquidity. Default redemption flows may
185
+ * still choose the position face value.
186
+ *
187
+ * @returns Maximum credit units currently withdrawable.
188
+ * @example
189
+ * ```ts
190
+ * import { AccrualPosition } from "@morpho-org/midnight-sdk";
191
+ *
192
+ * const position = new AccrualPosition(
193
+ * {
194
+ * user: "0x0000000000000000000000000000000000009000",
195
+ * credit: 1_000n,
196
+ * pendingFee: 100n,
197
+ * lastLossFactor: 0n,
198
+ * lastAccrual: 1_000n,
199
+ * debt: 0n,
200
+ * collateralBitmap: 1n,
201
+ * collateral: [50n],
202
+ * },
203
+ * {
204
+ * params: {
205
+ * chainId: 8453,
206
+ * midnight: "0x0000000000000000000000000000000000001000",
207
+ * loanToken: "0x0000000000000000000000000000000000006000",
208
+ * collateralParams: [
209
+ * {
210
+ * token: "0x0000000000000000000000000000000000007000",
211
+ * lltv: 770000000000000000n,
212
+ * liquidationCursor: 250000000000000000n,
213
+ * oracle: "0x0000000000000000000000000000000000008000",
214
+ * },
215
+ * ],
216
+ * maturity: 54_000n,
217
+ * rcfThreshold: 0n,
218
+ * enterGate: "0x0000000000000000000000000000000000000000",
219
+ * liquidatorGate: "0x0000000000000000000000000000000000000000",
220
+ * },
221
+ * totalUnits: 1_000n,
222
+ * lossFactor: 0n,
223
+ * withdrawable: 950n,
224
+ * continuousFeeCredit: 0n,
225
+ * settlementFeeCbps: [1, 2, 3, 4, 5, 6, 7],
226
+ * continuousFee: 10,
227
+ * tickSpacing: 4,
228
+ * },
229
+ * );
230
+ * console.log(position.withdrawable); // 950n
231
+ * ```
232
+ */
233
+ get withdrawable(): bigint;
161
234
  /**
162
235
  * Returns the position collateral balance at an index configured by the market.
163
236
  *
@@ -184,6 +257,7 @@ export declare class AccrualPosition extends Position {
184
257
  *
185
258
  * const position = new AccrualPosition(
186
259
  * {
260
+ * user: "0x0000000000000000000000000000000000009000",
187
261
  * credit: 1_000n,
188
262
  * pendingFee: 100n,
189
263
  * lastLossFactor: 0n,
@@ -251,6 +325,7 @@ export declare class AccrualPosition extends Position {
251
325
  * const collateralToken = "0x0000000000000000000000000000000000007000";
252
326
  * const position = new AccrualPosition(
253
327
  * {
328
+ * user: "0x0000000000000000000000000000000000009000",
254
329
  * credit: 1_000n,
255
330
  * pendingFee: 100n,
256
331
  * lastLossFactor: 0n,
@@ -317,6 +392,7 @@ export declare class AccrualPosition extends Position {
317
392
  *
318
393
  * const position = new AccrualPosition(
319
394
  * {
395
+ * user: "0x0000000000000000000000000000000000009000",
320
396
  * credit: 1_000n,
321
397
  * pendingFee: 100n,
322
398
  * lastLossFactor: 0n,
@@ -386,6 +462,7 @@ export declare class AccrualPosition extends Position {
386
462
  *
387
463
  * const position = new AccrualPosition(
388
464
  * {
465
+ * user: "0x0000000000000000000000000000000000009000",
389
466
  * credit: 1_000n,
390
467
  * pendingFee: 100n,
391
468
  * lastLossFactor: 0n,