@morpho-dev/router 0.0.12 → 0.0.14

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 (33) hide show
  1. package/README.md +15 -0
  2. package/dist/drizzle/0000_add-offers-table.sql +37 -0
  3. package/dist/drizzle/0001_create_offer_status_relation.sql +10 -0
  4. package/dist/drizzle/0002_add_created_at_in_offer_status_relation.sql +3 -0
  5. package/dist/drizzle/0003_add-cursor-indices-to-offers.sql +6 -0
  6. package/dist/drizzle/0004_offer-start.sql +1 -0
  7. package/dist/drizzle/0005_rename-price-token-buy.sql +8 -0
  8. package/dist/drizzle/0006_rename-buy.sql +3 -0
  9. package/dist/drizzle/0007_rename-offering.sql +3 -0
  10. package/dist/drizzle/0008_add-consumed-relation.sql +10 -0
  11. package/dist/drizzle/meta/0000_snapshot.json +344 -0
  12. package/dist/drizzle/meta/0001_snapshot.json +426 -0
  13. package/dist/drizzle/meta/0002_snapshot.json +439 -0
  14. package/dist/drizzle/meta/0003_snapshot.json +553 -0
  15. package/dist/drizzle/meta/0004_snapshot.json +559 -0
  16. package/dist/drizzle/meta/0005_snapshot.json +559 -0
  17. package/dist/drizzle/meta/0006_snapshot.json +559 -0
  18. package/dist/drizzle/meta/0007_snapshot.json +559 -0
  19. package/dist/drizzle/meta/0008_snapshot.json +635 -0
  20. package/dist/drizzle/meta/_journal.json +69 -0
  21. package/dist/index.browser.d.cts +116 -25
  22. package/dist/index.browser.d.ts +116 -25
  23. package/dist/index.browser.js +671 -70
  24. package/dist/index.browser.js.map +1 -1
  25. package/dist/index.browser.mjs +670 -72
  26. package/dist/index.browser.mjs.map +1 -1
  27. package/dist/index.node.d.cts +934 -7
  28. package/dist/index.node.d.ts +934 -7
  29. package/dist/index.node.js +2328 -4819
  30. package/dist/index.node.js.map +1 -1
  31. package/dist/index.node.mjs +2319 -4820
  32. package/dist/index.node.mjs.map +1 -1
  33. package/package.json +17 -3
@@ -1,7 +1,9 @@
1
- import { Errors, Offer } from '@morpho-dev/mempool';
1
+ import { Errors, Offer, Format } from '@morpho-dev/mempool';
2
2
  export * from '@morpho-dev/mempool';
3
3
  import { base, mainnet } from 'viem/chains';
4
- import { parseAbi } from 'viem';
4
+ import { maxUint256, parseAbi } from 'viem';
5
+ import { z } from 'zod/v4';
6
+ import { createDocument } from 'zod-openapi';
5
7
 
6
8
  var __defProp = Object.defineProperty;
7
9
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -65,9 +67,9 @@ var chains = {
65
67
  }
66
68
  };
67
69
 
68
- // src/core/index.ts
69
- var core_exports = {};
70
- __export(core_exports, {
70
+ // src/core/Client.ts
71
+ var Client_exports = {};
72
+ __export(Client_exports, {
71
73
  HttpForbiddenError: () => HttpForbiddenError,
72
74
  HttpGetOffersFailedError: () => HttpGetOffersFailedError,
73
75
  HttpRateLimitError: () => HttpRateLimitError,
@@ -77,7 +79,647 @@ __export(core_exports, {
77
79
  get: () => get,
78
80
  match: () => match
79
81
  });
80
- var MAX_BATCH_SIZE = 100;
82
+
83
+ // src/RouterOffer.ts
84
+ var RouterOffer_exports = {};
85
+ __export(RouterOffer_exports, {
86
+ InvalidRouterOfferError: () => InvalidRouterOfferError,
87
+ OfferStatusValues: () => OfferStatusValues,
88
+ RouterOfferSchema: () => RouterOfferSchema,
89
+ from: () => from,
90
+ fromSnakeCase: () => fromSnakeCase,
91
+ random: () => random,
92
+ toSnakeCase: () => toSnakeCase
93
+ });
94
+ var OfferStatusValues = [
95
+ "valid",
96
+ "callback_not_supported",
97
+ "callback_error",
98
+ "unverified"
99
+ ];
100
+ var RouterOfferSchema = (parameters) => Offer.OfferSchema(parameters).extend({
101
+ consumed: z.bigint({ coerce: true }).min(0n).max(maxUint256),
102
+ status: z.enum(OfferStatusValues),
103
+ metadata: z.object({
104
+ issue: z.string()
105
+ }).optional()
106
+ });
107
+ function from(input) {
108
+ try {
109
+ const parsedOffer = RouterOfferSchema({ omitHash: true }).parse(input);
110
+ const parsedHash = Offer.OfferHashSchema.parse(Offer.hash(parsedOffer));
111
+ return {
112
+ ...parsedOffer,
113
+ hash: parsedHash
114
+ };
115
+ } catch (error) {
116
+ throw new InvalidRouterOfferError(error);
117
+ }
118
+ }
119
+ function fromSnakeCase(input) {
120
+ return from(Format.fromSnakeCase(input));
121
+ }
122
+ function toSnakeCase(offer) {
123
+ return Format.toSnakeCase(offer);
124
+ }
125
+ function random() {
126
+ const baseOffer = Offer.random();
127
+ return from({
128
+ ...baseOffer,
129
+ status: "valid",
130
+ metadata: void 0,
131
+ consumed: 0n
132
+ });
133
+ }
134
+ var InvalidRouterOfferError = class extends Errors.BaseError {
135
+ constructor(error) {
136
+ super("Invalid router offer.", { cause: error });
137
+ __publicField(this, "name", "RouterOffer.InvalidRouterOfferError");
138
+ }
139
+ };
140
+
141
+ // src/utils/batch.ts
142
+ function* batch(array, batchSize) {
143
+ for (let i = 0; i < array.length; i += batchSize) {
144
+ yield array.slice(i, i + batchSize);
145
+ }
146
+ }
147
+
148
+ // src/utils/cursor.ts
149
+ function validateCursor(cursor) {
150
+ if (!cursor || typeof cursor !== "object") {
151
+ throw new Error("Cursor must be an object");
152
+ }
153
+ const c = cursor;
154
+ if (!["rate", "maturity", "expiry", "amount"].includes(c.sort)) {
155
+ throw new Error(
156
+ `Invalid sort field: ${c.sort}. Must be one of: rate, maturity, expiry, amount`
157
+ );
158
+ }
159
+ if (!["asc", "desc"].includes(c.dir)) {
160
+ throw new Error(`Invalid direction: ${c.dir}. Must be one of: asc, desc`);
161
+ }
162
+ if (!/^0x[a-fA-F0-9]{64}$/.test(c.hash)) {
163
+ throw new Error(
164
+ `Invalid hash format: ${c.hash}. Must be a 64-character hex string starting with 0x`
165
+ );
166
+ }
167
+ const validations = {
168
+ rate: {
169
+ field: "rate",
170
+ type: "string",
171
+ pattern: /^\d+$/,
172
+ error: "numeric string"
173
+ },
174
+ amount: {
175
+ field: "assets",
176
+ type: "string",
177
+ pattern: /^\d+$/,
178
+ error: "numeric string"
179
+ },
180
+ maturity: {
181
+ field: "maturity",
182
+ type: "number",
183
+ validator: (val) => val > 0,
184
+ error: "positive number"
185
+ },
186
+ expiry: {
187
+ field: "expiry",
188
+ type: "number",
189
+ validator: (val) => val > 0,
190
+ error: "positive number"
191
+ }
192
+ };
193
+ const validation = validations[c.sort];
194
+ if (!validation) {
195
+ throw new Error(`Invalid sort field: ${c.sort}`);
196
+ }
197
+ const fieldValue = c[validation.field];
198
+ if (!fieldValue) {
199
+ throw new Error(`${c.sort} sort requires '${validation.field}' field to be present`);
200
+ }
201
+ if (typeof fieldValue !== validation.type) {
202
+ throw new Error(
203
+ `${c.sort} sort requires '${validation.field}' field of type ${validation.type}`
204
+ );
205
+ }
206
+ if (validation.pattern && !validation.pattern.test(fieldValue)) {
207
+ throw new Error(
208
+ `Invalid ${validation.field} format: ${fieldValue}. Must be a ${validation.error}`
209
+ );
210
+ }
211
+ if (validation.validator && !validation.validator(fieldValue)) {
212
+ throw new Error(
213
+ `Invalid ${validation.field} value: ${fieldValue}. Must be a ${validation.error}`
214
+ );
215
+ }
216
+ return true;
217
+ }
218
+ function encodeCursor(c) {
219
+ return Buffer.from(JSON.stringify(c)).toString("base64url");
220
+ }
221
+ function decodeCursor(token) {
222
+ if (!token) return null;
223
+ const decoded = JSON.parse(Buffer.from(token, "base64url").toString());
224
+ validateCursor(decoded);
225
+ return decoded;
226
+ }
227
+
228
+ // src/utils/wait.ts
229
+ async function wait(time) {
230
+ return new Promise((res) => setTimeout(res, time));
231
+ }
232
+
233
+ // src/utils/poll.ts
234
+ function poll(fn, { interval }) {
235
+ let active = true;
236
+ const unwatch = () => active = false;
237
+ const watch = async () => {
238
+ await wait(interval);
239
+ const poll2 = async () => {
240
+ if (!active) return;
241
+ await fn({ unpoll: unwatch });
242
+ await wait(interval);
243
+ poll2();
244
+ };
245
+ poll2();
246
+ };
247
+ watch();
248
+ return unwatch;
249
+ }
250
+
251
+ // src/core/apiSchema/requests.ts
252
+ var MAX_LIMIT = 100;
253
+ var DEFAULT_LIMIT = 20;
254
+ var MAX_LLTV = 100;
255
+ var MIN_LLTV = 0;
256
+ var GetOffersQueryParams = z.object({
257
+ // Core filtering parameters
258
+ creators: z.string().regex(/^0x[a-fA-F0-9]{40}(,0x[a-fA-F0-9]{40})*$/, {
259
+ message: "Creators must be comma-separated Ethereum addresses"
260
+ }).transform((val) => val.split(",").map((addr) => addr.toLowerCase())).optional().meta({
261
+ description: "Filter by multiple creator addresses (comma-separated)",
262
+ example: "0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
263
+ }),
264
+ side: z.enum(["buy", "sell"]).optional().meta({
265
+ description: "Filter by offer type: buy offers or sell offers",
266
+ example: "buy"
267
+ }),
268
+ chains: z.string().regex(/^\d+(,\d+)*$/, {
269
+ message: "Chains must be comma-separated chain IDs"
270
+ }).transform((val) => val.split(",").map(Number)).optional().meta({
271
+ description: "Filter by multiple blockchain networks (comma-separated chain IDs)",
272
+ example: "1,137,10"
273
+ }),
274
+ loan_tokens: z.string().regex(/^0x[a-fA-F0-9]{40}(,0x[a-fA-F0-9]{40})*$/, {
275
+ message: "Loan assets must be comma-separated Ethereum addresses"
276
+ }).transform((val) => val.split(",").map((addr) => addr.toLowerCase())).optional().meta({
277
+ description: "Filter by multiple loan assets (comma-separated)",
278
+ example: "0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
279
+ }),
280
+ status: z.string().regex(/^[a-zA-Z_]+(,[a-zA-Z_]+)*$/, {
281
+ message: "Status must be comma-separated status values"
282
+ }).transform((val) => val.split(",")).refine((statuses) => statuses.every((status) => OfferStatusValues.includes(status)), {
283
+ message: `Invalid status value. Must be one of: ${OfferStatusValues.join(", ")}`
284
+ }).optional().meta({
285
+ description: `Filter by multiple statuses (comma-separated). Valid values: ${OfferStatusValues.join(", ")}. By default, only offers with 'valid' status are returned.`,
286
+ example: "valid,callback_error"
287
+ }),
288
+ callback_addresses: z.string().regex(/^0x[a-fA-F0-9]{40}(,0x[a-fA-F0-9]{40})*$/, {
289
+ message: "Callback addresses must be comma-separated Ethereum addresses"
290
+ }).transform((val) => val.split(",").map((addr) => addr.toLowerCase())).optional().meta({
291
+ description: "Filter by multiple callback addresses (comma-separated)",
292
+ example: "0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
293
+ }),
294
+ // Asset range
295
+ min_amount: z.bigint({ coerce: true }).positive({
296
+ message: "Min amount must be a positive number"
297
+ }).optional().meta({
298
+ description: "Minimum amount of assets in the offer",
299
+ example: "1000"
300
+ }),
301
+ max_amount: z.bigint({ coerce: true }).positive({
302
+ message: "Max amount must be a positive number"
303
+ }).optional().meta({
304
+ description: "Maximum amount of assets in the offer",
305
+ example: "10000"
306
+ }),
307
+ // Rate range
308
+ min_rate: z.bigint({ coerce: true }).positive({
309
+ message: "Min rate must be a positive number"
310
+ }).optional().meta({
311
+ description: "Minimum rate per asset (in wei)",
312
+ example: "500000000000000000"
313
+ }),
314
+ max_rate: z.bigint({ coerce: true }).positive({
315
+ message: "Max rate must be a positive number"
316
+ }).optional().meta({
317
+ description: "Maximum rate per asset (in wei)",
318
+ example: "1500000000000000000"
319
+ }),
320
+ // Time range
321
+ min_maturity: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
322
+ description: "Minimum maturity timestamp (Unix timestamp in seconds)",
323
+ example: "1700000000"
324
+ }),
325
+ max_maturity: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
326
+ description: "Maximum maturity timestamp (Unix timestamp in seconds)",
327
+ example: "1800000000"
328
+ }),
329
+ min_expiry: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
330
+ description: "Minimum expiry timestamp (Unix timestamp in seconds)",
331
+ example: "1700000000"
332
+ }),
333
+ max_expiry: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
334
+ description: "Maximum expiry timestamp (Unix timestamp in seconds)",
335
+ example: "1800000000"
336
+ }),
337
+ // Collateral filtering
338
+ collateral_assets: z.string().regex(/^0x[a-fA-F0-9]{40}(,0x[a-fA-F0-9]{40})*$/, {
339
+ message: "Collateral assets must be comma-separated Ethereum addresses"
340
+ }).transform((val) => val.split(",").map((addr) => addr.toLowerCase())).optional().meta({
341
+ description: "Filter by multiple collateral assets (comma-separated)",
342
+ example: "0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
343
+ }),
344
+ collateral_oracles: z.string().regex(/^0x[a-fA-F0-9]{40}(,0x[a-fA-F0-9]{40})*$/, {
345
+ message: "Collateral oracles must be comma-separated Ethereum addresses"
346
+ }).transform((val) => val.split(",").map((addr) => addr.toLowerCase())).optional().meta({
347
+ description: "Filter by multiple rate oracles (comma-separated)",
348
+ example: "0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd"
349
+ }),
350
+ collateral_tuple: z.string().regex(
351
+ /^(0x[a-fA-F0-9]{40}(:0x[a-fA-F0-9]{40})?(:[0-9]+(\.[0-9]+)?)?)(#0x[a-fA-F0-9]{40}(:0x[a-fA-F0-9]{40})?(:[0-9]+(\.[0-9]+)?)?)*$/,
352
+ {
353
+ message: "Collateral tuple must be in format: asset:oracle:lltv#asset2:oracle2:lltv2. Oracle and lltv are optional. Asset must be 0x + 40 hex chars, oracle must be 0x + 40 hex chars, lltv must be a number (e.g., 80.5)."
354
+ }
355
+ ).transform((val) => {
356
+ return val.split("#").map((tuple) => {
357
+ const parts = tuple.split(":");
358
+ if (parts.length === 0 || !parts[0]) {
359
+ throw new z.ZodError([
360
+ {
361
+ code: "custom",
362
+ message: "Asset address is required for each collateral tuple",
363
+ path: ["collateral_tuple"],
364
+ input: val
365
+ }
366
+ ]);
367
+ }
368
+ const asset = parts[0]?.toLowerCase();
369
+ const oracle = parts[1]?.toLowerCase();
370
+ const lltv = parts[2] ? parseFloat(parts[2]) : void 0;
371
+ if (lltv !== void 0 && (lltv < MIN_LLTV || lltv > MAX_LLTV)) {
372
+ throw new z.ZodError([
373
+ {
374
+ code: "custom",
375
+ message: `LLTV must be between ${MIN_LLTV} and ${MAX_LLTV} (0-100%)`,
376
+ path: ["collateral_tuple"],
377
+ input: val
378
+ }
379
+ ]);
380
+ }
381
+ return {
382
+ asset,
383
+ oracle,
384
+ lltv
385
+ };
386
+ });
387
+ }).optional().meta({
388
+ description: "Filter by collateral combinations in format: asset:oracle:lltv#asset2:oracle2:lltv2. Oracle and lltv are optional. Use # to separate multiple combinations.",
389
+ example: "0x1234567890123456789012345678901234567890:0xabcdefabcdefabcdefabcdefabcdefabcdefabcd:8000#0x9876543210987654321098765432109876543210::8000"
390
+ }),
391
+ min_lltv: z.string().regex(/^\d+(\.\d+)?$/, {
392
+ message: "Min LLTV must be a valid number"
393
+ }).transform((val) => parseFloat(val)).pipe(z.number().min(0).max(100)).optional().meta({
394
+ description: "Minimum Loan-to-Value ratio (LLTV) for collateral (percentage as decimal, e.g., 80.5 = 80.5%)",
395
+ example: "80.5"
396
+ }),
397
+ max_lltv: z.string().regex(/^\d+(\.\d+)?$/, {
398
+ message: "Max LLTV must be a valid number"
399
+ }).transform((val) => parseFloat(val)).pipe(z.number().min(0).max(100)).optional().meta({
400
+ description: "Maximum Loan-to-Value ratio (LLTV) for collateral (percentage as decimal, e.g., 95.5 = 95.5%)",
401
+ example: "95.5"
402
+ }),
403
+ // Sorting parameters
404
+ sort_by: z.enum(["rate", "maturity", "expiry", "amount"]).optional().meta({
405
+ description: "Field to sort results by",
406
+ example: "rate"
407
+ }),
408
+ sort_order: z.enum(["asc", "desc"]).optional().default("desc").meta({
409
+ description: "Sort direction: asc (ascending) or desc (descending, default)",
410
+ example: "desc"
411
+ }),
412
+ // Pagination
413
+ cursor: z.string().optional().refine(
414
+ (val) => {
415
+ if (!val) return true;
416
+ try {
417
+ const decoded = decodeCursor(val);
418
+ return decoded !== null;
419
+ } catch (_error) {
420
+ return false;
421
+ }
422
+ },
423
+ {
424
+ message: "Invalid cursor format. Must be a valid base64url-encoded cursor object"
425
+ }
426
+ ).meta({
427
+ description: "Pagination cursor in base64url-encoded format",
428
+ example: "eyJzb3J0IjoicHJpY2UiLCJkaXIiOiJkZXNjIiwicHJpY2UiOiIxMDAwMDAwMDAwMDAwMDAwMDAwIiwiaGFzaCI6IjB4ZGRmZDY4NTllM2UwODJkMTkzODlhMWFlYzFiZGFkN2U4ZDkyZDk2YjFhYTc5NDBkYTkxYTMxMjVkMzFlM2JlNWIifQ"
429
+ }),
430
+ limit: z.string().regex(/^[1-9]\d*$/, {
431
+ message: "Limit must be a positive integer"
432
+ }).transform((val) => Number.parseInt(val, 10)).pipe(
433
+ z.number().max(MAX_LIMIT, {
434
+ message: `Limit cannot exceed ${MAX_LIMIT}`
435
+ })
436
+ ).optional().default(DEFAULT_LIMIT).meta({
437
+ description: `Limit maximum: ${MAX_LIMIT}. Default: ${DEFAULT_LIMIT}`,
438
+ example: 10
439
+ })
440
+ }).refine(
441
+ (data) => data.min_maturity === void 0 || data.max_maturity === void 0 || data.max_maturity >= data.min_maturity,
442
+ {
443
+ message: "max_maturity must be greater than or equal to min_maturity",
444
+ path: ["max_maturity"]
445
+ }
446
+ ).refine(
447
+ (data) => data.min_expiry === void 0 || data.max_expiry === void 0 || data.max_expiry >= data.min_expiry,
448
+ {
449
+ message: "max_expiry must be greater than or equal to min_expiry",
450
+ path: ["max_expiry"]
451
+ }
452
+ ).refine(
453
+ (data) => data.min_amount === void 0 || data.max_amount === void 0 || data.max_amount >= data.min_amount,
454
+ {
455
+ message: "max_amount must be greater than or equal to min_amount",
456
+ path: ["max_amount"]
457
+ }
458
+ ).refine(
459
+ (data) => data.min_rate === void 0 || data.max_rate === void 0 || data.max_rate >= data.min_rate,
460
+ {
461
+ message: "max_rate must be greater than or equal to min_rate",
462
+ path: ["max_rate"]
463
+ }
464
+ ).refine(
465
+ (data) => data.min_lltv === void 0 || data.max_lltv === void 0 || data.max_lltv >= data.min_lltv,
466
+ {
467
+ message: "max_lltv must be greater than or equal to min_lltv",
468
+ path: ["max_lltv"]
469
+ }
470
+ );
471
+ var MatchOffersQueryParams = z.object({
472
+ // Required parameters
473
+ side: z.enum(["buy", "sell"]).meta({
474
+ description: "The desired side of the match: 'buy' if you want to buy, 'sell' if you want to sell. If your intent is to sell, buy offers will be returned, and vice versa.",
475
+ example: "buy"
476
+ }),
477
+ chain_id: z.string().regex(/^\d+$/, {
478
+ message: "Chain ID must be a positive integer"
479
+ }).transform((val) => Number.parseInt(val, 10)).pipe(z.number().positive()).meta({
480
+ description: "The blockchain network chain ID",
481
+ example: "1"
482
+ }),
483
+ // Optional parameters
484
+ rate: z.bigint({ coerce: true }).positive({
485
+ message: "Rate must be a positive number"
486
+ }).optional().meta({
487
+ description: "Rate per asset (in wei) for matching offers",
488
+ example: "1000000000000000000"
489
+ }),
490
+ // Collateral filtering
491
+ collaterals: z.string().regex(
492
+ /^(0x[a-fA-F0-9]{40}:0x[a-fA-F0-9]{40}:\d+)(#0x[a-fA-F0-9]{40}:0x[a-fA-F0-9]{40}:\d+)*$/,
493
+ {
494
+ message: "Collaterals must be in format: asset:oracle:lltv#asset2:oracle2:lltv2. All fields are required for each collateral."
495
+ }
496
+ ).transform((val) => {
497
+ return val.split("#").map((collateral) => {
498
+ const parts = collateral.split(":");
499
+ if (parts.length !== 3) {
500
+ throw new z.ZodError([
501
+ {
502
+ code: "custom",
503
+ message: "Each collateral must have exactly 3 parts: asset:oracle:lltv",
504
+ path: ["collaterals"],
505
+ input: val
506
+ }
507
+ ]);
508
+ }
509
+ const [asset, oracle, lltvStr] = parts;
510
+ if (!asset || !oracle || !lltvStr) {
511
+ throw new z.ZodError([
512
+ {
513
+ code: "custom",
514
+ message: "Asset, oracle, and lltv are all required for each collateral",
515
+ path: ["collaterals"],
516
+ input: val
517
+ }
518
+ ]);
519
+ }
520
+ const lltv = BigInt(lltvStr);
521
+ if (lltv <= 0n) {
522
+ throw new z.ZodError([
523
+ {
524
+ code: "custom",
525
+ message: "LLTV must be a positive number",
526
+ path: ["collaterals"],
527
+ input: val
528
+ }
529
+ ]);
530
+ }
531
+ return {
532
+ asset: asset.toLowerCase(),
533
+ oracle: oracle.toLowerCase(),
534
+ lltv
535
+ };
536
+ });
537
+ }).optional().meta({
538
+ description: "Collateral requirements in format: asset:oracle:lltv#asset2:oracle2:lltv2. Use # to separate multiple collaterals.",
539
+ example: "0x1234567890123456789012345678901234567890:0xabcdefabcdefabcdefabcdefabcdefabcdefabcd:800000000000000000#0x9876543210987654321098765432109876543210:0xfedcbafedcbafedcbafedcbafedcbafedcbafedc:900000000000000000"
540
+ }),
541
+ // Maturity filtering
542
+ maturity: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
543
+ description: "Exact maturity timestamp (Unix timestamp in seconds)",
544
+ example: "1700000000"
545
+ }),
546
+ min_maturity: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
547
+ description: "Minimum maturity timestamp (Unix timestamp in seconds, inclusive)",
548
+ example: "1700000000"
549
+ }),
550
+ max_maturity: z.bigint({ coerce: true }).min(0n).optional().transform((val) => val === void 0 ? void 0 : Number(val)).meta({
551
+ description: "Maximum maturity timestamp (Unix timestamp in seconds, inclusive)",
552
+ example: "1800000000"
553
+ }),
554
+ // Asset and creator filtering
555
+ loan_token: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {
556
+ message: "Loan asset must be a valid Ethereum address"
557
+ }).transform((val) => val.toLowerCase()).optional().meta({
558
+ description: "The loan asset address to match against",
559
+ example: "0x1234567890123456789012345678901234567890"
560
+ }),
561
+ creator: z.string().regex(/^0x[a-fA-F0-9]{40}$/, {
562
+ message: "Creator must be a valid Ethereum address"
563
+ }).transform((val) => val.toLowerCase()).optional().meta({
564
+ description: "Filter by a specific offer creator address",
565
+ example: "0x1234567890123456789012345678901234567890"
566
+ }),
567
+ // Status filtering
568
+ status: z.string().regex(/^[a-zA-Z_]+(,[a-zA-Z_]+)*$/, {
569
+ message: "Status must be comma-separated status values"
570
+ }).transform((val) => val.split(",")).refine((statuses) => statuses.every((status) => OfferStatusValues.includes(status)), {
571
+ message: `Invalid status value. Must be one of: ${OfferStatusValues.join(", ")}`
572
+ }).optional().meta({
573
+ description: `Filter by multiple statuses (comma-separated). Valid values: ${OfferStatusValues.join(", ")}. By default, only offers with 'valid' status are returned.`,
574
+ example: "valid,callback_error"
575
+ }),
576
+ // Pagination
577
+ cursor: z.string().optional().refine(
578
+ (val) => {
579
+ if (!val) return true;
580
+ try {
581
+ const decoded = decodeCursor(val);
582
+ return decoded !== null;
583
+ } catch (_error) {
584
+ return false;
585
+ }
586
+ },
587
+ {
588
+ message: "Invalid cursor format. Must be a valid base64url-encoded cursor object"
589
+ }
590
+ ).meta({
591
+ description: "Pagination cursor in base64url-encoded format",
592
+ example: "eyJzb3J0IjoicHJpY2UiLCJkaXIiOiJkZXNjIiwicHJpY2UiOiIxMDAwMDAwMDAwMDAwMDAwMDAwIiwiaGFzaCI6IjB4ZGRmZDY4NTllM2UwODJkMTkzODlhMWFlYzFiZGFkN2U4ZDkyZDk2YjFhYTc5NDBkYTkxYTMxMjVkMzFlM2JlNWIifQ"
593
+ }),
594
+ limit: z.string().regex(/^[1-9]\d*$/, {
595
+ message: "Limit must be a positive integer"
596
+ }).transform((val) => Number.parseInt(val, 10)).pipe(
597
+ z.number().max(MAX_LIMIT, {
598
+ message: `Limit cannot exceed ${MAX_LIMIT}`
599
+ })
600
+ ).optional().default(DEFAULT_LIMIT).meta({
601
+ description: `Limit maximum: ${MAX_LIMIT}. Default: ${DEFAULT_LIMIT}`,
602
+ example: 10
603
+ })
604
+ }).refine(
605
+ (data) => data.min_maturity === void 0 || data.max_maturity === void 0 || data.max_maturity >= data.min_maturity,
606
+ {
607
+ message: "max_maturity must be greater than or equal to min_maturity",
608
+ path: ["max_maturity"]
609
+ }
610
+ );
611
+ var schemas = {
612
+ get_offers: GetOffersQueryParams,
613
+ match_offers: MatchOffersQueryParams
614
+ };
615
+ function safeParse(action, query) {
616
+ return schemas[action].safeParse(query);
617
+ }
618
+
619
+ // src/core/apiSchema/openapi.ts
620
+ var successResponseSchema = z.object({
621
+ status: z.literal("success"),
622
+ cursor: z.string().nullable(),
623
+ data: z.array(z.any()),
624
+ meta: z.object({
625
+ timestamp: z.string()
626
+ })
627
+ });
628
+ var errorResponseSchema = z.object({
629
+ status: z.literal("error"),
630
+ error: z.object({
631
+ code: z.string(),
632
+ message: z.string(),
633
+ details: z.any().optional()
634
+ }),
635
+ meta: z.object({
636
+ timestamp: z.string()
637
+ })
638
+ });
639
+ var paths = {
640
+ "/v1/offers": {
641
+ get: {
642
+ summary: "Get offers",
643
+ description: "Get all offers with optional filtering and pagination",
644
+ tags: ["Offers"],
645
+ requestParams: {
646
+ query: GetOffersQueryParams
647
+ },
648
+ responses: {
649
+ 200: {
650
+ description: "Success",
651
+ content: {
652
+ "application/json": {
653
+ schema: successResponseSchema
654
+ }
655
+ }
656
+ },
657
+ 400: {
658
+ description: "Bad Request",
659
+ content: {
660
+ "application/json": {
661
+ schema: errorResponseSchema
662
+ }
663
+ }
664
+ }
665
+ }
666
+ }
667
+ },
668
+ "/v1/match-offers": {
669
+ get: {
670
+ summary: "Match offers",
671
+ description: "Find offers that match specific criteria",
672
+ tags: ["Offers"],
673
+ requestParams: {
674
+ query: MatchOffersQueryParams
675
+ },
676
+ responses: {
677
+ 200: {
678
+ description: "Success",
679
+ content: {
680
+ "application/json": {
681
+ schema: successResponseSchema
682
+ }
683
+ }
684
+ },
685
+ 400: {
686
+ description: "Bad Request",
687
+ content: {
688
+ "application/json": {
689
+ schema: errorResponseSchema
690
+ }
691
+ }
692
+ }
693
+ }
694
+ }
695
+ }
696
+ };
697
+ createDocument({
698
+ openapi: "3.1.0",
699
+ info: {
700
+ title: "Router API",
701
+ version: "1.0.0",
702
+ description: "API for the Morpho Router"
703
+ },
704
+ tags: [
705
+ {
706
+ name: "Offers"
707
+ }
708
+ ],
709
+ servers: [
710
+ {
711
+ url: "https://router.morpho.dev",
712
+ description: "Production server"
713
+ },
714
+ {
715
+ url: "http://localhost:8081",
716
+ description: "Local development server"
717
+ }
718
+ ],
719
+ paths
720
+ });
721
+
722
+ // src/core/Client.ts
81
723
  function connect(opts) {
82
724
  const u = new URL(opts?.url || "https://router.morpho.dev");
83
725
  if (u.protocol !== "http:" && u.protocol !== "https:") {
@@ -180,14 +822,7 @@ async function get(config, parameters) {
180
822
  const { cursor: returnedCursor, data: offers } = await getApi(config, url);
181
823
  return {
182
824
  cursor: returnedCursor,
183
- offers: offers.map((offer) => {
184
- const baseOffer = Offer.fromSnakeCase(offer);
185
- return {
186
- ...baseOffer,
187
- status: offer.status,
188
- metadata: offer.metadata
189
- };
190
- })
825
+ offers: offers.map(fromSnakeCase)
191
826
  };
192
827
  }
193
828
  async function match(config, parameters) {
@@ -228,24 +863,29 @@ async function match(config, parameters) {
228
863
  const { cursor: returnedCursor, data: offers } = await getApi(config, url);
229
864
  return {
230
865
  cursor: returnedCursor,
231
- offers: offers.map((offer) => {
232
- const baseOffer = Offer.fromSnakeCase(offer);
233
- return {
234
- ...baseOffer,
235
- status: offer.status,
236
- metadata: offer.metadata
237
- };
238
- })
866
+ offers: offers.map(fromSnakeCase)
239
867
  };
240
868
  }
241
869
  async function getApi(config, url) {
242
- if (url.searchParams.get("limit") && Number(url.searchParams.get("limit")) > MAX_BATCH_SIZE) {
243
- throw new HttpGetOffersFailedError(
244
- `The maximum number of offers that can be returned is ${MAX_BATCH_SIZE}.`,
245
- {
246
- details: `The limit is set to ${url.searchParams.get("limit")}. Maximum is ${MAX_BATCH_SIZE}.`
247
- }
248
- );
870
+ const pathname = url.pathname;
871
+ let action;
872
+ switch (true) {
873
+ case pathname.includes("/v1/offers"):
874
+ action = "get_offers";
875
+ break;
876
+ case pathname.includes("/v1/match-offers"):
877
+ action = "match_offers";
878
+ break;
879
+ default:
880
+ throw new HttpGetOffersFailedError("Unknown endpoint", {
881
+ details: `Unsupported path: ${pathname}`
882
+ });
883
+ }
884
+ const schemaParseResult = safeParse(action, Object.fromEntries(url.searchParams));
885
+ if (!schemaParseResult.success) {
886
+ throw new HttpGetOffersFailedError(`Invalid URL parameters`, {
887
+ details: schemaParseResult.error.issues[0]?.message
888
+ });
249
889
  }
250
890
  const response = await fetch(url.toString(), {
251
891
  method: "GET",
@@ -328,48 +968,6 @@ function buildId(event) {
328
968
  }
329
969
  }
330
970
 
331
- // src/RouterOffer.ts
332
- var RouterOffer_exports = {};
333
- __export(RouterOffer_exports, {
334
- OfferStatusValues: () => OfferStatusValues
335
- });
336
- var OfferStatusValues = [
337
- "valid",
338
- "callback_not_supported",
339
- "callback_error",
340
- "unverified"
341
- ];
342
-
343
- // src/utils/batch.ts
344
- function* batch(array, batchSize) {
345
- for (let i = 0; i < array.length; i += batchSize) {
346
- yield array.slice(i, i + batchSize);
347
- }
348
- }
349
-
350
- // src/utils/wait.ts
351
- async function wait(time) {
352
- return new Promise((res) => setTimeout(res, time));
353
- }
354
-
355
- // src/utils/poll.ts
356
- function poll(fn, { interval }) {
357
- let active = true;
358
- const unwatch = () => active = false;
359
- const watch = async () => {
360
- await wait(interval);
361
- const poll2 = async () => {
362
- if (!active) return;
363
- await fn({ unpoll: unwatch });
364
- await wait(interval);
365
- poll2();
366
- };
367
- poll2();
368
- };
369
- watch();
370
- return unwatch;
371
- }
372
-
373
971
  // src/Validation.ts
374
972
  var Validation_exports = {};
375
973
  __export(Validation_exports, {
@@ -583,6 +1181,6 @@ function morpho(parameters) {
583
1181
  ];
584
1182
  }
585
1183
 
586
- export { Chain_exports as Chain, core_exports as Router, RouterEvent_exports as RouterEvent, RouterOffer_exports as RouterOffer, Validation_exports as Validation, ValidationRule_exports as ValidationRule, batch, poll, wait };
1184
+ export { Chain_exports as Chain, Client_exports as Router, RouterEvent_exports as RouterEvent, RouterOffer_exports as RouterOffer, Validation_exports as Validation, ValidationRule_exports as ValidationRule, batch, decodeCursor, encodeCursor, poll, validateCursor, wait };
587
1185
  //# sourceMappingURL=index.browser.mjs.map
588
1186
  //# sourceMappingURL=index.browser.mjs.map