@morpho-dev/router 0.1.17 → 0.1.18

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.
@@ -422,8 +422,12 @@ var chains = {
422
422
  [
423
423
  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
424
424
  // USDC
425
- "0x6B175474E89094C44Da98b954EedeAC495271d0F"
425
+ "0x6B175474E89094C44Da98b954EedeAC495271d0F",
426
426
  // DAI
427
+ "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
428
+ // WETH
429
+ "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
430
+ // WBTC
427
431
  ].map((address) => address.toLowerCase())
428
432
  ),
429
433
  morpho: "0x0000000000000000000000000000000000000000",
@@ -446,8 +450,12 @@ var chains = {
446
450
  [
447
451
  "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
448
452
  // USDC
449
- "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb"
453
+ "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
450
454
  // DAI
455
+ "0x4200000000000000000000000000000000000006",
456
+ // WETH
457
+ "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
458
+ // WBTC
451
459
  ].map((address) => address.toLowerCase())
452
460
  ),
453
461
  morpho: "0x0000000000000000000000000000000000000000",
@@ -470,8 +478,12 @@ var chains = {
470
478
  [
471
479
  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
472
480
  // USDC
473
- "0x6B175474E89094C44Da98b954EedeAC495271d0F"
481
+ "0x6B175474E89094C44Da98b954EedeAC495271d0F",
474
482
  // DAI
483
+ "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
484
+ // WETH
485
+ "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
486
+ // WBTC
475
487
  ].map((address) => address.toLowerCase())
476
488
  ),
477
489
  morpho: "0x11a002d45db720ed47a80d2f3489cba5b833eaf5",
@@ -495,8 +507,12 @@ var chains = {
495
507
  [
496
508
  "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
497
509
  // USDC
498
- "0x6B175474E89094C44Da98b954EedeAC495271d0F"
510
+ "0x6B175474E89094C44Da98b954EedeAC495271d0F",
499
511
  // DAI
512
+ "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
513
+ // WETH
514
+ "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"
515
+ // WBTC
500
516
  ].map((address) => address.toLowerCase())
501
517
  ),
502
518
  morpho: "0x23DFBc4B8B80C14CC5e25011B8491f268395BAd6",
@@ -1254,39 +1270,92 @@ function fromSnakeCase3(input) {
1254
1270
  function toSnakeCase2(offer) {
1255
1271
  return toSnakeCase(offer);
1256
1272
  }
1257
- function random2() {
1258
- const loanToken = privateKeyToAccount(generatePrivateKey()).address;
1259
- const maturity = from3("end_of_month");
1260
- const expiry = from3("end_of_week") - 1;
1261
- const lltv = from(0.965);
1273
+ function random2(config) {
1274
+ const chain = config?.chains ? config.chains[Math.floor(Math.random() * config.chains.length)] : chains.ethereum;
1275
+ const loanToken = config?.loanTokens ? config.loanTokens[Math.floor(Math.random() * config.loanTokens.length)] : privateKeyToAccount(generatePrivateKey()).address;
1276
+ const collateralCandidates = config?.collateralTokens ? config.collateralTokens.filter((a) => a !== loanToken) : [privateKeyToAccount(generatePrivateKey()).address];
1277
+ const collateralAsset = collateralCandidates[Math.floor(Math.random() * collateralCandidates.length)];
1278
+ const maturityOption = weightedChoice([
1279
+ ["end_of_month", 1],
1280
+ ["end_of_next_month", 1]
1281
+ ]);
1282
+ const maturity = config?.maturity ?? from3(maturityOption);
1283
+ const lltv = from(
1284
+ weightedChoice([
1285
+ [0.385, 1],
1286
+ [0.5, 1],
1287
+ [0.625, 2],
1288
+ [0.77, 8],
1289
+ [0.86, 10],
1290
+ [0.915, 8],
1291
+ [0.945, 6],
1292
+ [0.965, 4],
1293
+ [0.98, 2]
1294
+ ])
1295
+ );
1296
+ const buy = config?.buy !== void 0 ? config.buy : Math.random() > 0.5;
1297
+ const ONE = 1000000000000000000n;
1298
+ const qMin = buy ? 16 : 4;
1299
+ const qMax = buy ? 32 : 16;
1300
+ const len = qMax - qMin + 1;
1301
+ const ratePairs = Array.from(
1302
+ { length: len },
1303
+ (_, idx) => {
1304
+ const q = qMin + idx;
1305
+ const scaledRate = BigInt(q) * (ONE / 4n);
1306
+ const weight = buy ? 1 + idx : 1 + (len - 1 - idx);
1307
+ return [scaledRate, weight];
1308
+ }
1309
+ );
1310
+ const rate = config?.rate ?? weightedChoice(ratePairs);
1311
+ const loanTokenDecimals = config?.assetsDecimals?.[loanToken] ?? 18;
1312
+ const unit = BigInt(10) ** BigInt(loanTokenDecimals);
1313
+ const amountBase = BigInt(100 + Math.floor(Math.random() * (1e6 - 100 + 1)));
1314
+ const assetsScaled = config?.assets ?? amountBase * unit;
1315
+ const consumed2 = config?.consumed !== void 0 ? config.consumed : Math.random() < 0.8 ? 0n : assetsScaled * BigInt(1 + Math.floor(Math.random() * 900)) / 1000n;
1316
+ const callbackBySide = (() => {
1317
+ if (buy) return { address: zeroAddress, data: "0x", gasLimit: 0n };
1318
+ const sellCallbackAddress = WhitelistedCallbackAddresses["sell_erc20_callback" /* SellERC20Callback */][0].toLowerCase();
1319
+ const amount = assetsScaled * 1000000000000000000000n;
1320
+ const data = encodeSellERC20Callback({
1321
+ collaterals: [collateralAsset],
1322
+ amounts: [amount]
1323
+ });
1324
+ return { address: sellCallbackAddress, data, gasLimit: 500000n };
1325
+ })();
1262
1326
  const offer = from5({
1263
- offering: privateKeyToAccount(generatePrivateKey()).address,
1264
- assets: BigInt(Math.floor(Math.random() * 1e6)),
1265
- rate: BigInt(Math.floor(Math.random() * 1e6)),
1327
+ offering: config?.offering ?? privateKeyToAccount(generatePrivateKey()).address,
1328
+ assets: assetsScaled,
1329
+ rate,
1266
1330
  maturity,
1267
- expiry,
1268
- start: expiry - 10,
1331
+ expiry: config?.expiry ?? maturity - 1,
1332
+ start: config?.start ?? maturity - 10,
1269
1333
  nonce: BigInt(Math.floor(Math.random() * 1e6)),
1270
- buy: Math.random() > 0.5,
1271
- chainId: 1n,
1334
+ buy,
1335
+ chainId: chain.id,
1272
1336
  loanToken,
1273
- collaterals: [
1337
+ collaterals: config?.collaterals ?? [
1274
1338
  from2({
1275
- asset: zeroAddress,
1339
+ asset: collateralAsset,
1276
1340
  oracle: zeroAddress,
1277
1341
  lltv
1278
1342
  })
1279
1343
  ],
1280
- callback: {
1281
- address: zeroAddress,
1282
- data: "0x",
1283
- gasLimit: 0n
1284
- },
1285
- consumed: 0n,
1344
+ callback: config?.callback ?? callbackBySide,
1345
+ consumed: consumed2,
1286
1346
  blockNumber: Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
1287
1347
  });
1288
1348
  return offer;
1289
1349
  }
1350
+ var weightedChoice = (pairs) => {
1351
+ const total = pairs.reduce((sum, [, weight]) => sum + weight, 0);
1352
+ let roll = Math.random() * total;
1353
+ for (const [value, weight] of pairs) {
1354
+ roll -= weight;
1355
+ if (roll < 0) return value;
1356
+ }
1357
+ return pairs[0][0];
1358
+ };
1290
1359
  var domain = (chainId) => ({
1291
1360
  chainId,
1292
1361
  verifyingContract: zeroAddress
@@ -6116,6 +6185,157 @@ function serve(parameters) {
6116
6185
  });
6117
6186
  }
6118
6187
 
6119
- export { Abi_exports as Abi, BrandTypeId, Callback_exports as Callback, Chain_exports as Chain, ChainHealth, ChainStore_exports as ChainStore, ChainsHealthResponse, Collateral_exports as Collateral, collectors_exports as Collector, CollectorHealth, CollectorStore_exports as CollectorStore, CollectorsHealthResponse, Cursor_exports as Cursor, Errors_exports as Errors, Format_exports as Format, Health_exports as Health, LLTV_exports as LLTV, Liquidity_exports as Liquidity, LiquidityStore_exports as LiquidityStore, Logger_exports as Logger, Maturity_exports as Maturity, mempool_exports as Mempool, Obligation_exports as Obligation, ObligationResponse_exports as ObligationResponse, Offer_exports as Offer, OfferResponse_exports as OfferResponse, OfferStore_exports as OfferStore, schema_exports as OffersSchema, OpenApi, PG_exports as PG, Quote_exports as Quote, RouterApi_exports as RouterApi, RouterIndexer_exports as RouterIndexer, RouterStatusResponse, Services_exports as Services, time_exports as Time, utils_exports as Utils, Validation_exports as Validation, ValidationRule_exports as ValidationRule, parse, safeParse };
6188
+ // src/client/Client.ts
6189
+ var Client_exports = {};
6190
+ __export(Client_exports, {
6191
+ HttpForbiddenError: () => HttpForbiddenError,
6192
+ HttpGetApiFailedError: () => HttpGetApiFailedError,
6193
+ HttpRateLimitError: () => HttpRateLimitError,
6194
+ HttpUnauthorizedError: () => HttpUnauthorizedError,
6195
+ InvalidUrlError: () => InvalidUrlError,
6196
+ connect: () => connect3,
6197
+ getObligations: () => getObligations2,
6198
+ getOffers: () => getOffers2
6199
+ });
6200
+ function connect3(options) {
6201
+ const u = new URL(options?.url || "https://router.morpho.dev");
6202
+ if (u.protocol !== "http:" && u.protocol !== "https:") {
6203
+ throw new InvalidUrlError(u.toString());
6204
+ }
6205
+ const headers = options?.headers ?? new Headers();
6206
+ headers.set("Content-Type", "application/json");
6207
+ options?.apiKey !== void 0 ? headers.set("X-API-Key", options.apiKey) : null;
6208
+ const config = {
6209
+ url: u,
6210
+ headers
6211
+ };
6212
+ return {
6213
+ ...config,
6214
+ getOffers: (parameters) => getOffers2(config, parameters),
6215
+ getObligations: (parameters) => getObligations2(config, parameters)
6216
+ };
6217
+ }
6218
+ async function getOffers2(config, parameters) {
6219
+ const url = new URL(`${config.url.toString()}v1/offers`);
6220
+ url.searchParams.set("side", parameters.side);
6221
+ url.searchParams.set("obligation_id", parameters.obligationId.toString());
6222
+ if (parameters.cursor) {
6223
+ url.searchParams.set("cursor", parameters.cursor);
6224
+ }
6225
+ if (parameters.limit !== void 0) {
6226
+ url.searchParams.set("limit", parameters.limit.toString());
6227
+ }
6228
+ const { cursor: returnedCursor, data: offers2 } = await getApi(config, url);
6229
+ const routerOffers = offers2.map(Offer_exports.fromSnakeCase);
6230
+ return {
6231
+ cursor: returnedCursor,
6232
+ offers: routerOffers
6233
+ };
6234
+ }
6235
+ async function getObligations2(config, parameters) {
6236
+ const url = new URL(`${config.url.toString()}v1/obligations`);
6237
+ if (parameters?.cursor !== void 0) {
6238
+ url.searchParams.set("cursor", parameters.cursor);
6239
+ }
6240
+ if (parameters?.limit !== void 0) {
6241
+ url.searchParams.set("limit", parameters.limit.toString());
6242
+ }
6243
+ const { cursor: returnedCursor, data: items } = await getApi(config, url);
6244
+ const obligations2 = items.map((item) => {
6245
+ const obligation = Obligation_exports.fromSnakeCase(item);
6246
+ const { obligationId: _, ...returned } = {
6247
+ id: () => Obligation_exports.id(obligation),
6248
+ ...obligation,
6249
+ ...Quote_exports.fromSnakeCase({ obligation_id: item.id, ask: item.ask, bid: item.bid })
6250
+ };
6251
+ return returned;
6252
+ });
6253
+ return {
6254
+ cursor: returnedCursor,
6255
+ obligations: obligations2
6256
+ };
6257
+ }
6258
+ async function getApi(config, url) {
6259
+ const pathname = url.pathname;
6260
+ let action;
6261
+ switch (true) {
6262
+ case pathname.includes("/v1/offers"):
6263
+ action = "get_offers";
6264
+ break;
6265
+ case pathname.includes("/v1/obligations"):
6266
+ action = "get_obligations";
6267
+ break;
6268
+ default:
6269
+ throw new HttpGetApiFailedError("Unknown endpoint", {
6270
+ details: `Unsupported path: ${pathname}`
6271
+ });
6272
+ }
6273
+ const schemaParseResult = safeParse(action, Object.fromEntries(url.searchParams));
6274
+ if (!schemaParseResult.success) {
6275
+ throw new HttpGetApiFailedError(`Invalid URL parameters`, {
6276
+ details: schemaParseResult.error.issues[0]?.message
6277
+ });
6278
+ }
6279
+ const response = await fetch(url.toString(), {
6280
+ method: "GET",
6281
+ headers: config.headers
6282
+ });
6283
+ if (!response.ok) {
6284
+ switch (response.status) {
6285
+ case 401:
6286
+ throw new HttpUnauthorizedError();
6287
+ case 403:
6288
+ throw new HttpForbiddenError();
6289
+ case 429:
6290
+ throw new HttpRateLimitError();
6291
+ }
6292
+ throw new HttpGetApiFailedError(`GET request returned ${response.status}`, {
6293
+ details: await response.text()
6294
+ });
6295
+ }
6296
+ return response.json();
6297
+ }
6298
+ var InvalidUrlError = class extends BaseError {
6299
+ name = "Router.InvalidUrlError";
6300
+ constructor(url) {
6301
+ super(`URL "${url}" is not http/https.`);
6302
+ }
6303
+ };
6304
+ var HttpUnauthorizedError = class extends BaseError {
6305
+ name = "Router.HttpUnauthorizedError";
6306
+ constructor() {
6307
+ super("Unauthorized.", {
6308
+ metaMessages: ["Ensure that an API key is provided."]
6309
+ });
6310
+ }
6311
+ };
6312
+ var HttpForbiddenError = class extends BaseError {
6313
+ name = "Router.HttpForbiddenError";
6314
+ constructor() {
6315
+ super("Forbidden.", {
6316
+ metaMessages: ["Ensure that the API key is valid."]
6317
+ });
6318
+ }
6319
+ };
6320
+ var HttpRateLimitError = class extends BaseError {
6321
+ name = "Router.HttpRateLimitError";
6322
+ constructor() {
6323
+ super("Rate limit exceeded.", {
6324
+ metaMessages: [
6325
+ "The number of allowed requests has been exceeded. You must wait for the rate limit to reset."
6326
+ ]
6327
+ });
6328
+ }
6329
+ };
6330
+ var HttpGetApiFailedError = class extends BaseError {
6331
+ name = "Router.HttpGetApiFailedError";
6332
+ constructor(message, { details } = {}) {
6333
+ super(message, {
6334
+ metaMessages: [details]
6335
+ });
6336
+ }
6337
+ };
6338
+
6339
+ export { Abi_exports as Abi, BrandTypeId, Callback_exports as Callback, Chain_exports as Chain, ChainHealth, ChainStore_exports as ChainStore, ChainsHealthResponse, Collateral_exports as Collateral, collectors_exports as Collector, CollectorHealth, CollectorStore_exports as CollectorStore, CollectorsHealthResponse, Cursor_exports as Cursor, Errors_exports as Errors, Format_exports as Format, Health_exports as Health, LLTV_exports as LLTV, Liquidity_exports as Liquidity, LiquidityStore_exports as LiquidityStore, Logger_exports as Logger, Maturity_exports as Maturity, mempool_exports as Mempool, Obligation_exports as Obligation, ObligationResponse_exports as ObligationResponse, Offer_exports as Offer, OfferResponse_exports as OfferResponse, OfferStore_exports as OfferStore, schema_exports as OffersSchema, OpenApi, PG_exports as PG, Quote_exports as Quote, RouterApi_exports as RouterApi, Client_exports as RouterClient, RouterIndexer_exports as RouterIndexer, RouterStatusResponse, Services_exports as Services, time_exports as Time, utils_exports as Utils, Validation_exports as Validation, ValidationRule_exports as ValidationRule, parse, safeParse };
6120
6340
  //# sourceMappingURL=index.node.mjs.map
6121
6341
  //# sourceMappingURL=index.node.mjs.map