@morpho-dev/router 0.0.13 → 0.0.15

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,8 +1,9 @@
1
- import { Errors, Offer, Mempool, Format } from '@morpho-dev/mempool';
1
+ import { Errors, Offer, Format, Mempool } from '@morpho-dev/mempool';
2
2
  export * from '@morpho-dev/mempool';
3
3
  import { base, mainnet, optimism, foundry, abstractTestnet, acala, ancient8, ancient8Sepolia, anvil, apexTestnet, arbitrum, arbitrumGoerli, arbitrumNova, assetChainTestnet, astar, astarZkEVM, astarZkyoto, arbitrumSepolia, areonNetwork, areonNetworkTestnet, artelaTestnet, atletaOlympia, aurora, auroraTestnet, auroria, avalanche, avalancheFuji, b3Sepolia, b3, bahamut, baseGoerli, baseSepolia, beam, beamTestnet, bearNetworkChainMainnet, bearNetworkChainTestnet, berachainTestnet, berachainTestnetbArtio, bevmMainnet, bitkub, bitkubTestnet, bitTorrent, bitTorrentTestnet, blast, blastSepolia, bob, bobSepolia, boba, bobaSepolia, botanixTestnet, bronos, bronosTestnet, bsc, bscTestnet, bscGreenfield, btr, btrTestnet, bxn, bxnTestnet, canto, celo, celoAlfajores, chiliz, chips, classic, confluxESpace, confluxESpaceTestnet, coreDao, crab, cronos, cronoszkEVM, cronoszkEVMTestnet, cronosTestnet, crossbell, curtis, cyber, cyberTestnet, darwinia, dchain, dchainTestnet, defichainEvm, defichainEvmTestnet, degen, dfk, dodochainTestnet, dogechain, dreyerxMainnet, dreyerxTestnet, edgeless, edgelessTestnet, edgeware, edgewareTestnet, eon, eos, eosTestnet, etherlink, etherlinkTestnet, evmos, evmosTestnet, ekta, ektaTestnet, fantom, fantomSonicTestnet, fantomTestnet, fibo, filecoin, filecoinCalibration, filecoinHyperspace, flare, flareTestnet, flowPreviewnet, flowMainnet, flowTestnet, fluence, fluenceStage, fluenceTestnet, forma, fraxtal, fraxtalTestnet, funkiMainnet, funkiSepolia, fuse, fuseSparknet, iotex, iotexTestnet, jbc, jbcTestnet, karura, gobi, goerli, gnosis, gnosisChiado, gravity, ham, hardhat, harmonyOne, hashkeyTestnet, haqqMainnet, haqqTestedge2, hedera, hederaTestnet, hederaPreviewnet, holesky, immutableZkEvm, immutableZkEvmTestnet, inEVM, iota, iotaTestnet, kakarotSepolia, kava, kavaTestnet, kcc, klaytn, klaytnBaobab, kaia, kairos, koi, kroma, kromaSepolia, l3x, l3xTestnet, lightlinkPegasus, lightlinkPhoenix, linea, lineaGoerli, lineaSepolia, lineaTestnet, lisk, liskSepolia, localhost, lukso, luksoTestnet, lycan, lyra, mandala, manta, mantaSepoliaTestnet, mantaTestnet, mantle, mantleSepoliaTestnet, mantleTestnet, merlin, metachain, metachainIstanbul, metalL2, meter, meterTestnet, metis, metisGoerli, mev, mevTestnet, mintSepoliaTestnet, mode, modeTestnet, moonbaseAlpha, moonbeam, moonbeamDev, moonriver, morphHolesky, morphSepolia, nautilus, neonDevnet, neonMainnet, nexi, nexilix, oasys, oasisTestnet, okc, optimismGoerli, optimismSepolia, opBNB, opBNBTestnet, oortMainnetDev, otimDevnet, palm, palmTestnet, playfiAlbireo, pgn, pgnTestnet, phoenix, plinga, plumeTestnet, polygon, polygonAmoy, polygonMumbai, polygonZkEvm, polygonZkEvmCardona, polygonZkEvmTestnet, pulsechain, pulsechainV4, qMainnet, qTestnet, real, redbellyTestnet, redstone, reyaNetwork, rollux, rolluxTestnet, ronin, root, rootPorcini, rootstock, rootstockTestnet, rss3, rss3Sepolia, saigon, sapphire, sapphireTestnet, satoshiVM, satoshiVMTestnet, scroll, scrollSepolia, sei, seiDevnet, seiTestnet, sepolia, shapeSepolia, shimmer, shimmerTestnet, skaleBlockBrawlers, skaleCalypso, skaleCalypsoTestnet, skaleCryptoBlades, skaleCryptoColosseum, skaleEuropa, skaleEuropaTestnet, skaleExorde, skaleHumanProtocol, skaleNebula, skaleNebulaTestnet, skaleRazor, skaleTitan, skaleTitanTestnet, sketchpad, soneiumMinato, songbird, songbirdTestnet, sophonTestnet, spicy, shardeumSphinx, shibarium, shibariumTestnet, storyTestnet, stratis, syscoin, syscoinTestnet, taraxa, taiko, taikoHekla, taikoJolnir, taikoKatla, taikoTestnetSepolia, taraxaTestnet, telcoinTestnet, telos, telosTestnet, tenet, thaiChain, thunderTestnet, tron, unreal, vechain, wanchain, wanchainTestnet, wemix, wemixTestnet, xLayerTestnet, x1Testnet, xLayer, xai, xaiTestnet, xdc, xdcTestnet, xrSepolia, yooldoVerse, yooldoVerseTestnet, zetachain, zetachainAthensTestnet, zhejiang, zilliqa, zilliqaTestnet, zkFair, zkFairTestnet, zkLinkNova, zkLinkNovaSepoliaTestnet, zksync, zksyncInMemoryNode, zksyncLocalNode, zksyncSepoliaTestnet, zora, zoraSepolia, zoraTestnet, zircuitTestnet } from 'viem/chains';
4
4
  import { z } from 'zod/v4';
5
5
  import { createDocument } from 'zod-openapi';
6
+ import { defineChain, hexToBytes as hexToBytes$1, bytesToHex as bytesToHex$1, maxUint256, keccak256 as keccak256$2, toHex, parseEther as parseEther$1, concatHex, pad, createClient, publicActions, walletActions, testActions, parseAbi as parseAbi$1, createTransport, withRetry, numberToHex as numberToHex$2, hexToBigInt as hexToBigInt$1, stringToHex as stringToHex$1, numberToBytes, encodeFunctionData as encodeFunctionData$1, createPublicClient, InternalRpcError, decodeFunctionResult as decodeFunctionResult$1 } from 'viem';
6
7
  import { serve as serve$1 } from '@hono/node-server';
7
8
  import { Hono } from 'hono';
8
9
  import * as drizzle_orm_star from 'drizzle-orm';
@@ -17,7 +18,6 @@ import { Pool } from 'pg';
17
18
  import { pgTable, timestamp, varchar, bigint, text, boolean, integer, index, serial, jsonb } from 'drizzle-orm/pg-core';
18
19
  import { safeParseNumber } from '@morpho-org/blue-sdk-viem';
19
20
  import fs from 'fs';
20
- import { defineChain, hexToBytes as hexToBytes$1, bytesToHex as bytesToHex$1, keccak256 as keccak256$2, toHex, parseEther as parseEther$1, concatHex, pad, createClient, publicActions, walletActions, testActions, parseAbi as parseAbi$1, createTransport, withRetry, numberToHex as numberToHex$2, hexToBigInt as hexToBigInt$1, stringToHex as stringToHex$1, numberToBytes, encodeFunctionData as encodeFunctionData$1, createPublicClient, InternalRpcError, decodeFunctionResult as decodeFunctionResult$1 } from 'viem';
21
21
  import * as nc from 'crypto';
22
22
  import { privateKeyToAccount } from 'viem/accounts';
23
23
  import { hexToBytes as hexToBytes$2, parseEther, getAddress, keccak256 as keccak256$1, bytesToHex as bytesToHex$2, hexToBigInt, hexToNumber as hexToNumber$1, stringToHex, numberToHex as numberToHex$1, bytesToNumber, bytesToBigInt as bytesToBigInt$1, toHex as toHex$1, isHex, parseGwei, fromRlp, encodeFunctionData, decodeErrorResult, decodeFunctionResult, encodeDeployData, toBytes as toBytes$1, serializeTransaction, toRlp } from 'viem/utils';
@@ -43,11 +43,11 @@ var __export = (target, all) => {
43
43
  for (var name in all)
44
44
  __defProp(target, name, { get: all[name], enumerable: true });
45
45
  };
46
- var __copyProps = (to, from, except, desc3) => {
47
- if (from && typeof from === "object" || typeof from === "function") {
48
- for (let key of __getOwnPropNames(from))
46
+ var __copyProps = (to, from2, except, desc3) => {
47
+ if (from2 && typeof from2 === "object" || typeof from2 === "function") {
48
+ for (let key of __getOwnPropNames(from2))
49
49
  if (!__hasOwnProp.call(to, key) && key !== except)
50
- __defProp(to, key, { get: () => from[key], enumerable: !(desc3 = __getOwnPropDesc(from, key)) || desc3.enumerable });
50
+ __defProp(to, key, { get: () => from2[key], enumerable: !(desc3 = __getOwnPropDesc(from2, key)) || desc3.enumerable });
51
51
  }
52
52
  return to;
53
53
  };
@@ -6987,7 +6987,7 @@ var require_from = __commonJS({
6987
6987
  return (hint === "string" ? String : Number)(input);
6988
6988
  }
6989
6989
  var ERR_INVALID_ARG_TYPE = require_errors().codes.ERR_INVALID_ARG_TYPE;
6990
- function from(Readable2, iterable, opts) {
6990
+ function from2(Readable2, iterable, opts) {
6991
6991
  var iterator;
6992
6992
  if (iterable && typeof iterable.next === "function") {
6993
6993
  iterator = iterable;
@@ -7026,7 +7026,7 @@ var require_from = __commonJS({
7026
7026
  }
7027
7027
  return readable;
7028
7028
  }
7029
- module2.exports = from;
7029
+ module2.exports = from2;
7030
7030
  }
7031
7031
  });
7032
7032
 
@@ -7069,7 +7069,7 @@ var require_stream_readable = __commonJS({
7069
7069
  var ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
7070
7070
  var StringDecoder;
7071
7071
  var createReadableStreamAsyncIterator;
7072
- var from;
7072
+ var from2;
7073
7073
  require_inherits()(Readable2, Stream);
7074
7074
  var errorOrDestroy = destroyImpl.errorOrDestroy;
7075
7075
  var kProxyEvents = ["error", "close", "destroy", "pause", "resume"];
@@ -7747,10 +7747,10 @@ var require_stream_readable = __commonJS({
7747
7747
  }
7748
7748
  if (typeof Symbol === "function") {
7749
7749
  Readable2.from = function(iterable, opts) {
7750
- if (from === void 0) {
7751
- from = require_from();
7750
+ if (from2 === void 0) {
7751
+ from2 = require_from();
7752
7752
  }
7753
- return from(Readable2, iterable, opts);
7753
+ return from2(Readable2, iterable, opts);
7754
7754
  };
7755
7755
  }
7756
7756
  function indexOf(xs, x) {
@@ -7927,8 +7927,8 @@ var require_pipeline = __commonJS({
7927
7927
  function call(fn) {
7928
7928
  fn();
7929
7929
  }
7930
- function pipe(from, to) {
7931
- return from.pipe(to);
7930
+ function pipe(from2, to) {
7931
+ return from2.pipe(to);
7932
7932
  }
7933
7933
  function popCallback(streams) {
7934
7934
  if (!streams.length) return noop;
@@ -8117,6 +8117,7 @@ __export(index_node_exports, {
8117
8117
  Validation: () => Validation_exports,
8118
8118
  ValidationRule: () => ValidationRule_exports,
8119
8119
  batch: () => batch,
8120
+ consumed: () => consumed,
8120
8121
  decodeCursor: () => decodeCursor,
8121
8122
  encodeCursor: () => encodeCursor,
8122
8123
  offerCollaterals: () => offerCollaterals,
@@ -8192,7 +8193,13 @@ __export(apiSchema_exports, {
8192
8193
  // src/RouterOffer.ts
8193
8194
  var RouterOffer_exports = {};
8194
8195
  __export(RouterOffer_exports, {
8195
- OfferStatusValues: () => OfferStatusValues
8196
+ InvalidRouterOfferError: () => InvalidRouterOfferError,
8197
+ OfferStatusValues: () => OfferStatusValues,
8198
+ RouterOfferSchema: () => RouterOfferSchema,
8199
+ from: () => from,
8200
+ fromSnakeCase: () => fromSnakeCase,
8201
+ random: () => random,
8202
+ toSnakeCase: () => toSnakeCase
8196
8203
  });
8197
8204
  var OfferStatusValues = [
8198
8205
  "valid",
@@ -8200,6 +8207,46 @@ var OfferStatusValues = [
8200
8207
  "callback_error",
8201
8208
  "unverified"
8202
8209
  ];
8210
+ var RouterOfferSchema = (parameters) => Offer.OfferSchema(parameters).extend({
8211
+ consumed: z.bigint({ coerce: true }).min(0n).max(maxUint256),
8212
+ status: z.enum(OfferStatusValues),
8213
+ metadata: z.object({
8214
+ issue: z.string()
8215
+ }).optional()
8216
+ });
8217
+ function from(input) {
8218
+ try {
8219
+ const parsedOffer = RouterOfferSchema({ omitHash: true }).parse(input);
8220
+ const parsedHash = Offer.OfferHashSchema.parse(Offer.hash(parsedOffer));
8221
+ return {
8222
+ ...parsedOffer,
8223
+ hash: parsedHash
8224
+ };
8225
+ } catch (error) {
8226
+ throw new InvalidRouterOfferError(error);
8227
+ }
8228
+ }
8229
+ function fromSnakeCase(input) {
8230
+ return from(Format.fromSnakeCase(input));
8231
+ }
8232
+ function toSnakeCase(offer) {
8233
+ return Format.toSnakeCase(offer);
8234
+ }
8235
+ function random() {
8236
+ const baseOffer = Offer.random();
8237
+ return from({
8238
+ ...baseOffer,
8239
+ status: "valid",
8240
+ metadata: void 0,
8241
+ consumed: 0n
8242
+ });
8243
+ }
8244
+ var InvalidRouterOfferError = class extends Errors.BaseError {
8245
+ name = "RouterOffer.InvalidRouterOfferError";
8246
+ constructor(error) {
8247
+ super("Invalid router offer.", { cause: error });
8248
+ }
8249
+ };
8203
8250
 
8204
8251
  // src/utils/batch.ts
8205
8252
  function* batch(array, batchSize) {
@@ -8900,14 +8947,7 @@ async function get(config, parameters) {
8900
8947
  const { cursor: returnedCursor, data: offers2 } = await getApi(config, url);
8901
8948
  return {
8902
8949
  cursor: returnedCursor,
8903
- offers: offers2.map((offer) => {
8904
- const baseOffer = Offer.fromSnakeCase(offer);
8905
- return {
8906
- ...baseOffer,
8907
- status: offer.status,
8908
- metadata: offer.metadata
8909
- };
8910
- })
8950
+ offers: offers2.map(fromSnakeCase)
8911
8951
  };
8912
8952
  }
8913
8953
  async function match(config, parameters) {
@@ -8948,14 +8988,7 @@ async function match(config, parameters) {
8948
8988
  const { cursor: returnedCursor, data: offers2 } = await getApi(config, url);
8949
8989
  return {
8950
8990
  cursor: returnedCursor,
8951
- offers: offers2.map((offer) => {
8952
- const baseOffer = Offer.fromSnakeCase(offer);
8953
- return {
8954
- ...baseOffer,
8955
- status: offer.status,
8956
- metadata: offer.metadata
8957
- };
8958
- })
8991
+ offers: offers2.map(fromSnakeCase)
8959
8992
  };
8960
8993
  }
8961
8994
  async function getApi(config, url) {
@@ -9044,6 +9077,7 @@ var OfferDB_exports2 = {};
9044
9077
  __export(OfferDB_exports2, {
9045
9078
  OfferDB: () => OfferDB_exports,
9046
9079
  OfferRepository: () => OfferRepository_exports,
9080
+ consumed: () => consumed,
9047
9081
  offerCollaterals: () => offerCollaterals,
9048
9082
  offerStatus: () => offerStatus,
9049
9083
  offers: () => offers
@@ -9062,6 +9096,7 @@ __export(OfferDB_exports, {
9062
9096
  // src/OfferDB/schema.ts
9063
9097
  var schema_exports = {};
9064
9098
  __export(schema_exports, {
9099
+ consumed: () => consumed,
9065
9100
  offerCollaterals: () => offerCollaterals,
9066
9101
  offerStatus: () => offerStatus,
9067
9102
  offers: () => offers
@@ -9133,6 +9168,25 @@ var offerStatus = pgTable(
9133
9168
  index("offer_status_status_idx").on(table.status)
9134
9169
  ]
9135
9170
  );
9171
+ var consumed = pgTable(
9172
+ "consumed_per_user_and_nonce",
9173
+ {
9174
+ id: serial("id").primaryKey(),
9175
+ chainId: bigint("chain_id", { mode: "bigint" }).notNull(),
9176
+ offering: varchar("offering", { length: 42 }).notNull(),
9177
+ nonce: bigint("nonce", { mode: "bigint" }).notNull(),
9178
+ consumed: bigint("consumed", { mode: "bigint" }).notNull(),
9179
+ createdAt: timestamp("created_at").defaultNow().notNull()
9180
+ },
9181
+ (table) => [
9182
+ index("consumed_per_user_and_nonce_chain_id_offering_nonce_created_at_idx").on(
9183
+ table.chainId,
9184
+ table.offering,
9185
+ table.nonce,
9186
+ desc(table.createdAt)
9187
+ )
9188
+ ]
9189
+ );
9136
9190
 
9137
9191
  // src/OfferDB/OfferDB.ts
9138
9192
  function create({
@@ -9216,6 +9270,22 @@ function create2(config) {
9216
9270
  status,
9217
9271
  metadata
9218
9272
  });
9273
+ const consumedAmountExists = await tx.select().from(consumed).where(
9274
+ and(
9275
+ eq(consumed.offering, offer.offering.toLowerCase()),
9276
+ eq(consumed.nonce, offer.nonce),
9277
+ eq(consumed.chainId, offer.chainId)
9278
+ )
9279
+ );
9280
+ if (consumedAmountExists.length > 0) {
9281
+ return offer.hash;
9282
+ }
9283
+ await tx.insert(consumed).values({
9284
+ chainId: offer.chainId,
9285
+ offering: offer.offering.toLowerCase(),
9286
+ nonce: offer.nonce,
9287
+ consumed: 0n
9288
+ });
9219
9289
  return offer.hash;
9220
9290
  });
9221
9291
  },
@@ -9254,6 +9324,23 @@ function create2(config) {
9254
9324
  status,
9255
9325
  metadata
9256
9326
  });
9327
+ const consumedAmountExists = await tx.select().from(consumed).where(
9328
+ and(
9329
+ eq(consumed.offering, offer.offering.toLowerCase()),
9330
+ eq(consumed.nonce, offer.nonce),
9331
+ eq(consumed.chainId, offer.chainId)
9332
+ )
9333
+ );
9334
+ if (consumedAmountExists.length > 0) {
9335
+ hashes.push(offer.hash);
9336
+ continue;
9337
+ }
9338
+ await tx.insert(consumed).values({
9339
+ chainId: offer.chainId,
9340
+ offering: offer.offering.toLowerCase(),
9341
+ nonce: offer.nonce,
9342
+ consumed: 0n
9343
+ });
9257
9344
  hashes.push(offer.hash);
9258
9345
  }
9259
9346
  return hashes;
@@ -9389,10 +9476,22 @@ function create2(config) {
9389
9476
  status: offerStatus.status,
9390
9477
  metadata: offerStatus.metadata
9391
9478
  }).from(offerStatus).where(eq(offerStatus.offerHash, offers.hash)).orderBy(desc(offerStatus.createdAt)).limit(1).as("latest_status");
9479
+ const latestConsumed = db.selectDistinctOn(
9480
+ [
9481
+ consumed.offering,
9482
+ consumed.nonce,
9483
+ consumed.chainId,
9484
+ consumed.createdAt
9485
+ ],
9486
+ {
9487
+ consumed: consumed.consumed
9488
+ }
9489
+ ).from(consumed).orderBy(desc(consumed.createdAt)).limit(1).as("latest_consumed");
9392
9490
  const results = await db.select({
9393
9491
  hash: offers.hash,
9394
9492
  offering: offers.offering,
9395
9493
  assets: offers.assets,
9494
+ consumed: latestConsumed.consumed,
9396
9495
  rate: offers.rate,
9397
9496
  maturity: offers.maturity,
9398
9497
  expiry: offers.expiry,
@@ -9411,10 +9510,11 @@ function create2(config) {
9411
9510
  collateralLltv: offerCollaterals.lltv,
9412
9511
  status: latestStatus.status,
9413
9512
  metadata: latestStatus.metadata
9414
- }).from(offers).leftJoin(offerCollaterals, eq(offers.hash, offerCollaterals.offerHash)).leftJoinLateral(latestStatus, sql`true`).where(
9513
+ }).from(offers).leftJoin(offerCollaterals, eq(offers.hash, offerCollaterals.offerHash)).leftJoinLateral(latestStatus, sql`true`).leftJoinLateral(latestConsumed, sql`true`).where(
9415
9514
  and(
9416
9515
  conditions.length > 0 ? and(...conditions) : sql`true`,
9417
- query?.status && query.status.length > 0 ? inArray(latestStatus.status, query.status) : eq(latestStatus.status, "valid")
9516
+ query?.status && query.status.length > 0 ? inArray(latestStatus.status, query.status) : eq(latestStatus.status, "valid"),
9517
+ sql`( ${offers.assets} - COALESCE(${latestConsumed.consumed}, 0) ) > 0`
9418
9518
  )
9419
9519
  ).orderBy(sortOrder === "asc" ? asc(sortColumn) : desc(sortColumn)).limit(limit);
9420
9520
  const offerMap = /* @__PURE__ */ new Map();
@@ -9423,6 +9523,7 @@ function create2(config) {
9423
9523
  hash: row.hash,
9424
9524
  offering: row.offering,
9425
9525
  assets: row.assets,
9526
+ consumed: row.consumed || 0n,
9426
9527
  rate: row.rate,
9427
9528
  maturity: row.maturity,
9428
9529
  expiry: row.expiry,
@@ -9499,6 +9600,7 @@ function create2(config) {
9499
9600
  });
9500
9601
  transformedResults.push({
9501
9602
  ...offer,
9603
+ consumed: offerData.consumed,
9502
9604
  status: offerData.status,
9503
9605
  ...offerData.metadata !== null ? { metadata: offerData.metadata } : {}
9504
9606
  });
@@ -9598,29 +9700,83 @@ function create2(config) {
9598
9700
  status: offerStatus.status,
9599
9701
  metadata: offerStatus.metadata
9600
9702
  }).from(offerStatus).where(eq(offerStatus.offerHash, offers.hash)).orderBy(desc(offerStatus.createdAt)).limit(1).as("latest_status");
9703
+ const latestConsumed = db.selectDistinctOn(
9704
+ [
9705
+ consumed.offering,
9706
+ consumed.nonce,
9707
+ consumed.chainId,
9708
+ consumed.createdAt
9709
+ ],
9710
+ {
9711
+ consumed: consumed.consumed
9712
+ }
9713
+ ).from(consumed).orderBy(desc(consumed.createdAt)).limit(1).as("latest_consumed");
9601
9714
  const statusCondition = status && status.length > 0 ? inArray(latestStatus.status, status) : eq(latestStatus.status, "valid");
9715
+ const bestOffers = db.selectDistinctOn(
9716
+ // group key
9717
+ [offers.offering, offers.nonce, offers.buy],
9718
+ {
9719
+ hash: offers.hash,
9720
+ offering: offers.offering,
9721
+ assets: offers.assets,
9722
+ consumed: latestConsumed.consumed,
9723
+ rate: offers.rate,
9724
+ maturity: offers.maturity,
9725
+ expiry: offers.expiry,
9726
+ start: offers.start,
9727
+ nonce: offers.nonce,
9728
+ buy: offers.buy,
9729
+ chainId: offers.chainId,
9730
+ loanToken: offers.loanToken,
9731
+ callbackAddress: offers.callbackAddress,
9732
+ callbackData: offers.callbackData,
9733
+ callbackGasLimit: offers.callbackGasLimit,
9734
+ signature: offers.signature,
9735
+ status: latestStatus.status,
9736
+ metadata: latestStatus.metadata
9737
+ }
9738
+ ).from(offers).leftJoinLateral(latestStatus, sql`true`).leftJoinLateral(latestConsumed, sql`true`).where(
9739
+ and(
9740
+ and(...conditions),
9741
+ statusCondition,
9742
+ sql`( ${offers.assets} - COALESCE(${latestConsumed.consumed}, 0) ) > 0`
9743
+ )
9744
+ ).orderBy(
9745
+ offers.offering,
9746
+ offers.nonce,
9747
+ offers.buy,
9748
+ // 1 price (direction depends on side)
9749
+ sql`CASE WHEN ${offers.buy} THEN ${offers.rate} ELSE -${offers.rate} END`,
9750
+ // 2 size (remaining)
9751
+ sql`( ${offers.assets} - COALESCE(${latestConsumed.consumed}, 0) ) DESC`,
9752
+ // 3 term (longer maturity)
9753
+ desc(offers.maturity)
9754
+ ).as("best_offers");
9602
9755
  const rows = await db.select({
9603
- hash: offers.hash,
9604
- offering: offers.offering,
9605
- assets: offers.assets,
9606
- rate: offers.rate,
9607
- maturity: offers.maturity,
9608
- expiry: offers.expiry,
9609
- start: offers.start,
9610
- nonce: offers.nonce,
9611
- buy: offers.buy,
9612
- chainId: offers.chainId,
9613
- loanToken: offers.loanToken,
9614
- callbackAddress: offers.callbackAddress,
9615
- callbackData: offers.callbackData,
9616
- callbackGasLimit: offers.callbackGasLimit,
9617
- signature: offers.signature,
9618
- status: latestStatus.status,
9619
- metadata: latestStatus.metadata,
9756
+ hash: bestOffers.hash,
9757
+ offering: bestOffers.offering,
9758
+ assets: bestOffers.assets,
9759
+ consumed: bestOffers.consumed,
9760
+ rate: bestOffers.rate,
9761
+ maturity: bestOffers.maturity,
9762
+ expiry: bestOffers.expiry,
9763
+ start: bestOffers.start,
9764
+ nonce: bestOffers.nonce,
9765
+ buy: bestOffers.buy,
9766
+ chainId: bestOffers.chainId,
9767
+ loanToken: bestOffers.loanToken,
9768
+ callbackAddress: bestOffers.callbackAddress,
9769
+ callbackData: bestOffers.callbackData,
9770
+ callbackGasLimit: bestOffers.callbackGasLimit,
9771
+ signature: bestOffers.signature,
9772
+ status: bestOffers.status,
9773
+ metadata: bestOffers.metadata,
9620
9774
  collateralAsset: offerCollaterals.asset,
9621
9775
  collateralOracle: offerCollaterals.oracle,
9622
9776
  collateralLltv: offerCollaterals.lltv
9623
- }).from(offers).leftJoin(offerCollaterals, eq(offers.hash, offerCollaterals.offerHash)).leftJoinLateral(latestStatus, sql`true`).where(and(and(...conditions), statusCondition)).orderBy(sortOrder === "asc" ? asc(offers.rate) : desc(offers.rate)).limit(limit + 1);
9777
+ }).from(bestOffers).leftJoin(offerCollaterals, eq(bestOffers.hash, offerCollaterals.offerHash)).orderBy(
9778
+ sortOrder === "asc" ? sql`CASE WHEN ${bestOffers.buy} THEN ${bestOffers.rate} ELSE -${bestOffers.rate} END ASC` : sql`CASE WHEN ${bestOffers.buy} THEN -${bestOffers.rate} ELSE ${bestOffers.rate} END DESC`
9779
+ ).limit(limit + 1);
9624
9780
  const offerMap = /* @__PURE__ */ new Map();
9625
9781
  for (const r of rows) {
9626
9782
  const entry = offerMap.get(r.hash) ?? { base: r, collaterals: [] };
@@ -9659,6 +9815,7 @@ function create2(config) {
9659
9815
  },
9660
9816
  signature: base2.signature === null ? void 0 : base2.signature
9661
9817
  }),
9818
+ consumed: base2.consumed || 0n,
9662
9819
  status: base2.status,
9663
9820
  ...base2.metadata ? { metadata: base2.metadata } : {}
9664
9821
  }));
@@ -9692,6 +9849,9 @@ function create2(config) {
9692
9849
  },
9693
9850
  updateStatus: async (parameters) => {
9694
9851
  await db.insert(offerStatus).values(parameters);
9852
+ },
9853
+ updateConsumedAmount: async (parameters) => {
9854
+ await db.insert(consumed).values(parameters);
9695
9855
  }
9696
9856
  };
9697
9857
  }
@@ -9704,6 +9864,8 @@ function createTest() {
9704
9864
  delete: async (_hash) => false,
9705
9865
  deleteMany: async (_hashes) => 0,
9706
9866
  updateStatus: async (_params) => {
9867
+ },
9868
+ updateConsumedAmount: async (_params) => {
9707
9869
  }
9708
9870
  };
9709
9871
  }
@@ -11389,15 +11551,15 @@ function weierstrassPoints(opts) {
11389
11551
  throw new Error("ProjectivePoint expected");
11390
11552
  }
11391
11553
  const toAffineMemo = memoized((p, iz) => {
11392
- const { px: x, py: y, pz: z5 } = p;
11393
- if (Fp5.eql(z5, Fp5.ONE))
11554
+ const { px: x, py: y, pz: z6 } = p;
11555
+ if (Fp5.eql(z6, Fp5.ONE))
11394
11556
  return { x, y };
11395
11557
  const is0 = p.is0();
11396
11558
  if (iz == null)
11397
- iz = is0 ? Fp5.ONE : Fp5.inv(z5);
11559
+ iz = is0 ? Fp5.ONE : Fp5.inv(z6);
11398
11560
  const ax = Fp5.mul(x, iz);
11399
11561
  const ay = Fp5.mul(y, iz);
11400
- const zz = Fp5.mul(z5, iz);
11562
+ const zz = Fp5.mul(z6, iz);
11401
11563
  if (is0)
11402
11564
  return { x: Fp5.ZERO, y: Fp5.ZERO };
11403
11565
  if (!Fp5.eql(zz, Fp5.ONE))
@@ -11812,7 +11974,7 @@ function weierstrass(curveDef) {
11812
11974
  function normalizeS(s) {
11813
11975
  return isBiggerThanHalfOrder(s) ? modN(-s) : s;
11814
11976
  }
11815
- const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
11977
+ const slcNum = (b, from2, to) => bytesToNumberBE(b.slice(from2, to));
11816
11978
  class Signature {
11817
11979
  constructor(r, s, recovery) {
11818
11980
  aInRange("r", r, _1n4, CURVE_ORDER);
@@ -13064,25 +13226,25 @@ var isValidAddress = function(hexAddress) {
13064
13226
  }
13065
13227
  return /^0x[0-9a-fA-F]{40}$/.test(hexAddress);
13066
13228
  };
13067
- var generateAddress = function(from, nonce) {
13068
- assertIsBytes(from);
13229
+ var generateAddress = function(from2, nonce) {
13230
+ assertIsBytes(from2);
13069
13231
  assertIsBytes(nonce);
13070
13232
  if (bytesToBigInt(nonce) === BIGINT_02) {
13071
- return keccak256(RLP.encode([from, Uint8Array.from([])])).subarray(-20);
13233
+ return keccak256(RLP.encode([from2, Uint8Array.from([])])).subarray(-20);
13072
13234
  }
13073
- return keccak256(RLP.encode([from, nonce])).subarray(-20);
13235
+ return keccak256(RLP.encode([from2, nonce])).subarray(-20);
13074
13236
  };
13075
- var generateAddress2 = function(from, salt, initCode) {
13076
- assertIsBytes(from);
13237
+ var generateAddress2 = function(from2, salt, initCode) {
13238
+ assertIsBytes(from2);
13077
13239
  assertIsBytes(salt);
13078
13240
  assertIsBytes(initCode);
13079
- if (from.length !== 20) {
13241
+ if (from2.length !== 20) {
13080
13242
  throw EthereumJSErrorWithoutCode("Expected from to be of length 20");
13081
13243
  }
13082
13244
  if (salt.length !== 32) {
13083
13245
  throw EthereumJSErrorWithoutCode("Expected salt to be of length 32");
13084
13246
  }
13085
- const address = keccak256(concatBytes4(hexToBytes5("0xff"), from, salt, keccak256(initCode)));
13247
+ const address = keccak256(concatBytes4(hexToBytes5("0xff"), from2, salt, keccak256(initCode)));
13086
13248
  return address.subarray(-20);
13087
13249
  };
13088
13250
  var pubToAddress = function(pubKey, sanitize = false) {
@@ -20953,7 +21115,7 @@ async function precompile0a(opts) {
20953
21115
  const version2 = Number(opts.common.param("blobCommitmentVersionKzg"));
20954
21116
  const fieldElementsPerBlob = opts.common.param("fieldElementsPerBlob");
20955
21117
  const versionedHash = bytesToHex4(opts.data.subarray(0, 32));
20956
- const z5 = bytesToHex4(opts.data.subarray(32, 64));
21118
+ const z6 = bytesToHex4(opts.data.subarray(32, 64));
20957
21119
  const y = bytesToHex4(opts.data.subarray(64, 96));
20958
21120
  const commitment = bytesToHex4(opts.data.subarray(96, 144));
20959
21121
  const kzgProof = bytesToHex4(opts.data.subarray(144, 192));
@@ -20964,10 +21126,10 @@ async function precompile0a(opts) {
20964
21126
  return EVMErrorResult(new EVMError(EVMError.errorMessages.INVALID_COMMITMENT), opts.gasLimit);
20965
21127
  }
20966
21128
  if (opts._debug !== void 0) {
20967
- opts._debug(`${pName}: proof verification with commitment=${commitment} z=${z5} y=${y} kzgProof=${kzgProof}`);
21129
+ opts._debug(`${pName}: proof verification with commitment=${commitment} z=${z6} y=${y} kzgProof=${kzgProof}`);
20968
21130
  }
20969
21131
  try {
20970
- const res = opts.common.customCrypto?.kzg?.verifyProof(commitment, z5, y, kzgProof);
21132
+ const res = opts.common.customCrypto?.kzg?.verifyProof(commitment, z6, y, kzgProof);
20971
21133
  if (res === false) {
20972
21134
  return EVMErrorResult(new EVMError(EVMError.errorMessages.INVALID_PROOF), opts.gasLimit);
20973
21135
  }
@@ -22369,15 +22531,15 @@ function weierstrassN(CURVE, curveOpts = {}) {
22369
22531
  throw new Error("ProjectivePoint expected");
22370
22532
  }
22371
22533
  const toAffineMemo = memoized2((p, iz) => {
22372
- const { px: x, py: y, pz: z5 } = p;
22373
- if (Fp5.eql(z5, Fp5.ONE))
22534
+ const { px: x, py: y, pz: z6 } = p;
22535
+ if (Fp5.eql(z6, Fp5.ONE))
22374
22536
  return { x, y };
22375
22537
  const is0 = p.is0();
22376
22538
  if (iz == null)
22377
- iz = is0 ? Fp5.ONE : Fp5.inv(z5);
22539
+ iz = is0 ? Fp5.ONE : Fp5.inv(z6);
22378
22540
  const ax = Fp5.mul(x, iz);
22379
22541
  const ay = Fp5.mul(y, iz);
22380
- const zz = Fp5.mul(z5, iz);
22542
+ const zz = Fp5.mul(z6, iz);
22381
22543
  if (is0)
22382
22544
  return { x: Fp5.ZERO, y: Fp5.ZERO };
22383
22545
  if (!Fp5.eql(zz, Fp5.ONE))
@@ -24029,13 +24191,13 @@ var { Fp, Fp2, Fp6, Fp4Square, Fp12 } = tower12({
24029
24191
  };
24030
24192
  },
24031
24193
  Fp12cyclotomicExp(num, n) {
24032
- let z5 = Fp12.ONE;
24194
+ let z6 = Fp12.ONE;
24033
24195
  for (let i = BLS_X_LEN - 1; i >= 0; i--) {
24034
- z5 = Fp12._cyclotomicSquare(z5);
24196
+ z6 = Fp12._cyclotomicSquare(z6);
24035
24197
  if (bitGet(n, i))
24036
- z5 = Fp12.mul(z5, num);
24198
+ z6 = Fp12.mul(z6, num);
24037
24199
  }
24038
- return z5;
24200
+ return z6;
24039
24201
  },
24040
24202
  // https://eprint.iacr.org/2010/354.pdf
24041
24203
  // https://eprint.iacr.org/2009/565.pdf
@@ -24216,7 +24378,7 @@ function pointG2FromBytes(bytes2) {
24216
24378
  sort && infinity && compressed) {
24217
24379
  throw new Error("invalid encoding flag: " + (bytes2[0] & 224));
24218
24380
  }
24219
- const slc = (b, from, to) => bytesToNumberBE2(b.slice(from, to));
24381
+ const slc = (b, from2, to) => bytesToNumberBE2(b.slice(from2, to));
24220
24382
  if (value.length === 96 && compressed) {
24221
24383
  if (infinity) {
24222
24384
  if (value.reduce((p, c) => p !== 0 ? c + 1 : c, 0) > 0) {
@@ -25122,16 +25284,16 @@ var Kr160 = /* @__PURE__ */ Uint32Array.from([
25122
25284
  2053994217,
25123
25285
  0
25124
25286
  ]);
25125
- function ripemd_f(group, x, y, z5) {
25287
+ function ripemd_f(group, x, y, z6) {
25126
25288
  if (group === 0)
25127
- return x ^ y ^ z5;
25289
+ return x ^ y ^ z6;
25128
25290
  if (group === 1)
25129
- return x & y | ~x & z5;
25291
+ return x & y | ~x & z6;
25130
25292
  if (group === 2)
25131
- return (x | ~y) ^ z5;
25293
+ return (x | ~y) ^ z6;
25132
25294
  if (group === 3)
25133
- return x & z5 | y & ~z5;
25134
- return x ^ (y | ~z5);
25295
+ return x & z6 | y & ~z6;
25296
+ return x ^ (y | ~z6);
25135
25297
  }
25136
25298
  var BUF_160 = /* @__PURE__ */ new Uint32Array(16);
25137
25299
  var RIPEMD160 = class extends HashMD {
@@ -25955,13 +26117,13 @@ var { Fp: Fp3, Fp2: Fp22, Fp6: Fp62, Fp4Square: Fp4Square2, Fp12: Fp122 } = towe
25955
26117
  };
25956
26118
  },
25957
26119
  Fp12cyclotomicExp(num, n) {
25958
- let z5 = Fp122.ONE;
26120
+ let z6 = Fp122.ONE;
25959
26121
  for (let i = BN_X_LEN - 1; i >= 0; i--) {
25960
- z5 = Fp122._cyclotomicSquare(z5);
26122
+ z6 = Fp122._cyclotomicSquare(z6);
25961
26123
  if (bitGet(n, i))
25962
- z5 = Fp122.mul(z5, num);
26124
+ z6 = Fp122.mul(z6, num);
25963
26125
  }
25964
- return z5;
26126
+ return z6;
25965
26127
  },
25966
26128
  // https://eprint.iacr.org/2010/354.pdf
25967
26129
  // https://eprint.iacr.org/2009/565.pdf
@@ -35995,14 +36157,14 @@ var createAddress = (address) => {
35995
36157
  });
35996
36158
  }
35997
36159
  };
35998
- var createContractAddress = (from, nonce) => {
35999
- if (!(from.bytes instanceof Uint8Array)) {
36160
+ var createContractAddress = (from2, nonce) => {
36161
+ if (!(from2.bytes instanceof Uint8Array)) {
36000
36162
  throw new InvalidAddressError("Expected from to be an Address or ethereumjs Address");
36001
36163
  }
36002
36164
  if (nonce === 0n) {
36003
- return createAddress(keccak256$1(toRlp([from.bytes, Uint8Array.from([])]), "bytes").subarray(-20));
36165
+ return createAddress(keccak256$1(toRlp([from2.bytes, Uint8Array.from([])]), "bytes").subarray(-20));
36004
36166
  }
36005
- return createAddress(keccak256$1(toRlp([from.bytes, numberToBytes(nonce)]), "bytes").subarray(-20));
36167
+ return createAddress(keccak256$1(toRlp([from2.bytes, numberToBytes(nonce)]), "bytes").subarray(-20));
36006
36168
  };
36007
36169
 
36008
36170
  // ../../node_modules/.pnpm/@ethereumjs+tx@10.0.0/node_modules/@ethereumjs/tx/dist/esm/types.js
@@ -40438,13 +40600,13 @@ function weierstrassPoints3(opts) {
40438
40600
  // Can accept precomputed Z^-1 - for example, from invertBatch.
40439
40601
  // (x, y, z) ∋ (x=x/z, y=y/z)
40440
40602
  toAffine(iz) {
40441
- const { px: x, py: y, pz: z5 } = this;
40603
+ const { px: x, py: y, pz: z6 } = this;
40442
40604
  const is0 = this.is0();
40443
40605
  if (iz == null)
40444
- iz = is0 ? Fp5.ONE : Fp5.inv(z5);
40606
+ iz = is0 ? Fp5.ONE : Fp5.inv(z6);
40445
40607
  const ax = Fp5.mul(x, iz);
40446
40608
  const ay = Fp5.mul(y, iz);
40447
- const zz = Fp5.mul(z5, iz);
40609
+ const zz = Fp5.mul(z6, iz);
40448
40610
  if (is0)
40449
40611
  return { x: Fp5.ZERO, y: Fp5.ZERO };
40450
40612
  if (!Fp5.eql(zz, Fp5.ONE))
@@ -40564,7 +40726,7 @@ function weierstrass3(curveDef) {
40564
40726
  function normalizeS(s) {
40565
40727
  return isBiggerThanHalfOrder(s) ? modN(-s) : s;
40566
40728
  }
40567
- const slcNum = (b, from, to) => bytesToNumberBE3(b.slice(from, to));
40729
+ const slcNum = (b, from2, to) => bytesToNumberBE3(b.slice(from2, to));
40568
40730
  class Signature {
40569
40731
  constructor(r, s, recovery) {
40570
40732
  this.r = r;
@@ -47415,10 +47577,10 @@ var ReceiptsManager = class _ReceiptsManager {
47415
47577
  * // Get logs with specific topics
47416
47578
  * const logs = await receiptManager.getLogs(block100, block200, undefined, [eventTopic])
47417
47579
  */
47418
- async getLogs(from, to, addresses, topics = []) {
47580
+ async getLogs(from2, to, addresses, topics = []) {
47419
47581
  const returnedLogs = [];
47420
47582
  let returnedLogsSize = 0;
47421
- for (let i = from.header.number; i <= to.header.number; i++) {
47583
+ for (let i = from2.header.number; i <= to.header.number; i++) {
47422
47584
  const block = await getBlock(this.chain)(i);
47423
47585
  const receipts = await this.getReceipts(block.hash());
47424
47586
  if (receipts.length === 0) continue;
@@ -54393,7 +54555,7 @@ var anvilStopImpersonatingAccountJsonRpcProcedure = (client) => {
54393
54555
  };
54394
54556
  var ethCreateAccessListProcedure = (client) => async (req) => {
54395
54557
  const [tx, blockTag] = req.params;
54396
- const { data, from, to, gas, gasPrice, value } = tx;
54558
+ const { data, from: from2, to, gas, gasPrice, value } = tx;
54397
54559
  const response = await callProcedure(client)({
54398
54560
  ...req.id !== void 0 ? { id: req.id } : {},
54399
54561
  jsonrpc: req.jsonrpc,
@@ -54405,7 +54567,7 @@ var ethCreateAccessListProcedure = (client) => async (req) => {
54405
54567
  ...gas !== void 0 ? { gas } : {},
54406
54568
  ...value !== void 0 ? { value } : {},
54407
54569
  ...to !== void 0 ? { to } : {},
54408
- ...from !== void 0 ? { from } : {},
54570
+ ...from2 !== void 0 ? { from: from2 } : {},
54409
54571
  ...blockTag !== void 0 ? { blockTag } : {},
54410
54572
  createAccessList: true
54411
54573
  }
@@ -54795,7 +54957,7 @@ var ethBlobBaseFeeJsonRpcProcedure = (client) => {
54795
54957
  };
54796
54958
  var ethCallProcedure = (client) => async (req) => {
54797
54959
  const [tx, blockTag, stateOverrideSet, blockOverrideSet] = req.params;
54798
- const { data, from, to, gas, gasPrice, value } = tx;
54960
+ const { data, from: from2, to, gas, gasPrice, value } = tx;
54799
54961
  const response = await callProcedure(client)({
54800
54962
  ...req.id !== void 0 ? { id: req.id } : {},
54801
54963
  jsonrpc: req.jsonrpc,
@@ -54807,7 +54969,7 @@ var ethCallProcedure = (client) => async (req) => {
54807
54969
  ...gas !== void 0 ? { gas } : {},
54808
54970
  ...value !== void 0 ? { value } : {},
54809
54971
  ...to !== void 0 ? { to } : {},
54810
- ...from !== void 0 ? { from } : {},
54972
+ ...from2 !== void 0 ? { from: from2 } : {},
54811
54973
  ...blockTag !== void 0 ? { blockTag } : {}
54812
54974
  },
54813
54975
  stateOverrideSet,
@@ -56566,14 +56728,14 @@ var debugTraceBlockJsonRpcProcedure = (client) => {
56566
56728
  };
56567
56729
  var debugTraceCallJsonRpcProcedure = (client) => {
56568
56730
  return async (request) => {
56569
- const { blockTag, tracer, to, gas, data, from, value, timeout, gasPrice, tracerConfig } = request.params[0];
56731
+ const { blockTag, tracer, to, gas, data, from: from2, value, timeout, gasPrice, tracerConfig } = request.params[0];
56570
56732
  if (timeout !== void 0) {
56571
56733
  client.logger.warn("Warning: timeout is currently respected param of debug_traceCall");
56572
56734
  }
56573
56735
  const traceResult = await traceCallHandler(client)({
56574
56736
  tracer,
56575
56737
  ...to !== void 0 ? { to } : {},
56576
- ...from !== void 0 ? { from } : {},
56738
+ ...from2 !== void 0 ? { from: from2 } : {},
56577
56739
  ...gas !== void 0 ? { gas: typeof gas === "bigint" ? gas : hexToBigInt(gas) } : {},
56578
56740
  ...gasPrice !== void 0 ? { gasPrice: typeof gasPrice === "bigint" ? gasPrice : hexToBigInt(gasPrice) } : {},
56579
56741
  ...value !== void 0 ? { value: typeof value === "bigint" ? value : hexToBigInt(value) } : {},
@@ -57600,6 +57762,6 @@ safe-buffer/index.js:
57600
57762
  (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
57601
57763
  */
57602
57764
 
57603
- export { apiSchema_exports as ApiSchema, Chain_exports as Chain, EVM_exports as EVM, Logger_exports as Logger, OfferDB_exports as OfferDB, OfferRepository_exports as OfferRepository, core_exports as Router, RouterEvent_exports as RouterEvent, RouterOffer_exports as RouterOffer, Validation_exports as Validation, ValidationRule_exports as ValidationRule, batch, decodeCursor, encodeCursor, offerCollaterals, offerStatus, offers, poll, validateCursor, wait };
57765
+ export { apiSchema_exports as ApiSchema, Chain_exports as Chain, EVM_exports as EVM, Logger_exports as Logger, OfferDB_exports as OfferDB, OfferRepository_exports as OfferRepository, core_exports as Router, RouterEvent_exports as RouterEvent, RouterOffer_exports as RouterOffer, Validation_exports as Validation, ValidationRule_exports as ValidationRule, batch, consumed, decodeCursor, encodeCursor, offerCollaterals, offerStatus, offers, poll, validateCursor, wait };
57604
57766
  //# sourceMappingURL=index.node.mjs.map
57605
57767
  //# sourceMappingURL=index.node.mjs.map