@morpho-dev/router 0.0.12 → 0.0.13

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