@morpho-dev/router 0.0.11 → 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.
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/meta/0000_snapshot.json +344 -0
  11. package/dist/drizzle/meta/0001_snapshot.json +426 -0
  12. package/dist/drizzle/meta/0002_snapshot.json +439 -0
  13. package/dist/drizzle/meta/0003_snapshot.json +553 -0
  14. package/dist/drizzle/meta/0004_snapshot.json +559 -0
  15. package/dist/drizzle/meta/0005_snapshot.json +559 -0
  16. package/dist/drizzle/meta/0006_snapshot.json +559 -0
  17. package/dist/drizzle/meta/0007_snapshot.json +559 -0
  18. package/dist/drizzle/meta/_journal.json +62 -0
  19. package/dist/{index.d.cts → index.browser.d.cts} +34 -90
  20. package/dist/{index.d.ts → index.browser.d.ts} +34 -90
  21. package/dist/index.browser.js +1172 -0
  22. package/dist/index.browser.js.map +1 -0
  23. package/dist/index.browser.mjs +1154 -0
  24. package/dist/index.browser.mjs.map +1 -0
  25. package/dist/index.node.d.cts +1342 -0
  26. package/dist/index.node.d.ts +1342 -0
  27. package/dist/{index.js → index.node.js} +2119 -4773
  28. package/dist/index.node.js.map +1 -0
  29. package/dist/{index.mjs → index.node.mjs} +2111 -4774
  30. package/dist/index.node.mjs.map +1 -0
  31. package/package.json +33 -11
  32. package/dist/index.js.map +0 -1
  33. package/dist/index.mjs.map +0 -1
@@ -0,0 +1,1154 @@
1
+ import { Errors, Offer } from '@morpho-dev/mempool';
2
+ export * from '@morpho-dev/mempool';
3
+ import { base, mainnet } from 'viem/chains';
4
+ import { z } from 'zod/v4';
5
+ import { createDocument } from 'zod-openapi';
6
+ import { parseAbi } from 'viem';
7
+
8
+ var __defProp = Object.defineProperty;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __publicField = (obj, key, value) => __defNormalProp(obj, key + "" , value);
15
+
16
+ // src/Chain.ts
17
+ var Chain_exports = {};
18
+ __export(Chain_exports, {
19
+ ChainId: () => ChainId,
20
+ chainIds: () => chainIds,
21
+ chainNames: () => chainNames,
22
+ chains: () => chains,
23
+ getChain: () => getChain
24
+ });
25
+ var chainNames = ["ethereum", "base"];
26
+ var ChainId = {
27
+ ETHEREUM: BigInt(mainnet.id),
28
+ BASE: BigInt(base.id)
29
+ };
30
+ var chainIds = new Set(Object.values(ChainId));
31
+ var chainNameLookup = new Map(Object.entries(ChainId).map(([key, value]) => [value, key]));
32
+ function getChain(chainId) {
33
+ const chainName = chainNameLookup.get(chainId)?.toLowerCase();
34
+ if (!chainName) {
35
+ return void 0;
36
+ }
37
+ return chains[chainName];
38
+ }
39
+ var chains = {
40
+ ethereum: {
41
+ ...mainnet,
42
+ id: ChainId.ETHEREUM,
43
+ name: "ethereum",
44
+ whitelistedAssets: new Set(
45
+ [
46
+ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
47
+ // USDC
48
+ "0x6B175474E89094C44Da98b954EedeAC495271d0F"
49
+ // DAI
50
+ ].map((address) => address.toLowerCase())
51
+ ),
52
+ morpho: "0x0000000000000000000000000000000000000000"
53
+ },
54
+ base: {
55
+ ...base,
56
+ id: ChainId.BASE,
57
+ name: "base",
58
+ whitelistedAssets: new Set(
59
+ [
60
+ "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
61
+ // USDC
62
+ "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"
63
+ // DAI
64
+ ].map((address) => address.toLowerCase())
65
+ ),
66
+ morpho: "0x0000000000000000000000000000000000000000"
67
+ }
68
+ };
69
+
70
+ // src/core/Client.ts
71
+ var Client_exports = {};
72
+ __export(Client_exports, {
73
+ HttpForbiddenError: () => HttpForbiddenError,
74
+ HttpGetOffersFailedError: () => HttpGetOffersFailedError,
75
+ HttpRateLimitError: () => HttpRateLimitError,
76
+ HttpUnauthorizedError: () => HttpUnauthorizedError,
77
+ InvalidUrlError: () => InvalidUrlError,
78
+ connect: () => connect,
79
+ get: () => get,
80
+ match: () => match
81
+ });
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
677
+ function connect(opts) {
678
+ const u = new URL(opts?.url || "https://router.morpho.dev");
679
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
680
+ throw new InvalidUrlError(u.toString());
681
+ }
682
+ const headers = new Headers();
683
+ headers.set("Content-Type", "application/json");
684
+ opts?.apiKey !== void 0 ? headers.set("X-API-Key", opts.apiKey) : null;
685
+ const config = {
686
+ url: u,
687
+ headers
688
+ };
689
+ return {
690
+ ...config,
691
+ get: (parameters) => get(config, parameters),
692
+ match: (parameters) => match(config, parameters)
693
+ };
694
+ }
695
+ async function get(config, parameters) {
696
+ const url = new URL(`${config.url.toString()}v1/offers`);
697
+ if (parameters.creators?.length) {
698
+ url.searchParams.set("creators", parameters.creators.join(","));
699
+ }
700
+ if (parameters.side) {
701
+ url.searchParams.set("side", parameters.side);
702
+ }
703
+ if (parameters.chains?.length) {
704
+ url.searchParams.set("chains", parameters.chains.join(","));
705
+ }
706
+ if (parameters.loanTokens?.length) {
707
+ url.searchParams.set("loan_tokens", parameters.loanTokens.join(","));
708
+ }
709
+ if (parameters.status?.length) {
710
+ url.searchParams.set("status", parameters.status.join(","));
711
+ }
712
+ if (parameters.callbackAddresses?.length) {
713
+ url.searchParams.set("callback_addresses", parameters.callbackAddresses.join(","));
714
+ }
715
+ if (parameters.minAmount !== void 0) {
716
+ url.searchParams.set("min_amount", parameters.minAmount.toString());
717
+ }
718
+ if (parameters.maxAmount !== void 0) {
719
+ url.searchParams.set("max_amount", parameters.maxAmount.toString());
720
+ }
721
+ if (parameters.minRate !== void 0) {
722
+ url.searchParams.set("min_rate", parameters.minRate.toString());
723
+ }
724
+ if (parameters.maxRate !== void 0) {
725
+ url.searchParams.set("max_rate", parameters.maxRate.toString());
726
+ }
727
+ if (parameters.minMaturity !== void 0) {
728
+ url.searchParams.set("min_maturity", parameters.minMaturity.toString());
729
+ }
730
+ if (parameters.maxMaturity !== void 0) {
731
+ url.searchParams.set("max_maturity", parameters.maxMaturity.toString());
732
+ }
733
+ if (parameters.minExpiry !== void 0) {
734
+ url.searchParams.set("min_expiry", parameters.minExpiry.toString());
735
+ }
736
+ if (parameters.maxExpiry !== void 0) {
737
+ url.searchParams.set("max_expiry", parameters.maxExpiry.toString());
738
+ }
739
+ if (parameters.collateralAssets?.length) {
740
+ url.searchParams.set("collateral_assets", parameters.collateralAssets.join(","));
741
+ }
742
+ if (parameters.collateralOracles?.length) {
743
+ url.searchParams.set("collateral_oracles", parameters.collateralOracles.join(","));
744
+ }
745
+ if (parameters.collateralTuple?.length) {
746
+ const tupleStr = parameters.collateralTuple.map(({ asset, oracle, lltv }) => {
747
+ let result = asset;
748
+ if (oracle) {
749
+ result += `:${oracle}`;
750
+ } else if (lltv !== void 0) {
751
+ result += `:`;
752
+ }
753
+ if (lltv !== void 0) result += `:${lltv}`;
754
+ return result;
755
+ }).join("#");
756
+ url.searchParams.set("collateral_tuple", tupleStr);
757
+ }
758
+ if (parameters.minLltv !== void 0) {
759
+ url.searchParams.set("min_lltv", parameters.minLltv.toString());
760
+ }
761
+ if (parameters.maxLltv !== void 0) {
762
+ url.searchParams.set("max_lltv", parameters.maxLltv.toString());
763
+ }
764
+ if (parameters.sortBy) {
765
+ url.searchParams.set("sort_by", parameters.sortBy);
766
+ }
767
+ if (parameters.sortOrder) {
768
+ url.searchParams.set("sort_order", parameters.sortOrder);
769
+ }
770
+ if (parameters.cursor) {
771
+ url.searchParams.set("cursor", parameters.cursor);
772
+ }
773
+ if (parameters.limit !== void 0) {
774
+ url.searchParams.set("limit", parameters.limit.toString());
775
+ }
776
+ const { cursor: returnedCursor, data: offers } = await getApi(config, url);
777
+ return {
778
+ cursor: returnedCursor,
779
+ offers: offers.map((offer) => {
780
+ const baseOffer = Offer.fromSnakeCase(offer);
781
+ return {
782
+ ...baseOffer,
783
+ status: offer.status,
784
+ metadata: offer.metadata
785
+ };
786
+ })
787
+ };
788
+ }
789
+ async function match(config, parameters) {
790
+ const url = new URL(`${config.url.toString()}v1/match-offers`);
791
+ url.searchParams.set("side", parameters.side);
792
+ url.searchParams.set("chain_id", parameters.chainId.toString());
793
+ if (parameters.rate !== void 0) {
794
+ url.searchParams.set("rate", parameters.rate.toString());
795
+ }
796
+ if (parameters.collaterals?.length) {
797
+ const collateralsStr = parameters.collaterals.map(({ asset, oracle, lltv }) => `${asset}:${oracle}:${lltv}`).join("#");
798
+ url.searchParams.set("collaterals", collateralsStr);
799
+ }
800
+ if (parameters.maturity !== void 0) {
801
+ url.searchParams.set("maturity", parameters.maturity.toString());
802
+ }
803
+ if (parameters.minMaturity !== void 0) {
804
+ url.searchParams.set("min_maturity", parameters.minMaturity.toString());
805
+ }
806
+ if (parameters.maxMaturity !== void 0) {
807
+ url.searchParams.set("max_maturity", parameters.maxMaturity.toString());
808
+ }
809
+ if (parameters.loanToken) {
810
+ url.searchParams.set("loan_token", parameters.loanToken);
811
+ }
812
+ if (parameters.creator) {
813
+ url.searchParams.set("creator", parameters.creator);
814
+ }
815
+ if (parameters.status?.length) {
816
+ url.searchParams.set("status", parameters.status.join(","));
817
+ }
818
+ if (parameters.cursor) {
819
+ url.searchParams.set("cursor", parameters.cursor);
820
+ }
821
+ if (parameters.limit !== void 0) {
822
+ url.searchParams.set("limit", parameters.limit.toString());
823
+ }
824
+ const { cursor: returnedCursor, data: offers } = await getApi(config, url);
825
+ return {
826
+ cursor: returnedCursor,
827
+ offers: offers.map((offer) => {
828
+ const baseOffer = Offer.fromSnakeCase(offer);
829
+ return {
830
+ ...baseOffer,
831
+ status: offer.status,
832
+ metadata: offer.metadata
833
+ };
834
+ })
835
+ };
836
+ }
837
+ async function getApi(config, url) {
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
+ });
857
+ }
858
+ const response = await fetch(url.toString(), {
859
+ method: "GET",
860
+ headers: config.headers
861
+ });
862
+ if (!response.ok) {
863
+ switch (response.status) {
864
+ case 401:
865
+ throw new HttpUnauthorizedError();
866
+ case 403:
867
+ throw new HttpForbiddenError();
868
+ case 429:
869
+ throw new HttpRateLimitError();
870
+ }
871
+ throw new HttpGetOffersFailedError(`GET request returned ${response.status}`, {
872
+ details: await response.text()
873
+ });
874
+ }
875
+ return response.json();
876
+ }
877
+ var InvalidUrlError = class extends Errors.BaseError {
878
+ constructor(url) {
879
+ super(`URL "${url}" is not http/https.`);
880
+ __publicField(this, "name", "Router.InvalidUrlError");
881
+ }
882
+ };
883
+ var HttpUnauthorizedError = class extends Errors.BaseError {
884
+ constructor() {
885
+ super("Unauthorized.", {
886
+ metaMessages: ["Ensure that an API key is provided."]
887
+ });
888
+ __publicField(this, "name", "Router.HttpUnauthorizedError");
889
+ }
890
+ };
891
+ var HttpForbiddenError = class extends Errors.BaseError {
892
+ constructor() {
893
+ super("Forbidden.", {
894
+ metaMessages: ["Ensure that the API key is valid."]
895
+ });
896
+ __publicField(this, "name", "Router.HttpForbiddenError");
897
+ }
898
+ };
899
+ var HttpRateLimitError = class extends Errors.BaseError {
900
+ constructor() {
901
+ super("Rate limit exceeded.", {
902
+ metaMessages: [
903
+ "The number of allowed requests has been exceeded. You must wait for the rate limit to reset."
904
+ ]
905
+ });
906
+ __publicField(this, "name", "Router.HttpRateLimitError");
907
+ }
908
+ };
909
+ var HttpGetOffersFailedError = class extends Errors.BaseError {
910
+ constructor(message, { details } = {}) {
911
+ super(message, {
912
+ metaMessages: [details]
913
+ });
914
+ __publicField(this, "name", "Router.HttpGetOffersFailedError");
915
+ }
916
+ };
917
+
918
+ // src/RouterEvent.ts
919
+ var RouterEvent_exports = {};
920
+ __export(RouterEvent_exports, {
921
+ buildId: () => buildId,
922
+ types: () => types
923
+ });
924
+ var types = ["offer_created", "offer_matched", "offer_validation"];
925
+ function buildId(event) {
926
+ switch (event.type) {
927
+ case "offer_created":
928
+ return `offer_created:${event.offer.hash.toLowerCase()}`;
929
+ case "offer_matched":
930
+ return `offer_matched:${event.offer.hash.toLowerCase()}`;
931
+ case "offer_validation":
932
+ return `offer_validation:${event.offer.hash.toLowerCase()}`;
933
+ default: {
934
+ throw new Error("Unhandled event type");
935
+ }
936
+ }
937
+ }
938
+
939
+ // src/Validation.ts
940
+ var Validation_exports = {};
941
+ __export(Validation_exports, {
942
+ run: () => run
943
+ });
944
+ async function run(parameters) {
945
+ const { items, rules, ctx = {}, chunkSize } = parameters;
946
+ const issues = [];
947
+ let validItems = items.slice();
948
+ for (const rule of rules) {
949
+ if (validItems.length === 0) return { valid: [], issues };
950
+ const indicesToRemove = /* @__PURE__ */ new Set();
951
+ if (rule.kind === "single") {
952
+ for (let i = 0; i < validItems.length; i++) {
953
+ const item = validItems[i];
954
+ const issue = await rule.run(item, ctx);
955
+ if (issue) {
956
+ issues.push({ ...issue, ruleName: rule.name, item });
957
+ indicesToRemove.add(i);
958
+ }
959
+ }
960
+ } else if (rule.kind === "batch") {
961
+ const exec = async (slice, offset) => {
962
+ const map = await rule.run(slice, ctx);
963
+ for (let i = 0; i < slice.length; i++) {
964
+ const issue = map.get(i);
965
+ if (issue !== void 0) {
966
+ issues.push({ ...issue, ruleName: rule.name, item: slice[i] });
967
+ indicesToRemove.add(offset + i);
968
+ }
969
+ }
970
+ };
971
+ if (!chunkSize) await exec(validItems, 0);
972
+ else {
973
+ for (let i = 0; i < validItems.length; i += chunkSize) {
974
+ await exec(validItems.slice(i, i + chunkSize), i);
975
+ }
976
+ }
977
+ }
978
+ validItems = validItems.filter((_, i) => !indicesToRemove.has(i));
979
+ }
980
+ return {
981
+ valid: validItems,
982
+ issues
983
+ };
984
+ }
985
+
986
+ // src/ValidationRule.ts
987
+ var ValidationRule_exports = {};
988
+ __export(ValidationRule_exports, {
989
+ batch: () => batch2,
990
+ morpho: () => morpho,
991
+ single: () => single
992
+ });
993
+ function single(name, run2) {
994
+ return { kind: "single", name, run: run2 };
995
+ }
996
+ function batch2(name, run2) {
997
+ return { kind: "batch", name, run: run2 };
998
+ }
999
+ function morpho(parameters) {
1000
+ const { whitelistedChains } = parameters;
1001
+ const whitelistedChainIds = new Set(whitelistedChains.map((chain) => chain.id));
1002
+ const whitelistedLoanTokensPerChain = new Map(
1003
+ whitelistedChains.map((chain) => [
1004
+ chain.id,
1005
+ new Set(Array.from(chain.whitelistedAssets).map((a) => a.toLowerCase()))
1006
+ ])
1007
+ );
1008
+ const morphoPerChain = new Map(
1009
+ whitelistedChains.map((chain) => [chain.id, chain.morpho.toLowerCase()])
1010
+ );
1011
+ const chainId = single("chain_id", (offer, _) => {
1012
+ if (!whitelistedChainIds.has(offer.chainId)) {
1013
+ return { message: `Chain ID ${offer.chainId} is not whitelisted` };
1014
+ }
1015
+ });
1016
+ const loanToken = single("loan_token", (offer, _) => {
1017
+ if (!whitelistedLoanTokensPerChain.get(offer.chainId)?.has(offer.loanToken.toLowerCase())) {
1018
+ return {
1019
+ message: `Loan token ${offer.loanToken} is not whitelisted on chain ${offer.chainId}`
1020
+ };
1021
+ }
1022
+ });
1023
+ const expiry = single("expiry", (offer, _) => {
1024
+ if (offer.expiry < Math.floor(Date.now() / 1e3)) {
1025
+ return { message: "Expiry mismatch" };
1026
+ }
1027
+ });
1028
+ const emptyCallback = single("empty_callback", (offer, _) => {
1029
+ if (offer.callback.data !== "0x") {
1030
+ return { message: "Callback data is not empty. Not supported yet." };
1031
+ }
1032
+ });
1033
+ const sellOffersEmptyCallback = single(
1034
+ "sell_offers_empty_callback",
1035
+ (offer, _) => {
1036
+ if (!offer.buy && offer.callback.data === "0x") {
1037
+ return { message: "Sell offers with empty callback are not supported yet." };
1038
+ }
1039
+ }
1040
+ );
1041
+ const buyOffersEmptyCallback = batch2(
1042
+ "buy_offers_empty_callback",
1043
+ async (offers, { publicClients }) => {
1044
+ const issues = /* @__PURE__ */ new Map();
1045
+ const hashToIndex = /* @__PURE__ */ new Map();
1046
+ for (let i = 0; i < offers.length; i++) {
1047
+ const offer = offers[i];
1048
+ hashToIndex.set(offer.hash, i);
1049
+ }
1050
+ const { buyOffers, sellOffers: _sellOffers } = offers.reduce(
1051
+ (acc, offer) => {
1052
+ offer.buy ? acc.buyOffers.push(offer) : issues.set(hashToIndex.get(offer.hash), {
1053
+ message: "Onchain callback for sell offers is not supported yet."
1054
+ });
1055
+ return acc;
1056
+ },
1057
+ { buyOffers: [], sellOffers: [] }
1058
+ );
1059
+ const buyOffersPerLoanAsset = /* @__PURE__ */ new Map();
1060
+ for (const offer of buyOffers) {
1061
+ const chainName = getChain(offer.chainId)?.name;
1062
+ const loanTokens = buyOffersPerLoanAsset.get(chainName) ?? /* @__PURE__ */ new Map();
1063
+ const offers2 = loanTokens.get(offer.loanToken.toLowerCase()) ?? [];
1064
+ offers2.push(offer);
1065
+ loanTokens.set(offer.loanToken.toLowerCase(), offers2);
1066
+ buyOffersPerLoanAsset.set(chainName, loanTokens);
1067
+ }
1068
+ await Promise.all(
1069
+ Array.from(buyOffersPerLoanAsset.entries()).map(async ([name, loanTokens]) => {
1070
+ const chainName = name;
1071
+ const publicClient = publicClients[chainName];
1072
+ const morpho2 = morphoPerChain.get(chains[chainName].id);
1073
+ if (!publicClient) {
1074
+ const offers2 = Array.from(loanTokens.values()).flat();
1075
+ for (const offer of offers2) {
1076
+ issues.set(hashToIndex.get(offer.hash), {
1077
+ message: `Public client for chain "${chainName}" is not available`
1078
+ });
1079
+ }
1080
+ return;
1081
+ }
1082
+ const balances = /* @__PURE__ */ new Map();
1083
+ const allowances = /* @__PURE__ */ new Map();
1084
+ for (const [loanToken2, offers2] of loanTokens) {
1085
+ const data = await Promise.all(
1086
+ offers2.flatMap((offer) => [
1087
+ publicClient.readContract({
1088
+ address: loanToken2,
1089
+ abi: parseAbi([
1090
+ "function balanceOf(address owner) view returns (uint256 balance)"
1091
+ ]),
1092
+ functionName: "balanceOf",
1093
+ args: [offer.offering]
1094
+ }),
1095
+ publicClient.readContract({
1096
+ address: loanToken2,
1097
+ abi: parseAbi([
1098
+ "function allowance(address owner, address spender) public view returns (uint256 remaining)"
1099
+ ]),
1100
+ functionName: "allowance",
1101
+ args: [offer.offering, morpho2]
1102
+ })
1103
+ ])
1104
+ );
1105
+ for (let i = 0; i < offers2.length; i++) {
1106
+ const user = offers2[i].offering.toLowerCase();
1107
+ const balance = data[i * 2] || 0n;
1108
+ const allowance = data[i * 2 + 1] || 0n;
1109
+ const userBalances = balances.get(user) ?? /* @__PURE__ */ new Map();
1110
+ userBalances.set(loanToken2.toLowerCase(), balance);
1111
+ const userAllowances = allowances.get(user) ?? /* @__PURE__ */ new Map();
1112
+ userAllowances.set(loanToken2.toLowerCase(), allowance);
1113
+ balances.set(user, userBalances);
1114
+ allowances.set(user, userAllowances);
1115
+ }
1116
+ }
1117
+ for (const offer of Array.from(loanTokens.values()).flat()) {
1118
+ const user = offer.offering.toLowerCase();
1119
+ const userBalances = balances.get(user);
1120
+ const balance = userBalances?.get(offer.loanToken.toLowerCase());
1121
+ if (balance < offer.assets) {
1122
+ issues.set(hashToIndex.get(offer.hash), {
1123
+ message: `Insufficient balance for ${offer.loanToken} on chain ${offer.chainId} (${balance.toString()} < ${offer.assets.toString()})`
1124
+ });
1125
+ continue;
1126
+ }
1127
+ const userAllowances = allowances.get(user);
1128
+ const allowance = userAllowances?.get(offer.loanToken.toLowerCase());
1129
+ if (allowance < offer.assets) {
1130
+ issues.set(hashToIndex.get(offer.hash), {
1131
+ message: `Insufficient allowance for ${offer.loanToken} on chain ${offer.chainId} (${allowance.toString()} < ${offer.assets.toString()})`
1132
+ });
1133
+ }
1134
+ }
1135
+ })
1136
+ );
1137
+ return issues;
1138
+ }
1139
+ );
1140
+ return [
1141
+ chainId,
1142
+ loanToken,
1143
+ expiry,
1144
+ // note: callback onchain check should be done last since it does not mean that the offer is forever invalid
1145
+ // integrators should be able to keep the offers that have an invalid callback onchain and be sure that is the only check that is not valid
1146
+ emptyCallback,
1147
+ sellOffersEmptyCallback,
1148
+ buyOffersEmptyCallback
1149
+ ];
1150
+ }
1151
+
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 };
1153
+ //# sourceMappingURL=index.browser.mjs.map
1154
+ //# sourceMappingURL=index.browser.mjs.map