@morpho-org/midnight-sdk 1.0.0 → 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 (86) hide show
  1. package/lib/cjs/api/MidnightApi.js +67 -3
  2. package/lib/cjs/api/helpers.d.ts +11 -1
  3. package/lib/cjs/api/helpers.js +48 -1
  4. package/lib/cjs/errors.d.ts +15 -0
  5. package/lib/cjs/errors.js +21 -1
  6. package/lib/cjs/fetch/Market.js +37 -2
  7. package/lib/cjs/fetch/Position.d.ts +1 -1
  8. package/lib/cjs/fetch/Position.js +5 -1
  9. package/lib/cjs/fetch/utils.d.ts +1 -1
  10. package/lib/cjs/fetch/utils.js +9 -2
  11. package/lib/cjs/index.d.ts +1 -0
  12. package/lib/cjs/index.js +1 -0
  13. package/lib/cjs/market/index.d.ts +0 -2
  14. package/lib/cjs/market/index.js +0 -2
  15. package/lib/cjs/offers/Offer.d.ts +1 -1
  16. package/lib/cjs/offers/OfferChainUtils.d.ts +179 -0
  17. package/lib/cjs/offers/OfferChainUtils.js +446 -0
  18. package/lib/cjs/offers/OfferUtils.d.ts +5 -5
  19. package/lib/cjs/offers/OfferUtils.js +26 -13
  20. package/lib/cjs/offers/index.d.ts +1 -0
  21. package/lib/cjs/offers/index.js +1 -0
  22. package/lib/cjs/{market → position}/Position.d.ts +83 -6
  23. package/lib/cjs/{market → position}/Position.js +83 -5
  24. package/lib/{esm/market → cjs/position}/PositionUtils.d.ts +26 -1
  25. package/lib/cjs/{market → position}/PositionUtils.js +27 -0
  26. package/lib/cjs/position/index.d.ts +2 -0
  27. package/lib/cjs/position/index.js +18 -0
  28. package/lib/cjs/signatures/EcrecoverRatifierUtils.d.ts +118 -0
  29. package/lib/cjs/signatures/EcrecoverRatifierUtils.js +149 -1
  30. package/lib/cjs/signatures/Group.js +5 -3
  31. package/lib/cjs/signatures/GroupUtils.d.ts +48 -0
  32. package/lib/cjs/signatures/GroupUtils.js +51 -0
  33. package/lib/cjs/signatures/RatifierUtils.js +15 -3
  34. package/lib/cjs/signatures/SetterRatifierUtils.d.ts +31 -0
  35. package/lib/cjs/signatures/SetterRatifierUtils.js +38 -0
  36. package/lib/cjs/signatures/Tree.js +13 -3
  37. package/lib/cjs/signatures/TreeUtils.d.ts +6 -3
  38. package/lib/cjs/signatures/TreeUtils.js +35 -13
  39. package/lib/cjs/signatures/eip712.d.ts +22 -0
  40. package/lib/cjs/signatures/eip712.js +26 -0
  41. package/lib/cjs/signatures/index.d.ts +1 -0
  42. package/lib/cjs/signatures/index.js +1 -0
  43. package/lib/esm/api/MidnightApi.js +68 -4
  44. package/lib/esm/api/helpers.d.ts +11 -1
  45. package/lib/esm/api/helpers.js +48 -2
  46. package/lib/esm/errors.d.ts +15 -0
  47. package/lib/esm/errors.js +19 -0
  48. package/lib/esm/fetch/Market.js +38 -3
  49. package/lib/esm/fetch/Position.d.ts +1 -1
  50. package/lib/esm/fetch/Position.js +5 -1
  51. package/lib/esm/fetch/utils.d.ts +1 -1
  52. package/lib/esm/fetch/utils.js +9 -2
  53. package/lib/esm/index.d.ts +1 -0
  54. package/lib/esm/index.js +1 -0
  55. package/lib/esm/market/index.d.ts +0 -2
  56. package/lib/esm/market/index.js +0 -2
  57. package/lib/esm/offers/Offer.d.ts +1 -1
  58. package/lib/esm/offers/OfferChainUtils.d.ts +179 -0
  59. package/lib/esm/offers/OfferChainUtils.js +443 -0
  60. package/lib/esm/offers/OfferUtils.d.ts +5 -5
  61. package/lib/esm/offers/OfferUtils.js +28 -15
  62. package/lib/esm/offers/index.d.ts +1 -0
  63. package/lib/esm/offers/index.js +1 -0
  64. package/lib/esm/{market → position}/Position.d.ts +83 -6
  65. package/lib/esm/{market → position}/Position.js +83 -5
  66. package/lib/{cjs/market → esm/position}/PositionUtils.d.ts +26 -1
  67. package/lib/esm/{market → position}/PositionUtils.js +27 -0
  68. package/lib/esm/position/index.d.ts +2 -0
  69. package/lib/esm/position/index.js +2 -0
  70. package/lib/esm/signatures/EcrecoverRatifierUtils.d.ts +118 -0
  71. package/lib/esm/signatures/EcrecoverRatifierUtils.js +151 -3
  72. package/lib/esm/signatures/Group.js +5 -3
  73. package/lib/esm/signatures/GroupUtils.d.ts +48 -0
  74. package/lib/esm/signatures/GroupUtils.js +51 -0
  75. package/lib/esm/signatures/RatifierUtils.js +16 -4
  76. package/lib/esm/signatures/SetterRatifierUtils.d.ts +31 -0
  77. package/lib/esm/signatures/SetterRatifierUtils.js +38 -0
  78. package/lib/esm/signatures/Tree.js +14 -4
  79. package/lib/esm/signatures/TreeUtils.d.ts +6 -3
  80. package/lib/esm/signatures/TreeUtils.js +35 -13
  81. package/lib/esm/signatures/eip712.d.ts +22 -0
  82. package/lib/esm/signatures/eip712.js +22 -0
  83. package/lib/esm/signatures/index.d.ts +1 -0
  84. package/lib/esm/signatures/index.js +1 -0
  85. package/package.json +8 -7
  86. package/src/index.ts +0 -19
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MidnightApi = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const errors_js_1 = require("../errors.js");
6
+ const index_js_1 = require("../math/index.js");
4
7
  const Payload_js_1 = require("../signatures/Payload.js");
5
8
  const helpers_js_1 = require("./helpers.js");
6
9
  /**
@@ -220,7 +223,10 @@ class MidnightApi {
220
223
  }),
221
224
  });
222
225
  return {
223
- data: response.data.map(helpers_js_1.mapTakeableOffer),
226
+ data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
227
+ marketId: input.marketId,
228
+ side: input.side,
229
+ }),
224
230
  };
225
231
  }
226
232
  /**
@@ -270,7 +276,61 @@ class MidnightApi {
270
276
  assets: input.assets,
271
277
  },
272
278
  });
273
- const takeableOffers = response.data.takeable_offers.map(helpers_js_1.mapTakeableOffer);
279
+ const takeableOffers = (0, helpers_js_1.mapBoundTakeableOffers)(response.data.takeable_offers, {
280
+ marketId: input.marketId,
281
+ side: input.side,
282
+ });
283
+ const averageWorstPrice = "averageWorstPrice" in input && input.averageWorstPrice != null
284
+ ? input.averageWorstPrice
285
+ : "slippage" in input && input.slippage != null
286
+ ? response.data.average_worst_price
287
+ : undefined;
288
+ if (averageWorstPrice != null) {
289
+ const guard = BigInt(averageWorstPrice);
290
+ let filledUnits = 0n;
291
+ let weightedPrice = 0n;
292
+ if ("units" in input && input.units != null) {
293
+ let remainingUnits = BigInt(input.units);
294
+ for (const take of takeableOffers) {
295
+ if (remainingUnits === 0n)
296
+ break;
297
+ const price = index_js_1.TickLib.tickToPrice(take.offer.tick);
298
+ const filled = take.units < remainingUnits ? take.units : remainingUnits;
299
+ filledUnits += filled;
300
+ weightedPrice += filled * price;
301
+ remainingUnits -= filled;
302
+ }
303
+ }
304
+ else {
305
+ let remainingAssets = BigInt(input.assets);
306
+ for (const take of takeableOffers) {
307
+ if (remainingAssets === 0n)
308
+ break;
309
+ const price = index_js_1.TickLib.tickToPrice(take.offer.tick);
310
+ const takeAssets = input.side === "asks"
311
+ ? morpho_ts_1.MathLib.mulDivUp(take.units, price, morpho_ts_1.MathLib.WAD)
312
+ : morpho_ts_1.MathLib.mulDivDown(take.units, price, morpho_ts_1.MathLib.WAD);
313
+ if (takeAssets === 0n)
314
+ continue;
315
+ const fillsEntireTake = takeAssets <= remainingAssets;
316
+ const filled = fillsEntireTake
317
+ ? take.units
318
+ : morpho_ts_1.MathLib.mulDiv(remainingAssets, morpho_ts_1.MathLib.WAD, price, input.side === "asks" ? "Down" : "Up");
319
+ if (filled === 0n)
320
+ continue;
321
+ filledUnits += filled;
322
+ weightedPrice += filled * price;
323
+ remainingAssets = fillsEntireTake ? remainingAssets - takeAssets : 0n;
324
+ }
325
+ }
326
+ if (filledUnits > 0n) {
327
+ const averagePrice = morpho_ts_1.MathLib.mulDivDown(weightedPrice, 1n, filledUnits);
328
+ const violatesGuard = input.side === "asks" ? averagePrice > guard : averagePrice < guard;
329
+ if (violatesGuard) {
330
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API quote takeable offers imply average price "${averagePrice}" outside average_worst_price guard "${guard}".`);
331
+ }
332
+ }
333
+ }
274
334
  return {
275
335
  data: {
276
336
  averageBestPrice: response.data.average_best_price,
@@ -323,7 +383,11 @@ class MidnightApi {
323
383
  });
324
384
  return {
325
385
  cursor: response.cursor,
326
- data: response.data.map(helpers_js_1.mapTakeableOffer),
386
+ data: (0, helpers_js_1.mapBoundTakeableOffers)(response.data, {
387
+ maker: input.maker,
388
+ marketIds: input.marketIds,
389
+ groups: input.groups,
390
+ }),
327
391
  };
328
392
  }
329
393
  /**
@@ -1,4 +1,4 @@
1
- import type { Hash } from "viem";
1
+ import { type Address, type Hash } from "viem";
2
2
  import type { ApiBookMarketResponse, ApiCollateralResponse, ApiPriceLevelResponse, ApiRequestParams, ApiTakeableOfferResponse, MempoolPayloadValidationResult, MidnightApiBookMarket, MidnightApiBookSide, MidnightApiCollateral, MidnightApiPriceLevel, MidnightApiTake } from "./types.js";
3
3
  /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
4
4
  export declare function requestMidnightApi<Response = unknown>(params: ApiRequestParams): Promise<Response>;
@@ -16,5 +16,15 @@ export declare function mapCollateral(collateral: ApiCollateralResponse): Midnig
16
16
  export declare function mapPriceLevel(level: ApiPriceLevelResponse): MidnightApiPriceLevel;
17
17
  /** @internal Maps a takeable-offer API payload to the SDK response shape. */
18
18
  export declare function mapTakeableOffer(takeableOffer: ApiTakeableOfferResponse): MidnightApiTake;
19
+ /** @internal API response context required for a takeable offer to be executable for the caller's request. */
20
+ export interface TakeableOfferContext {
21
+ readonly marketId?: Hash;
22
+ readonly side?: MidnightApiBookSide;
23
+ readonly maker?: Address;
24
+ readonly marketIds?: readonly Hash[];
25
+ readonly groups?: readonly Hash[];
26
+ }
27
+ /** @internal Maps, validates, and best-price-sorts API takeable offers. */
28
+ export declare function mapBoundTakeableOffers(takeableOffers: readonly ApiTakeableOfferResponse[], context: TakeableOfferContext): MidnightApiTake[];
19
29
  /** @internal Parses the mempool validation response envelope. */
20
30
  export declare function parseValidationResponse(response: unknown): MempoolPayloadValidationResult;
@@ -6,13 +6,16 @@ exports.mapBookMarket = mapBookMarket;
6
6
  exports.mapCollateral = mapCollateral;
7
7
  exports.mapPriceLevel = mapPriceLevel;
8
8
  exports.mapTakeableOffer = mapTakeableOffer;
9
+ exports.mapBoundTakeableOffers = mapBoundTakeableOffers;
9
10
  exports.parseValidationResponse = parseValidationResponse;
10
11
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
12
+ const viem_1 = require("viem");
11
13
  const errors_js_1 = require("../errors.js");
14
+ const index_js_1 = require("../market/index.js");
12
15
  const DEFAULT_MIDNIGHT_API_URL = new URL("/v0/midnight", morpho_ts_1.BLUE_API_BASE_URL);
13
16
  // Keep this literal in source so the browser ESM build does not import package.json
14
17
  // through Node-only createRequire/module shims.
15
- const MIDNIGHT_SDK_VERSION = "0.1.0";
18
+ const MIDNIGHT_SDK_VERSION = "1.0.1";
16
19
  /** @internal Sends one Midnight API request and maps non-2xx responses to SDK errors. */
17
20
  async function requestMidnightApi(params) {
18
21
  const baseUrl = new URL(params.baseUrl ?? DEFAULT_MIDNIGHT_API_URL);
@@ -162,6 +165,50 @@ function mapTakeableOffer(takeableOffer) {
162
165
  ratifierData: takeableOffer.ratifier_data,
163
166
  };
164
167
  }
168
+ /** @internal Maps, validates, and best-price-sorts API takeable offers. */
169
+ function mapBoundTakeableOffers(takeableOffers, context) {
170
+ const mapped = takeableOffers.map((takeableOffer) => {
171
+ const take = mapTakeableOffer(takeableOffer);
172
+ const embeddedMarketId = index_js_1.MarketUtils.toId(take.offer.market);
173
+ if (!(0, morpho_ts_1.isHexEqual)(embeddedMarketId, take.marketId)) {
174
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match embedded offer market "${embeddedMarketId}".`);
175
+ }
176
+ if (context.marketId != null &&
177
+ !(0, morpho_ts_1.isHexEqual)(take.marketId, context.marketId)) {
178
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" does not match requested market "${context.marketId}".`);
179
+ }
180
+ if (context.marketIds != null &&
181
+ context.marketIds.length > 0 &&
182
+ !context.marketIds.some((marketId) => (0, morpho_ts_1.isHexEqual)(marketId, take.marketId))) {
183
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer market_id "${take.marketId}" is outside the requested market_ids filter.`);
184
+ }
185
+ if (context.side != null) {
186
+ const expectedBuy = context.side === "bids";
187
+ if (take.offer.buy !== expectedBuy) {
188
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API ${context.side} takeable offer returned offer.buy "${take.offer.buy}".`);
189
+ }
190
+ }
191
+ if (context.maker != null &&
192
+ !(0, viem_1.isAddressEqual)(take.offer.maker, context.maker)) {
193
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer maker "${take.offer.maker}" does not match requested maker "${context.maker}".`);
194
+ }
195
+ if (context.groups != null &&
196
+ context.groups.length > 0 &&
197
+ !context.groups.some((group) => (0, morpho_ts_1.isHexEqual)(group, take.offer.group))) {
198
+ throw new errors_js_1.InvalidMidnightApiResponseError(`Midnight API takeable offer group "${take.offer.group}" is outside the requested groups filter.`);
199
+ }
200
+ return take;
201
+ });
202
+ if (context.side == null)
203
+ return mapped;
204
+ return [...mapped].sort((a, b) => {
205
+ if (a.offer.tick === b.offer.tick)
206
+ return 0;
207
+ if (context.side === "asks")
208
+ return a.offer.tick < b.offer.tick ? -1 : 1;
209
+ return a.offer.tick > b.offer.tick ? -1 : 1;
210
+ });
211
+ }
165
212
  /** @internal Parses the mempool validation response envelope. */
166
213
  function parseValidationResponse(response) {
167
214
  const parsedResponse = requireRecord(response, "validation response");
@@ -277,6 +277,21 @@ export declare class InvalidTypedDataSignatureError extends Error {
277
277
  readonly signer: Address;
278
278
  constructor(signer: Address, cause?: unknown);
279
279
  }
280
+ /**
281
+ * Thrown when decoded Ecrecover ratifier data contains a non-canonical signature `v` value.
282
+ *
283
+ * @example
284
+ * ```ts
285
+ * import { InvalidEcrecoverSignatureVError } from "@morpho-org/midnight-sdk";
286
+ *
287
+ * throw new InvalidEcrecoverSignatureVError(29);
288
+ * ```
289
+ */
290
+ export declare class InvalidEcrecoverSignatureVError extends Error {
291
+ /** Invalid ECDSA recovery id. */
292
+ readonly v: number;
293
+ constructor(v: number);
294
+ }
280
295
  /**
281
296
  * Thrown when the Midnight API returns a non-2xx response.
282
297
  *
package/lib/cjs/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.InvalidMidnightApiResponseError = exports.MidnightApiError = exports.InvalidTypedDataSignatureError = exports.MidnightMempoolValidationError = exports.ChainIdMismatchError = exports.InvalidTreeError = exports.InvalidTreeHeightError = exports.PayloadDecodeError = exports.InvalidOfferParameterError = exports.UnknownCollateralIndexError = exports.InvalidMarketParameterError = exports.InvalidPositionAccrualStateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.SettlementFeeExceedsPriceError = exports.InvalidTickSpacingError = exports.PriceGreaterThanOneError = exports.TickOutOfRangeError = exports.InvalidOfferGroupError = void 0;
3
+ exports.InvalidMidnightApiResponseError = exports.MidnightApiError = exports.InvalidEcrecoverSignatureVError = exports.InvalidTypedDataSignatureError = exports.MidnightMempoolValidationError = exports.ChainIdMismatchError = exports.InvalidTreeError = exports.InvalidTreeHeightError = exports.PayloadDecodeError = exports.InvalidOfferParameterError = exports.UnknownCollateralIndexError = exports.InvalidMarketParameterError = exports.InvalidPositionAccrualStateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.SettlementFeeExceedsPriceError = exports.InvalidTickSpacingError = exports.PriceGreaterThanOneError = exports.TickOutOfRangeError = exports.InvalidOfferGroupError = void 0;
4
4
  /**
5
5
  * Thrown when a Midnight offer group violates protocol-level group mechanics.
6
6
  *
@@ -345,6 +345,26 @@ class InvalidTypedDataSignatureError extends Error {
345
345
  }
346
346
  }
347
347
  exports.InvalidTypedDataSignatureError = InvalidTypedDataSignatureError;
348
+ /**
349
+ * Thrown when decoded Ecrecover ratifier data contains a non-canonical signature `v` value.
350
+ *
351
+ * @example
352
+ * ```ts
353
+ * import { InvalidEcrecoverSignatureVError } from "@morpho-org/midnight-sdk";
354
+ *
355
+ * throw new InvalidEcrecoverSignatureVError(29);
356
+ * ```
357
+ */
358
+ class InvalidEcrecoverSignatureVError extends Error {
359
+ /** Invalid ECDSA recovery id. */
360
+ v;
361
+ constructor(v) {
362
+ super(`Ecrecover signature v "${v}" is invalid. Use canonical Ethereum v 27 or 28.`);
363
+ this.name = "InvalidEcrecoverSignatureVError";
364
+ this.v = v;
365
+ }
366
+ }
367
+ exports.InvalidEcrecoverSignatureVError = InvalidEcrecoverSignatureVError;
348
368
  /**
349
369
  * Thrown when the Midnight API returns a non-2xx response.
350
370
  *
@@ -5,6 +5,7 @@ exports.fetchMarket = fetchMarket;
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const actions_1 = require("viem/actions");
7
7
  const abis_js_1 = require("../abis.js");
8
+ const errors_js_1 = require("../errors.js");
8
9
  const index_js_1 = require("../market/index.js");
9
10
  const utils_js_1 = require("./utils.js");
10
11
  /**
@@ -45,7 +46,11 @@ async function fetchMarketParams(client, params) {
45
46
  functionName: "toMarket",
46
47
  args: [params.marketId],
47
48
  });
48
- return new index_js_1.MarketParams(market);
49
+ return normalizeFetchedMarketParams(market, {
50
+ marketId: params.marketId,
51
+ chainId,
52
+ midnight,
53
+ });
49
54
  }
50
55
  /**
51
56
  * Fetches a hydrated market by id.
@@ -96,7 +101,11 @@ async function fetchMarket(client, params) {
96
101
  ]);
97
102
  const [totalUnits, lossFactor, withdrawable, continuousFeeCredit, settlementFeeCbps0, settlementFeeCbps1, settlementFeeCbps2, settlementFeeCbps3, settlementFeeCbps4, settlementFeeCbps5, settlementFeeCbps6, continuousFee, tickSpacing,] = state;
98
103
  return new index_js_1.Market({
99
- params: new index_js_1.MarketParams(market),
104
+ params: normalizeFetchedMarketParams(market, {
105
+ marketId: params.marketId,
106
+ chainId,
107
+ midnight,
108
+ }),
100
109
  totalUnits,
101
110
  lossFactor,
102
111
  withdrawable,
@@ -114,3 +123,29 @@ async function fetchMarket(client, params) {
114
123
  tickSpacing,
115
124
  });
116
125
  }
126
+ function normalizeFetchedMarketParams(market, expected) {
127
+ const marketParams = new index_js_1.MarketParams(market);
128
+ if (marketParams.chainId !== BigInt(expected.chainId)) {
129
+ throw new errors_js_1.InvalidMarketParameterError({
130
+ parameter: "chainId",
131
+ value: marketParams.chainId,
132
+ instruction: `Fetched market must use client chain id "${expected.chainId}".`,
133
+ });
134
+ }
135
+ if (marketParams.midnight.toLowerCase() !== expected.midnight.toLowerCase()) {
136
+ throw new errors_js_1.InvalidMarketParameterError({
137
+ parameter: "midnight",
138
+ value: marketParams.midnight,
139
+ instruction: `Fetched market must use Midnight contract "${expected.midnight}".`,
140
+ });
141
+ }
142
+ const actualMarketId = index_js_1.MarketUtils.toId(marketParams);
143
+ if (actualMarketId.toLowerCase() !== expected.marketId.toLowerCase()) {
144
+ throw new errors_js_1.InvalidMarketParameterError({
145
+ parameter: "marketId",
146
+ value: actualMarketId,
147
+ instruction: `Fetched market must match requested market id "${expected.marketId}".`,
148
+ });
149
+ }
150
+ return marketParams;
151
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Address, Client, Hash } from "viem";
2
- import { AccrualPosition, Position } from "../market/index.js";
2
+ import { AccrualPosition, Position } from "../position/index.js";
3
3
  import type { MidnightFetchParams } from "./types.js";
4
4
  /**
5
5
  * Fetches a Midnight position by id and user.
@@ -6,7 +6,7 @@ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const actions_1 = require("viem/actions");
7
7
  const abis_js_1 = require("../abis.js");
8
8
  const constants_js_1 = require("../constants.js");
9
- const index_js_1 = require("../market/index.js");
9
+ const index_js_1 = require("../position/index.js");
10
10
  const GetPosition_js_1 = require("../queries/GetPosition.js");
11
11
  const Market_js_1 = require("./Market.js");
12
12
  const utils_js_1 = require("./utils.js");
@@ -64,6 +64,8 @@ async function fetchPosition(client, params) {
64
64
  });
65
65
  const collateral = position.collateral;
66
66
  return new index_js_1.Position({
67
+ user: params.user,
68
+ marketId: params.marketId,
67
69
  credit: position.credit,
68
70
  pendingFee: position.pendingFee,
69
71
  lastLossFactor: position.lastLossFactor,
@@ -96,6 +98,8 @@ async function fetchPosition(client, params) {
96
98
  });
97
99
  }));
98
100
  return new index_js_1.Position({
101
+ user: params.user,
102
+ marketId: params.marketId,
99
103
  credit: position[0],
100
104
  pendingFee: position[1],
101
105
  lastLossFactor: position[2],
@@ -4,5 +4,5 @@ import type { DeploylessFetchParameters, MidnightCallParameters } from "./types.
4
4
  export declare const callParameters: (params: MidnightCallParameters) => MidnightCallParameters;
5
5
  /** @internal Returns the configured deployless mode, defaulting to enabled. */
6
6
  export declare const shouldUseDeployless: (params: DeploylessFetchParameters) => boolean | "force";
7
- /** @internal Returns the configured viem client chain id or fetches it from RPC. */
7
+ /** @internal Returns the RPC chain id and rejects configured-chain drift. */
8
8
  export declare const resolveChainId: (client: Client) => Promise<number>;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveChainId = exports.shouldUseDeployless = exports.callParameters = void 0;
4
4
  const actions_1 = require("viem/actions");
5
+ const errors_js_1 = require("../errors.js");
5
6
  /** @internal Extracts viem call parameters from Midnight fetch inputs. */
6
7
  const callParameters = (params) => ({
7
8
  account: params.account,
@@ -13,6 +14,12 @@ exports.callParameters = callParameters;
13
14
  /** @internal Returns the configured deployless mode, defaulting to enabled. */
14
15
  const shouldUseDeployless = (params) => params.deployless ?? true;
15
16
  exports.shouldUseDeployless = shouldUseDeployless;
16
- /** @internal Returns the configured viem client chain id or fetches it from RPC. */
17
- const resolveChainId = async (client) => client.chain?.id ?? (await (0, actions_1.getChainId)(client));
17
+ /** @internal Returns the RPC chain id and rejects configured-chain drift. */
18
+ const resolveChainId = async (client) => {
19
+ const rpcChainId = await (0, actions_1.getChainId)(client);
20
+ if (client.chain?.id != null && client.chain.id !== rpcChainId) {
21
+ throw new errors_js_1.ChainIdMismatchError(client.chain.id, BigInt(rpcChainId));
22
+ }
23
+ return rpcChainId;
24
+ };
18
25
  exports.resolveChainId = resolveChainId;
@@ -5,6 +5,7 @@ export * from "./fetch/index.js";
5
5
  export * from "./market/index.js";
6
6
  export * from "./math/index.js";
7
7
  export * from "./offers/index.js";
8
+ export * from "./position/index.js";
8
9
  export * from "./signatures/index.js";
9
10
  /**
10
11
  * Namespace for Midnight mempool payload utilities.
package/lib/cjs/index.js CHANGED
@@ -22,6 +22,7 @@ __exportStar(require("./fetch/index.js"), exports);
22
22
  __exportStar(require("./market/index.js"), exports);
23
23
  __exportStar(require("./math/index.js"), exports);
24
24
  __exportStar(require("./offers/index.js"), exports);
25
+ __exportStar(require("./position/index.js"), exports);
25
26
  __exportStar(require("./signatures/index.js"), exports);
26
27
  /**
27
28
  * Namespace for Midnight mempool payload utilities.
@@ -1,4 +1,2 @@
1
1
  export * from "./Market.js";
2
2
  export * from "./MarketUtils.js";
3
- export * from "./Position.js";
4
- export * from "./PositionUtils.js";
@@ -16,5 +16,3 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./Market.js"), exports);
18
18
  __exportStar(require("./MarketUtils.js"), exports);
19
- __exportStar(require("./Position.js"), exports);
20
- __exportStar(require("./PositionUtils.js"), exports);
@@ -721,7 +721,7 @@ export interface BuildOfferParams {
721
721
  readonly maxUnits?: BigIntish;
722
722
  /** Maximum buyer or seller assets; defaults to zero. Exactly one of `maxUnits` and `maxAssets` must be non-zero. */
723
723
  readonly maxAssets?: BigIntish;
724
- /** Maximum market continuous fee accepted by this offer; defaults to the protocol maximum. */
724
+ /** Maximum market continuous fee accepted by this offer; defaults to zero. */
725
725
  readonly continuousFeeCap?: BigIntish;
726
726
  /** Offer start timestamp; defaults to zero. */
727
727
  readonly start?: BigIntish;
@@ -0,0 +1,179 @@
1
+ import { type BigIntish } from "@morpho-org/morpho-ts";
2
+ /** One time-bounded offer leg to convert into a Midnight `Offer.create` input. */
3
+ export interface FixedRateOfferChainLeg {
4
+ /** Spacing-aligned Midnight tick for this offer. */
5
+ readonly tick: bigint;
6
+ /** First timestamp at which the offer leg is active. */
7
+ readonly startTimestamp: bigint;
8
+ /** Last timestamp at which the offer leg is active. */
9
+ readonly expiryTimestamp: bigint;
10
+ }
11
+ /** Parameters shared by lend-only and borrow-only fixed-rate offer-chain builders. */
12
+ export interface BuildFixedRateOfferChainParams {
13
+ /** Target yearly fixed rate as a decimal number, for example `0.05` for 5%. */
14
+ readonly targetRate: number;
15
+ /** Tick spacing enforced by the market. */
16
+ readonly tickSpacing: BigIntish;
17
+ /** Market maturity timestamp in seconds. */
18
+ readonly maturityTimestamp: BigIntish;
19
+ /** First timestamp the chain should cover. */
20
+ readonly chainStartTimestamp: BigIntish;
21
+ /** Latest timestamp the chain may cover. */
22
+ readonly chainEndTimestamp: BigIntish;
23
+ }
24
+ /**
25
+ * Utilities for building time-bounded Midnight offer chains.
26
+ *
27
+ * A Midnight offer has one fixed price, so its displayed yearly rate changes
28
+ * as maturity approaches. The markets app uses these helpers when a maker wants
29
+ * to post, for example, a 5% order for several months: the app builds several
30
+ * adjacent offers sharing the same reserve, each with a different tick and time
31
+ * window, so the order reviews and renders as a stable 5% order across the
32
+ * selected window instead of drifting upward as time passes.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
37
+ *
38
+ * const legs = OfferChainUtils.buildLendFixedRateOfferChain({
39
+ * targetRate: 0.05,
40
+ * tickSpacing: 4n,
41
+ * maturityTimestamp: 1_798_761_600n,
42
+ * chainStartTimestamp: 1_767_225_600n,
43
+ * chainEndTimestamp: 1_791_153_600n,
44
+ * });
45
+ * console.log(legs[0]?.tick);
46
+ * ```
47
+ */
48
+ export declare namespace OfferChainUtils {
49
+ /**
50
+ * Maximum fraction of the initial time-to-maturity covered by a fixed-rate offer chain.
51
+ *
52
+ * Use this cap before displaying an expiry picker for a fixed-rate maker
53
+ * order. The last part of the maturity window is intentionally excluded
54
+ * because tiny time changes cause large displayed-rate drift.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
59
+ *
60
+ * console.log(OfferChainUtils.MAX_EXPIRY_TTM_FRACTION);
61
+ * ```
62
+ */
63
+ const MAX_EXPIRY_TTM_FRACTION = 0.75;
64
+ /**
65
+ * Builds borrow-side sell-offer legs that approximate one fixed maker rate over time.
66
+ *
67
+ * Use before a make-borrow or supply-collateral-and-make-borrow flow when a
68
+ * borrower wants one displayed fixed borrow rate across a longer window. Map
69
+ * the returned legs to `Offer.create({ buy: false, ... })`, then group and
70
+ * submit them through the maker flow.
71
+ *
72
+ * Borrow chains read their target rate at each leg's expiry edge. If a leg
73
+ * would need to extend past `chainEndTimestamp`, it is dropped rather than
74
+ * clamped so the expiry edge remains the recoverable target-rate edge.
75
+ *
76
+ * @param params - Fixed-rate offer-chain parameters without a side field.
77
+ * @param params.targetRate - Target yearly fixed rate expressed as a decimal number.
78
+ * @param params.tickSpacing - Tick spacing enforced by the market.
79
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
80
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
81
+ * @param params.chainEndTimestamp - Latest timestamp the chain may cover.
82
+ * @returns Borrow-side offer legs that can be mapped to `Offer.create({ buy: false, ... })`.
83
+ * @throws {InvalidOfferParameterError} when an input is invalid or the end timestamp exceeds the supported horizon.
84
+ * @example
85
+ * ```ts
86
+ * import { Offer, OfferChainUtils } from "@morpho-org/midnight-sdk";
87
+ *
88
+ * const legs = OfferChainUtils.buildBorrowFixedRateOfferChain({
89
+ * targetRate: 0.08,
90
+ * tickSpacing: market.tickSpacing,
91
+ * maturityTimestamp: market.params.maturity,
92
+ * chainStartTimestamp: now,
93
+ * chainEndTimestamp: expiry,
94
+ * });
95
+ * const offers = legs.map((leg) =>
96
+ * Offer.create({
97
+ * ...baseOffer,
98
+ * buy: false,
99
+ * tick: leg.tick,
100
+ * start: leg.startTimestamp,
101
+ * expiry: leg.expiryTimestamp,
102
+ * }),
103
+ * );
104
+ * ```
105
+ */
106
+ function buildBorrowFixedRateOfferChain(params: BuildFixedRateOfferChainParams): readonly FixedRateOfferChainLeg[];
107
+ /**
108
+ * Builds lend-side buy-offer legs that approximate one fixed maker rate over time.
109
+ *
110
+ * Use before a make-lend flow when a lender wants one displayed fixed lend
111
+ * rate across a longer window. Map the returned legs to
112
+ * `Offer.create({ buy: true, ... })`, then group and submit them through the
113
+ * maker flow.
114
+ *
115
+ * Lend chains read their target rate at each leg's start edge. The first leg
116
+ * may start before `chainStartTimestamp`; clamping that edge would move the
117
+ * recoverable display rate below the maker's target.
118
+ *
119
+ * @param params - Fixed-rate offer-chain parameters without a side field.
120
+ * @param params.targetRate - Target yearly fixed rate expressed as a decimal number.
121
+ * @param params.tickSpacing - Tick spacing enforced by the market.
122
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
123
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
124
+ * @param params.chainEndTimestamp - Latest timestamp the chain may cover.
125
+ * @returns Lend-side offer legs that can be mapped to `Offer.create({ buy: true, ... })`.
126
+ * @throws {InvalidOfferParameterError} when an input is invalid or the end timestamp exceeds the supported horizon.
127
+ * @example
128
+ * ```ts
129
+ * import { Offer, OfferChainUtils } from "@morpho-org/midnight-sdk";
130
+ *
131
+ * const legs = OfferChainUtils.buildLendFixedRateOfferChain({
132
+ * targetRate: 0.05,
133
+ * tickSpacing: market.tickSpacing,
134
+ * maturityTimestamp: market.params.maturity,
135
+ * chainStartTimestamp: now,
136
+ * chainEndTimestamp: expiry,
137
+ * });
138
+ * const offers = legs.map((leg) =>
139
+ * Offer.create({
140
+ * ...baseOffer,
141
+ * buy: true,
142
+ * tick: leg.tick,
143
+ * start: leg.startTimestamp,
144
+ * expiry: leg.expiryTimestamp,
145
+ * }),
146
+ * );
147
+ * ```
148
+ */
149
+ function buildLendFixedRateOfferChain(params: BuildFixedRateOfferChainParams): readonly FixedRateOfferChainLeg[];
150
+ /**
151
+ * Returns the latest supported end timestamp for a fixed-rate offer chain.
152
+ *
153
+ * Chains intentionally stop before the final part of the maturity window
154
+ * because rate sensitivity accelerates near maturity and would require too
155
+ * many short-lived offers for a stable maker quote.
156
+ * Call this when constraining a make-offer expiry selector, then pass the
157
+ * selected timestamp to the lend-only or borrow-only chain builder.
158
+ *
159
+ * @param params - Maturity and chain-start timestamps.
160
+ * @param params.maturityTimestamp - Market maturity timestamp in seconds.
161
+ * @param params.chainStartTimestamp - First timestamp the chain should cover.
162
+ * @returns Latest accepted chain end timestamp.
163
+ * @throws {InvalidOfferParameterError} when a timestamp is invalid.
164
+ * @example
165
+ * ```ts
166
+ * import { OfferChainUtils } from "@morpho-org/midnight-sdk";
167
+ *
168
+ * const maxExpiry = OfferChainUtils.getMaxFixedRateOfferChainEndTimestamp({
169
+ * maturityTimestamp: market.params.maturity,
170
+ * chainStartTimestamp: now,
171
+ * });
172
+ * console.log(maxExpiry);
173
+ * ```
174
+ */
175
+ function getMaxFixedRateOfferChainEndTimestamp(params: {
176
+ readonly maturityTimestamp: BigIntish;
177
+ readonly chainStartTimestamp: BigIntish;
178
+ }): bigint;
179
+ }