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