@gearbox-protocol/sdk 14.12.0-next.77 → 14.12.0-next.79

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 (107) hide show
  1. package/dist/cjs/model/filters.js +20 -0
  2. package/dist/cjs/model/filters.schema.js +21 -0
  3. package/dist/cjs/model/index.js +6 -0
  4. package/dist/cjs/model/liquidations.js +10 -8
  5. package/dist/cjs/model/liquidations.schema.js +6 -5
  6. package/dist/cjs/model/opportunities.js +11 -9
  7. package/dist/cjs/model/opportunities.schema.js +7 -6
  8. package/dist/cjs/model/positions.js +10 -8
  9. package/dist/cjs/model/positions.schema.js +5 -4
  10. package/dist/cjs/model/primitives.schema.js +5 -4
  11. package/dist/cjs/preview/index.js +0 -1
  12. package/dist/cjs/preview/preview/buildDelayedPreview.js +4 -3
  13. package/dist/cjs/preview/preview/index.js +0 -1
  14. package/dist/cjs/preview/preview/previewAdjustCreditAccount.js +3 -2
  15. package/dist/cjs/preview/preview/types.js +0 -16
  16. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +12 -38
  17. package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +1 -1
  18. package/dist/cjs/sdk/index.js +3 -0
  19. package/dist/cjs/sdk/market/MarketSuite.js +5 -3
  20. package/dist/cjs/sdk/market/credit/CreditFacadeV310Contract.js +10 -0
  21. package/dist/cjs/sdk/market/credit/expectedBalanceDeltas.js +25 -0
  22. package/dist/cjs/sdk/market/credit/index.js +2 -0
  23. package/dist/cjs/sdk/market/index.js +2 -0
  24. package/dist/cjs/sdk/opportunities/MultichainOpportunitiesService.js +5 -2
  25. package/dist/cjs/sdk/opportunities/OpportunitiesService.js +4 -1
  26. package/dist/cjs/sdk/positions/MultichainPositionsService.js +5 -2
  27. package/dist/cjs/sdk/positions/PositionsService.js +8 -4
  28. package/dist/cjs/sdk/utils/index.js +1 -0
  29. package/dist/cjs/sdk/utils/zod.js +36 -14
  30. package/dist/esm/model/filters.js +18 -0
  31. package/dist/esm/model/filters.schema.js +19 -0
  32. package/dist/esm/model/index.js +3 -1
  33. package/dist/esm/model/liquidations.js +10 -8
  34. package/dist/esm/model/liquidations.schema.js +6 -5
  35. package/dist/esm/model/opportunities.js +11 -9
  36. package/dist/esm/model/opportunities.schema.js +7 -6
  37. package/dist/esm/model/positions.js +10 -8
  38. package/dist/esm/model/positions.schema.js +5 -4
  39. package/dist/esm/model/primitives.schema.js +6 -5
  40. package/dist/esm/preview/index.js +2 -2
  41. package/dist/esm/preview/preview/buildDelayedPreview.js +5 -4
  42. package/dist/esm/preview/preview/index.js +2 -2
  43. package/dist/esm/preview/preview/previewAdjustCreditAccount.js +4 -3
  44. package/dist/esm/preview/preview/types.js +1 -16
  45. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +12 -38
  46. package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +1 -1
  47. package/dist/esm/sdk/index.js +3 -2
  48. package/dist/esm/sdk/market/MarketSuite.js +5 -3
  49. package/dist/esm/sdk/market/credit/CreditFacadeV310Contract.js +10 -0
  50. package/dist/esm/sdk/market/credit/expectedBalanceDeltas.js +24 -0
  51. package/dist/esm/sdk/market/credit/index.js +2 -1
  52. package/dist/esm/sdk/market/index.js +2 -1
  53. package/dist/esm/sdk/opportunities/MultichainOpportunitiesService.js +5 -2
  54. package/dist/esm/sdk/opportunities/OpportunitiesService.js +4 -1
  55. package/dist/esm/sdk/positions/MultichainPositionsService.js +5 -2
  56. package/dist/esm/sdk/positions/PositionsService.js +8 -4
  57. package/dist/esm/sdk/utils/index.js +2 -2
  58. package/dist/esm/sdk/utils/zod.js +36 -15
  59. package/dist/types/dev/AccountOpener.d.ts +1 -1
  60. package/dist/types/model/curators.schema.d.ts +1 -1
  61. package/dist/types/model/filters.d.ts +30 -0
  62. package/dist/types/model/filters.schema.d.ts +16 -0
  63. package/dist/types/model/history.schema.d.ts +6 -6
  64. package/dist/types/model/index.d.ts +3 -1
  65. package/dist/types/model/liquidations.d.ts +14 -10
  66. package/dist/types/model/liquidations.schema.d.ts +52 -52
  67. package/dist/types/model/opportunities.d.ts +15 -11
  68. package/dist/types/model/opportunities.schema.d.ts +107 -107
  69. package/dist/types/model/positions.d.ts +14 -10
  70. package/dist/types/model/positions.schema.d.ts +96 -96
  71. package/dist/types/model/primitives.d.ts +1 -0
  72. package/dist/types/model/primitives.schema.d.ts +9 -8
  73. package/dist/types/preview/index.d.ts +2 -2
  74. package/dist/types/preview/preview/index.d.ts +2 -2
  75. package/dist/types/preview/preview/types.d.ts +1 -16
  76. package/dist/types/sdk/OnchainSDK.d.ts +3 -3
  77. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +8 -7
  78. package/dist/types/sdk/accounts/bots/types.d.ts +1 -1
  79. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressor.d.ts +1 -1
  80. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressorV310Contract.d.ts +1 -1
  81. package/dist/types/sdk/accounts/credit-account-compressor/types.d.ts +3 -3
  82. package/dist/types/sdk/accounts/index.d.ts +2 -2
  83. package/dist/types/sdk/accounts/intents/operations/repay-credit-account/index.d.ts +1 -2
  84. package/dist/types/sdk/accounts/liquidations/types.d.ts +1 -1
  85. package/dist/types/sdk/accounts/types.d.ts +8 -78
  86. package/dist/types/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.d.ts +1 -1
  87. package/dist/types/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.d.ts +1 -1
  88. package/dist/types/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.d.ts +1 -1
  89. package/dist/types/sdk/base/index.d.ts +2 -2
  90. package/dist/types/sdk/base/types.d.ts +43 -2
  91. package/dist/types/sdk/index.d.ts +25 -24
  92. package/dist/types/sdk/market/MarketSuite.d.ts +1 -1
  93. package/dist/types/sdk/market/credit/CreditFacadeV310Contract.d.ts +6 -3
  94. package/dist/types/sdk/market/credit/CreditSuite.d.ts +2 -2
  95. package/dist/types/sdk/market/credit/expectedBalanceDeltas.d.ts +39 -0
  96. package/dist/types/sdk/market/credit/index.d.ts +3 -2
  97. package/dist/types/sdk/market/credit/types.d.ts +26 -3
  98. package/dist/types/sdk/market/index.d.ts +4 -3
  99. package/dist/types/sdk/market/rwa/index.d.ts +2 -2
  100. package/dist/types/sdk/market/rwa/securitize/SecuritizeRWAFactory.d.ts +1 -2
  101. package/dist/types/sdk/market/rwa/types.d.ts +11 -2
  102. package/dist/types/sdk/options.d.ts +4 -4
  103. package/dist/types/sdk/pools/types.d.ts +1 -12
  104. package/dist/types/sdk/positions/PositionsService.d.ts +1 -1
  105. package/dist/types/sdk/utils/index.d.ts +2 -2
  106. package/dist/types/sdk/utils/zod.d.ts +7 -3
  107. package/package.json +1 -1
@@ -1,6 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_base_SDKConstruct = require("../base/SDKConstruct.js");
3
3
  require("../base/index.js");
4
+ const require_model_filters = require("../../model/filters.js");
5
+ require("../../model/index.js");
4
6
  //#region src/sdk/opportunities/OpportunitiesService.ts
5
7
  /**
6
8
  * Builds the `opportunities` read model from the chain.
@@ -22,7 +24,8 @@ var OpportunitiesService = class extends require_sdk_base_SDKConstruct.SDKConstr
22
24
  * @param filter - Optional narrowing, applied to the built rows.
23
25
  **/
24
26
  async list(filter) {
25
- if (filter?.chainIds && !filter.chainIds.includes(this.chainId)) return [];
27
+ const chainIds = filter?.chainIds;
28
+ if (require_model_filters.isFilterSet(chainIds) && !chainIds.includes(this.chainId)) return [];
26
29
  return this.sdk.marketRegister.markets.flatMap((market) => market.opportunities(filter));
27
30
  }
28
31
  /**
@@ -2,6 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_chain_chains = require("../chain/chains.js");
3
3
  const require_sdk_base_MultichainConstruct = require("../base/MultichainConstruct.js");
4
4
  require("../base/index.js");
5
+ const require_model_filters = require("../../model/filters.js");
6
+ require("../../model/index.js");
5
7
  //#region src/sdk/positions/MultichainPositionsService.ts
6
8
  /**
7
9
  * Cross-chain counterpart of {@link PositionsService}.
@@ -34,9 +36,10 @@ var MultichainPositionsService = class extends require_sdk_base_MultichainConstr
34
36
  * a filter naming them is a narrowing, not a request.
35
37
  **/
36
38
  #networksOf(filter) {
37
- if (!filter?.chainIds) return;
39
+ const chainIds = filter?.chainIds;
40
+ if (!require_model_filters.isFilterSet(chainIds)) return;
38
41
  const networks = [];
39
- for (const chainId of filter.chainIds) try {
42
+ for (const chainId of chainIds) try {
40
43
  networks.push(require_sdk_chain_chains.getNetworkType(chainId));
41
44
  } catch {
42
45
  this.sdk.logger?.debug(`ignoring unsupported chain ${chainId} in positions filter`);
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_base_SDKConstruct = require("../base/SDKConstruct.js");
3
3
  require("../base/index.js");
4
+ const require_model_filters = require("../../model/filters.js");
4
5
  const require_model_positions = require("../../model/positions.js");
5
6
  require("../../model/index.js");
6
7
  //#region src/sdk/positions/PositionsService.ts
@@ -13,18 +14,21 @@ var PositionsService = class extends require_sdk_base_SDKConstruct.SDKConstruct
13
14
  /**
14
15
  * Every position of a wallet on this chain, optionally narrowed by
15
16
  * {@link PositionFilter} (see {@link matchesPositionFilter} for what each
16
- * criterion selects). Reads live chain state, so rows reflect the moment of
17
+ * condition selects). Reads live chain state, so rows reflect the moment of
17
18
  * the call rather than the SDK's loaded snapshot.
18
19
  **/
19
20
  async list(props) {
20
21
  const { wallet, filter } = props;
21
- if (filter?.chainIds && !filter.chainIds.includes(this.chainId)) return [];
22
- const wanted = (kind) => !filter?.kind || filter.kind === kind;
22
+ const chainIds = filter?.chainIds;
23
+ if (require_model_filters.isFilterSet(chainIds) && !chainIds.includes(this.chainId)) return [];
24
+ const wantedKind = filter?.kind;
25
+ const wanted = (kind) => !require_model_filters.isFilterSet(wantedKind) || wantedKind === kind;
26
+ const isZeroDebt = filter?.isZeroDebt;
23
27
  const [pool, strategy, liquidation] = await Promise.all([
24
28
  wanted("pool") ? this.sdk.pools.listPositions({ wallet }) : Promise.resolve([]),
25
29
  wanted("strategy") ? this.sdk.accounts.listPositions({
26
30
  owner: wallet,
27
- includeZeroDebt: filter?.isZeroDebt !== false
31
+ includeZeroDebt: !require_model_filters.isFilterSet(isZeroDebt) || isZeroDebt
28
32
  }) : Promise.resolve([]),
29
33
  wanted("liquidation") ? this.sdk.liquidations.getLiquidationPositions({ liquidator: wallet }) : Promise.resolve([])
30
34
  ]);
@@ -24,6 +24,7 @@ exports.AssetsMap = require_sdk_utils_AssetsMap.AssetsMap;
24
24
  exports.BigIntMath = require_sdk_utils_bigint_math.BigIntMath;
25
25
  exports.TypedObjectUtils = require_sdk_utils_mappers.TypedObjectUtils;
26
26
  exports.ZodAddress = require_sdk_utils_zod.ZodAddress;
27
+ exports.ZodBigInt = require_sdk_utils_zod.ZodBigInt;
27
28
  exports.ZodHex = require_sdk_utils_zod.ZodHex;
28
29
  exports.bytes32ToString = require_sdk_utils_bytes32ToString.bytes32ToString;
29
30
  exports.childLogger = require_sdk_utils_childLogger.childLogger;
@@ -3,27 +3,49 @@ let viem = require("viem");
3
3
  let zod_v4 = require("zod/v4");
4
4
  //#region src/sdk/utils/zod.ts
5
5
  /**
6
+ * A `bigint` codec that serializes into string, deserializes into bigint.
7
+ */
8
+ const ZodBigInt = () => zod_v4.z.codec(zod_v4.z.union([zod_v4.z.string().regex(zod_v4.z.regexes.integer), zod_v4.z.bigint()]), zod_v4.z.bigint(), {
9
+ decode: (value) => typeof value === "bigint" ? value : BigInt(value),
10
+ encode: (value) => value.toString()
11
+ });
12
+ const addressOut = zod_v4.z.custom((val) => typeof val === "string" && (0, viem.isAddress)(val, { strict: false }));
13
+ /**
6
14
  * Like Address from abitype/zod, but converts an address into an address that is checksum encoded.
7
15
  */
8
- const ZodAddress = () => zod_v4.z.string().transform((val, ctx) => {
9
- if (!(0, viem.isAddress)(val)) ctx.issues.push({
10
- code: "custom",
11
- message: `invalid address ${val}`,
12
- input: ctx.value
13
- });
14
- return (0, viem.getAddress)(val);
16
+ const ZodAddress = () => zod_v4.z.codec(zod_v4.z.string(), addressOut, {
17
+ decode: (val, ctx) => {
18
+ if (!(0, viem.isAddress)(val, { strict: false })) {
19
+ ctx.issues.push({
20
+ code: "custom",
21
+ message: `invalid address ${val}`,
22
+ input: val
23
+ });
24
+ return zod_v4.z.NEVER;
25
+ }
26
+ return (0, viem.getAddress)(val);
27
+ },
28
+ encode: (address) => address
15
29
  });
30
+ const hexOut = zod_v4.z.custom((val) => typeof val === "string" && (0, viem.isHex)(val));
16
31
  /**
17
32
  * A `0x`-prefixed hex string, as viem's Hex.
18
33
  */
19
- const ZodHex = () => zod_v4.z.string().transform((val, ctx) => {
20
- if (!(0, viem.isHex)(val)) ctx.issues.push({
21
- code: "custom",
22
- message: `invalid hex string ${val}`,
23
- input: ctx.value
24
- });
25
- return val;
34
+ const ZodHex = () => zod_v4.z.codec(zod_v4.z.string(), hexOut, {
35
+ decode: (val, ctx) => {
36
+ if (!(0, viem.isHex)(val)) {
37
+ ctx.issues.push({
38
+ code: "custom",
39
+ message: `invalid hex string ${val}`,
40
+ input: val
41
+ });
42
+ return zod_v4.z.NEVER;
43
+ }
44
+ return val;
45
+ },
46
+ encode: (hex) => hex
26
47
  });
27
48
  //#endregion
28
49
  exports.ZodAddress = ZodAddress;
50
+ exports.ZodBigInt = ZodBigInt;
29
51
  exports.ZodHex = ZodHex;
@@ -0,0 +1,18 @@
1
+ //#region src/model/filters.ts
2
+ /**
3
+ * The vocabulary every read-model filter is written in: how a single condition
4
+ * says "do not narrow", and how a predicate asks whether it narrows at all.
5
+ **/
6
+ /**
7
+ * Sentinel a filter condition can be set to instead of being omitted.
8
+ **/
9
+ const FILTER_ALL = "all";
10
+ /**
11
+ * Whether a condition narrows anything. An omitted condition and one set to
12
+ * {@link FILTER_ALL} both do not, so this is the only check a predicate needs.
13
+ **/
14
+ function isFilterSet(condition) {
15
+ return condition !== void 0 && condition !== "all";
16
+ }
17
+ //#endregion
18
+ export { FILTER_ALL, isFilterSet };
@@ -0,0 +1,19 @@
1
+ import "./filters.js";
2
+ import { z } from "zod/v4";
3
+ //#region src/model/filters.schema.ts
4
+ /**
5
+ * Runtime schemas for {@link ./filters.js}, see the note in
6
+ * `primitives.schema.ts` on why they are written by hand.
7
+ **/
8
+ /**
9
+ * {@link FilterAll}
10
+ **/
11
+ const filterAllSchema = z.literal("all");
12
+ /**
13
+ * {@link Filterable}
14
+ **/
15
+ function filterable(schema) {
16
+ return z.union([schema, filterAllSchema]);
17
+ }
18
+ //#endregion
19
+ export { filterAllSchema, filterable };
@@ -1,5 +1,7 @@
1
1
  import "./curators.js";
2
2
  import { curatorNameSchema, curatorSchema } from "./curators.schema.js";
3
+ import { FILTER_ALL, isFilterSet } from "./filters.js";
4
+ import { filterAllSchema, filterable } from "./filters.schema.js";
3
5
  import { POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_METRICS, STRATEGY_POSITION_HISTORY_METRICS } from "./history.js";
4
6
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema } from "./primitives.schema.js";
5
7
  import { apyBreakdownSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterSchema, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pointRewardsSchema, pointsProgramSchema, poolOpportunityDetailSchema, poolOpportunityKeySchema, poolOpportunitySchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, rewardsSchema, strategyOpportunityDetailSchema, strategyOpportunityKeySchema, strategyOpportunitySchema, tokenRewardsSchema } from "./opportunities.schema.js";
@@ -10,4 +12,4 @@ import { matchesLiquidatableAccountFilter } from "./liquidations.js";
10
12
  import { matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpportunityId } from "./opportunities.js";
11
13
  import { liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId } from "./positions.js";
12
14
  import "./primitives.js";
13
- export { POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_METRICS, STRATEGY_POSITION_HISTORY_METRICS, amountSchema, apyBreakdownSchema, assetTypeSchema, bpsSchema, chainIdSchema, curatorNameSchema, curatorSchema, delayedReceivedAssetSchema, historyChartMetadataSchema, historyMetricSchema, historyPointSchema, historyRangeSchema, historySeriesSchema, instantReceivedAssetSchema, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterSchema, opportunityHistoryQuerySchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolHistoryMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionHistoryMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterSchema, positionHistoryMetricSchema, positionHistoryQuerySchema, positionId, positionKeySchema, positionKindSchema, positionSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, rewardsPnLSchema, rewardsSchema, strategyHistoryMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionHistoryMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, txCallSchema };
15
+ export { FILTER_ALL, POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_METRICS, STRATEGY_POSITION_HISTORY_METRICS, amountSchema, apyBreakdownSchema, assetTypeSchema, bpsSchema, chainIdSchema, curatorNameSchema, curatorSchema, delayedReceivedAssetSchema, filterAllSchema, filterable, historyChartMetadataSchema, historyMetricSchema, historyPointSchema, historyRangeSchema, historySeriesSchema, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterSchema, opportunityHistoryQuerySchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolHistoryMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionHistoryMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterSchema, positionHistoryMetricSchema, positionHistoryQuerySchema, positionId, positionKeySchema, positionKindSchema, positionSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, rewardsPnLSchema, rewardsSchema, strategyHistoryMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionHistoryMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, txCallSchema };
@@ -1,21 +1,23 @@
1
+ import { isFilterSet } from "./filters.js";
1
2
  //#region src/model/liquidations.ts
2
3
  /**
3
- * Whether a liquidatable account satisfies every criterion of a filter.
4
+ * Whether a liquidatable account satisfies every condition of a filter.
4
5
  *
5
- * This is the single definition of what each criterion means: every source
6
+ * This is the single definition of what each condition means: every source
6
7
  * builds its rows first and runs them through here, so the chain and the
7
8
  * backend cannot disagree on what a filter selects.
8
9
  *
9
10
  * @param account - Row to test.
10
- * @param filter - Criteria to test against. An absent filter matches anything.
11
+ * @param filter - Conditions to test against. An absent filter matches
12
+ * anything.
11
13
  **/
12
14
  function matchesLiquidatableAccountFilter(account, filter) {
13
15
  if (!filter) return true;
14
- if (filter.chainIds && !filter.chainIds.includes(account.chainId)) return false;
15
- if (filter.underlyingType && account.totalValue.token.assetType !== filter.underlyingType) return false;
16
- if (filter.paused !== void 0 && account.paused !== filter.paused) return false;
17
- if (filter.rwa !== void 0 && account.rwa !== filter.rwa) return false;
18
- if (filter.delayed !== void 0 && account.isDelayed !== filter.delayed) return false;
16
+ if (isFilterSet(filter.chainIds) && !filter.chainIds.includes(account.chainId)) return false;
17
+ if (isFilterSet(filter.underlyingType) && account.totalValue.token.assetType !== filter.underlyingType) return false;
18
+ if (isFilterSet(filter.paused) && account.paused !== filter.paused) return false;
19
+ if (isFilterSet(filter.rwa) && account.rwa !== filter.rwa) return false;
20
+ if (isFilterSet(filter.delayed) && account.isDelayed !== filter.delayed) return false;
19
21
  return true;
20
22
  }
21
23
  //#endregion
@@ -1,4 +1,5 @@
1
1
  import { ZodAddress } from "../sdk/utils/zod.js";
2
+ import { filterable } from "./filters.schema.js";
2
3
  import { assetTypeSchema, chainIdSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema } from "./primitives.schema.js";
3
4
  import { z } from "zod/v4";
4
5
  //#region src/model/liquidations.schema.ts
@@ -10,11 +11,11 @@ import { z } from "zod/v4";
10
11
  * {@link LiquidatableAccountFilter}
11
12
  **/
12
13
  const liquidatableAccountFilterSchema = z.object({
13
- chainIds: z.array(chainIdSchema).optional(),
14
- underlyingType: assetTypeSchema.optional(),
15
- paused: z.boolean().optional(),
16
- rwa: z.boolean().optional(),
17
- delayed: z.boolean().optional()
14
+ chainIds: filterable(z.array(chainIdSchema)).optional(),
15
+ underlyingType: filterable(assetTypeSchema).optional(),
16
+ paused: filterable(z.boolean()).optional(),
17
+ rwa: filterable(z.boolean()).optional(),
18
+ delayed: filterable(z.boolean()).optional()
18
19
  });
19
20
  /**
20
21
  * {@link LiquidatableAccount}
@@ -1,3 +1,4 @@
1
+ import { isFilterSet } from "./filters.js";
1
2
  //#region src/model/opportunities.ts
2
3
  /**
3
4
  * Builds the canonical id of a pool opportunity.
@@ -28,23 +29,24 @@ function opportunityId(opportunity) {
28
29
  return opportunity.kind === "pool" ? poolOpportunityId(opportunity.chainId, opportunity.pool) : strategyOpportunityId(opportunity.chainId, opportunity.creditManager, opportunity.targetCollateral.address);
29
30
  }
30
31
  /**
31
- * Whether an opportunity satisfies every criterion of a filter.
32
+ * Whether an opportunity satisfies every condition of a filter.
32
33
  *
33
- * This is the single definition of what each criterion means: every source
34
+ * This is the single definition of what each condition means: every source
34
35
  * builds its rows first and runs them through here, so the chain and the
35
36
  * backend cannot disagree on what a filter selects.
36
37
  *
37
38
  * @param opportunity - Row to test.
38
- * @param filter - Criteria to test against. An absent filter matches anything.
39
+ * @param filter - Conditions to test against. An absent filter matches
40
+ * anything.
39
41
  **/
40
42
  function matchesOpportunityFilter(opportunity, filter) {
41
43
  if (!filter) return true;
42
- if (filter.kind && opportunity.kind !== filter.kind) return false;
43
- if (filter.chainIds && !filter.chainIds.includes(opportunity.chainId)) return false;
44
- if (filter.underlyingType && opportunity.underlyingToken.assetType !== filter.underlyingType) return false;
45
- if (filter.paused !== void 0 && opportunity.paused !== filter.paused) return false;
46
- if (filter.sunset !== void 0 && opportunity.sunset !== filter.sunset) return false;
47
- if (filter.rwa !== void 0 && opportunity.rwa !== filter.rwa) return false;
44
+ if (isFilterSet(filter.kind) && opportunity.kind !== filter.kind) return false;
45
+ if (isFilterSet(filter.chainIds) && !filter.chainIds.includes(opportunity.chainId)) return false;
46
+ if (isFilterSet(filter.underlyingType) && opportunity.underlyingToken.assetType !== filter.underlyingType) return false;
47
+ if (isFilterSet(filter.paused) && opportunity.paused !== filter.paused) return false;
48
+ if (isFilterSet(filter.sunset) && opportunity.sunset !== filter.sunset) return false;
49
+ if (isFilterSet(filter.rwa) && opportunity.rwa !== filter.rwa) return false;
48
50
  return true;
49
51
  }
50
52
  //#endregion
@@ -1,5 +1,6 @@
1
1
  import { ZodAddress } from "../sdk/utils/zod.js";
2
2
  import { curatorSchema } from "./curators.schema.js";
3
+ import { filterable } from "./filters.schema.js";
3
4
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenSchema } from "./primitives.schema.js";
4
5
  import { z } from "zod/v4";
5
6
  //#region src/model/opportunities.schema.ts
@@ -102,12 +103,12 @@ const opportunitySchema = z.discriminatedUnion("kind", [poolOpportunitySchema, s
102
103
  * {@link OpportunityFilter}
103
104
  **/
104
105
  const opportunityFilterSchema = z.object({
105
- kind: opportunityKindSchema.optional(),
106
- chainIds: z.array(chainIdSchema).optional(),
107
- underlyingType: assetTypeSchema.optional(),
108
- paused: z.boolean().optional(),
109
- sunset: z.boolean().optional(),
110
- rwa: z.boolean().optional()
106
+ kind: filterable(opportunityKindSchema).optional(),
107
+ chainIds: filterable(z.array(chainIdSchema)).optional(),
108
+ underlyingType: filterable(assetTypeSchema).optional(),
109
+ paused: filterable(z.boolean()).optional(),
110
+ sunset: filterable(z.boolean()).optional(),
111
+ rwa: filterable(z.boolean()).optional()
111
112
  });
112
113
  /**
113
114
  * {@link RateCurvePoint}
@@ -1,3 +1,4 @@
1
+ import { isFilterSet } from "./filters.js";
1
2
  //#region src/model/positions.ts
2
3
  /**
3
4
  * Builds the canonical id of a pool position.
@@ -45,26 +46,27 @@ function positionId(position) {
45
46
  }
46
47
  }
47
48
  /**
48
- * Whether a position satisfies every criterion of a filter.
49
+ * Whether a position satisfies every condition of a filter.
49
50
  *
50
- * This is the single definition of what each criterion means: every source
51
+ * This is the single definition of what each condition means: every source
51
52
  * builds its rows first and runs them through here, so the chain and the
52
53
  * backend cannot disagree on what a filter selects.
53
54
  *
54
- * A criterion that does not apply to a position's kind keeps the row rather
55
+ * A condition that does not apply to a position's kind keeps the row rather
55
56
  * than dropping it: `isZeroDebt` says nothing about a pool position, and
56
57
  * `underlyingType` says nothing about a liquidation position, which is
57
58
  * denominated in whatever its withdrawal pays out.
58
59
  *
59
60
  * @param position - Row to test.
60
- * @param filter - Criteria to test against. An absent filter matches anything.
61
+ * @param filter - Conditions to test against. An absent filter matches
62
+ * anything.
61
63
  **/
62
64
  function matchesPositionFilter(position, filter) {
63
65
  if (!filter) return true;
64
- if (filter.kind && position.kind !== filter.kind) return false;
65
- if (filter.chainIds && !filter.chainIds.includes(position.chainId)) return false;
66
- if (filter.isZeroDebt !== void 0 && position.kind === "strategy" && position.totalDebt.value === 0n !== filter.isZeroDebt) return false;
67
- if (filter.underlyingType) {
66
+ if (isFilterSet(filter.kind) && position.kind !== filter.kind) return false;
67
+ if (isFilterSet(filter.chainIds) && !filter.chainIds.includes(position.chainId)) return false;
68
+ if (isFilterSet(filter.isZeroDebt) && position.kind === "strategy" && position.totalDebt.value === 0n !== filter.isZeroDebt) return false;
69
+ if (isFilterSet(filter.underlyingType)) {
68
70
  const underlying = positionUnderlying(position);
69
71
  if (underlying && underlying.assetType !== filter.underlyingType) return false;
70
72
  }
@@ -1,4 +1,5 @@
1
1
  import { ZodAddress } from "../sdk/utils/zod.js";
2
+ import { filterable } from "./filters.schema.js";
2
3
  import { assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, tokenAmountSchema, tokenSchema } from "./primitives.schema.js";
3
4
  import { apyBreakdownSchema, pointsProgramSchema } from "./opportunities.schema.js";
4
5
  import { delayedReceivedAssetSchema, liquidationPositionSchema } from "./liquidations.schema.js";
@@ -100,10 +101,10 @@ const positionSchema = z.discriminatedUnion("kind", [
100
101
  * {@link PositionFilter}
101
102
  **/
102
103
  const positionFilterSchema = z.object({
103
- kind: positionKindSchema.optional(),
104
- isZeroDebt: z.boolean().optional(),
105
- chainIds: z.array(chainIdSchema).optional(),
106
- underlyingType: assetTypeSchema.optional()
104
+ kind: filterable(positionKindSchema).optional(),
105
+ isZeroDebt: filterable(z.boolean()).optional(),
106
+ chainIds: filterable(z.array(chainIdSchema)).optional(),
107
+ underlyingType: filterable(assetTypeSchema).optional()
107
108
  });
108
109
  /**
109
110
  * {@link PoolPositionKey}
@@ -1,4 +1,4 @@
1
- import { ZodAddress, ZodHex } from "../sdk/utils/zod.js";
1
+ import { ZodAddress, ZodBigInt, ZodHex } from "../sdk/utils/zod.js";
2
2
  import { z } from "zod/v4";
3
3
  //#region src/model/primitives.schema.ts
4
4
  /**
@@ -30,14 +30,15 @@ const assetTypeSchema = z.union([
30
30
  z.literal("BTC")
31
31
  ]);
32
32
  /**
33
- * {@link Leverage}
33
+ * {@link Leverage}. Nonnegative rather than positive: `0` is the backend's
34
+ * encoding of "leverage unavailable".
34
35
  **/
35
- const leverageSchema = z.number().positive();
36
+ const leverageSchema = z.number().nonnegative();
36
37
  /**
37
38
  * {@link Amount}
38
39
  **/
39
40
  const amountSchema = z.object({
40
- value: z.bigint(),
41
+ value: ZodBigInt(),
41
42
  valueUsd: z.number().nullable()
42
43
  });
43
44
  /**
@@ -61,7 +62,7 @@ const tokenAmountSchema = amountSchema.extend({ token: tokenSchema });
61
62
  const txCallSchema = z.object({
62
63
  to: ZodAddress(),
63
64
  callData: ZodHex(),
64
- value: z.bigint().optional()
65
+ value: ZodBigInt().optional()
65
66
  });
66
67
  //#endregion
67
68
  export { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema };
@@ -18,7 +18,7 @@ import { BalancePrerequisite } from "./prerequisites/BalancePrerequisite.js";
18
18
  import { RWAOpenRequirementsPrerequisite } from "./prerequisites/RWAOpenRequirementsPrerequisite.js";
19
19
  import { checkPrerequisites } from "./prerequisites/checkPrerequisites.js";
20
20
  import "./prerequisites/index.js";
21
- import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST } from "./preview/types.js";
21
+ import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN } from "./preview/types.js";
22
22
  import { buildDelayedPreview } from "./preview/buildDelayedPreview.js";
23
23
  import { CreditAccountState } from "./preview/CreditAccountState.js";
24
24
  import { classifyCloseOrRepay, isCloseOrRepay } from "./preview/detectCloseOrRepay.js";
@@ -32,4 +32,4 @@ import { previewCloseOrRepayCreditAccount } from "./preview/previewCloseOrRepayC
32
32
  import { previewOperation } from "./preview/previewOperation.js";
33
33
  import "./preview/index.js";
34
34
  import "./types.js";
35
- export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedPreview, checkPrerequisites, classifyCloseOrRepay, classifyInnerOperations, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
35
+ export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedPreview, checkPrerequisites, classifyCloseOrRepay, classifyInnerOperations, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -1,8 +1,9 @@
1
1
  import { AssetsMap } from "../../sdk/utils/AssetsMap.js";
2
2
  import { BigIntMath } from "../../sdk/utils/bigint-math.js";
3
+ import { DUST_THRESHOLD } from "../../sdk/constants/math.js";
3
4
  import "../../sdk/index.js";
4
5
  import "../../common-utils/index.js";
5
- import { ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST } from "./types.js";
6
+ import { ERROR_UNPRICEABLE_TOKEN } from "./types.js";
6
7
  import { isAddressEqual } from "viem";
7
8
  //#region src/preview/preview/buildDelayedPreview.ts
8
9
  /**
@@ -171,7 +172,7 @@ function buildClosePreview(post, converter, receivedToken) {
171
172
  };
172
173
  }
173
174
  function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
174
- const totalValue = totalValueInUnderlying(post, converter.convert, PREVIEW_DUST);
175
+ const totalValue = totalValueInUnderlying(post, converter.convert, DUST_THRESHOLD);
175
176
  return {
176
177
  operation: "AdjustCreditAccount",
177
178
  creditManager: post.creditManager,
@@ -183,8 +184,8 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
183
184
  debtChange: post.debt - before.debt,
184
185
  quotas: post.quotas.toAssets(0n),
185
186
  quotasChange: post.quotas.difference(before.quotas).toAssets(),
186
- assets: post.balances.toAssets(PREVIEW_DUST),
187
- assetsChange: post.balances.difference(before.balances).toAssets(PREVIEW_DUST),
187
+ assets: post.balances.toAssets(DUST_THRESHOLD),
188
+ assetsChange: post.balances.difference(before.balances).toAssets(DUST_THRESHOLD),
188
189
  error: converter.error
189
190
  };
190
191
  }
@@ -1,4 +1,4 @@
1
- import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST } from "./types.js";
1
+ import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN } from "./types.js";
2
2
  import { buildDelayedPreview } from "./buildDelayedPreview.js";
3
3
  import { CreditAccountState } from "./CreditAccountState.js";
4
4
  import { classifyCloseOrRepay, isCloseOrRepay } from "./detectCloseOrRepay.js";
@@ -10,4 +10,4 @@ import { replayMulticall } from "./replayMulticall.js";
10
10
  import { previewAdjustCreditAccount } from "./previewAdjustCreditAccount.js";
11
11
  import { previewCloseOrRepayCreditAccount } from "./previewCloseOrRepayCreditAccount.js";
12
12
  import { previewOperation } from "./previewOperation.js";
13
- export { CreditAccountState, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST, UnsupportedOperationError, buildDelayedPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, isCloseOrRepay, makeReplayState, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
13
+ export { CreditAccountState, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, UnsupportedOperationError, buildDelayedPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, isCloseOrRepay, makeReplayState, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -1,6 +1,7 @@
1
1
  import { AP_WETH_TOKEN } from "../../sdk/constants/address-provider.js";
2
+ import { DUST_THRESHOLD } from "../../sdk/constants/math.js";
2
3
  import "../../sdk/index.js";
3
- import { ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST } from "./types.js";
4
+ import { ERROR_UNPRICEABLE_TOKEN } from "./types.js";
4
5
  import { replayMulticall } from "./replayMulticall.js";
5
6
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
6
7
  //#region src/preview/preview/previewAdjustCreditAccount.ts
@@ -19,8 +20,8 @@ async function previewAdjustCreditAccount(input, operation, options) {
19
20
  let error = replayError;
20
21
  const { assets: collateralAdded, error: unwrapError } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
21
22
  error ??= unwrapError;
22
- const assets = account.balances.toAssets(PREVIEW_DUST);
23
- const assetsChange = account.balances.difference(before.balances).toAssets(PREVIEW_DUST);
23
+ const assets = account.balances.toAssets(DUST_THRESHOLD);
24
+ const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
24
25
  const totalValue = assets.reduce((acc, { token, balance }) => {
25
26
  try {
26
27
  return acc + market.priceOracle.convert(token, market.underlying, balance);
@@ -31,20 +31,5 @@ const ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP = 1005;
31
31
  const ERROR_INVALID_TRANSACTION_VALUE = 1006;
32
32
  /** A token in the preview could not be priced by the oracle */
33
33
  const ERROR_UNPRICEABLE_TOKEN = 2001;
34
- /**
35
- * Dust threshold for replayed preview balances and balance changes.
36
- *
37
- * Multicalls assembled by `CreditAccountsServiceV310` subtract a 10-unit
38
- * safety buffer from every expected output token in their
39
- * `storeExpectedBalances` deltas (`amount - 10n` in
40
- * `assembleStartDelayedWithdrawalCalls`/`assembleClaimDelayedCalls`), while
41
- * subsequent calls in the same multicall spend exact on-chain amounts. A
42
- * replay that credits only the min-guarantee can therefore be off by up to
43
- * 10 units per token, including small negative residues that are impossible
44
- * on-chain. Amounts within this threshold (in absolute value) are filtered
45
- * from preview outputs; anything beyond it is a genuine discrepancy and is
46
- * reported.
47
- */
48
- const PREVIEW_DUST = 10n;
49
34
  //#endregion
50
- export { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN, PREVIEW_DUST };
35
+ export { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPREVIEWABLE_RWA_WRAP_UNWRAP, ERROR_UNPRICEABLE_TOKEN };
@@ -10,6 +10,8 @@ import "./bots/index.js";
10
10
  import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
11
11
  import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
12
12
  import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
13
+ import { expectedBalanceDeltas } from "../market/credit/expectedBalanceDeltas.js";
14
+ import "../market/index.js";
13
15
  import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
14
16
  import "./credit-account-compressor/index.js";
15
17
  import { extractPriceUpdates, extractQuotaTokens, mergePriceUpdates } from "./multicall-utils.js";
@@ -173,49 +175,21 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
173
175
  * {@inheritDoc ICreditAccountsService.assembleStartDelayedWithdrawalCalls}
174
176
  **/
175
177
  assembleStartDelayedWithdrawalCalls({ creditFacade, preview }) {
176
- const record = preview.outputs.reduce((acc, o) => {
177
- const token = o.token.toLowerCase();
178
- acc[token] = (acc[token] || 0n) + o.amount;
179
- return acc;
180
- }, {});
181
- const deltas = Object.entries(record).filter(([, a]) => a > 10n).map(([token, amount]) => ({
182
- token,
183
- amount: amount > 10n ? amount - 10n : 0n
184
- }));
185
- if (preview.amountIn > 0n) deltas.push({
186
- token: preview.token,
187
- amount: -preview.amountIn
188
- });
189
- const facade = this.sdk.marketRegister.findCreditFacade(creditFacade);
190
- return [
191
- facade.prepareStoreExpectedBalances(deltas),
192
- ...preview.requestCalls,
193
- facade.prepareCompareBalances()
194
- ];
178
+ return this.sdk.marketRegister.findCreditFacade(creditFacade).prepareWithBalanceCheck(expectedBalanceDeltas({
179
+ outputs: preview.outputs,
180
+ spentToken: preview.token,
181
+ spentAmount: preview.amountIn
182
+ }), preview.requestCalls);
195
183
  }
196
184
  /**
197
185
  * {@inheritDoc ICreditAccountsService.assembleClaimDelayedCalls}
198
186
  **/
199
187
  assembleClaimDelayedCalls({ creditFacade, claimableNow }) {
200
- const record = claimableNow.outputs.reduce((acc, o) => {
201
- const token = o.token.toLowerCase();
202
- acc[token] = (acc[token] || 0n) + o.amount;
203
- return acc;
204
- }, {});
205
- const deltas = Object.entries(record).filter(([, a]) => a > 10n).map(([token, amount]) => ({
206
- token,
207
- amount: amount > 10n ? amount - 10n : 0n
208
- }));
209
- if (claimableNow.withdrawalTokenSpent > 0n) deltas.push({
210
- token: claimableNow.withdrawalPhantomToken,
211
- amount: -claimableNow.withdrawalTokenSpent
212
- });
213
- const facade = this.sdk.marketRegister.findCreditFacade(creditFacade);
214
- return [
215
- facade.prepareStoreExpectedBalances(deltas),
216
- ...claimableNow.claimCalls,
217
- facade.prepareCompareBalances()
218
- ];
188
+ return this.sdk.marketRegister.findCreditFacade(creditFacade).prepareWithBalanceCheck(expectedBalanceDeltas({
189
+ outputs: claimableNow.outputs,
190
+ spentToken: claimableNow.withdrawalPhantomToken,
191
+ spentAmount: claimableNow.withdrawalTokenSpent
192
+ }), claimableNow.claimCalls);
219
193
  }
220
194
  /**
221
195
  * {@inheritDoc ICreditAccountsService.getApprovalAddress}
@@ -9,12 +9,12 @@ import { hexEq } from "../../utils/hex.js";
9
9
  import "../../utils/index.js";
10
10
  import { SDKConstruct } from "../../base/SDKConstruct.js";
11
11
  import "../../base/index.js";
12
- import { iRWAFactoryAbi } from "../../../abi/rwa/iRWAFactory.js";
13
12
  import { borrowApyBps, healthFactorBps, positionLeverage, usdToNumber } from "../../market/math.js";
14
13
  import { dominantCollateral } from "../../market/credit/dominantCollateral.js";
15
14
  import { simulateWithPriceUpdates } from "../../utils/viem/simulateWithPriceUpdates.js";
16
15
  import "../../utils/viem/index.js";
17
16
  import "../../market/index.js";
17
+ import { iRWAFactoryAbi } from "../../../abi/rwa/iRWAFactory.js";
18
18
  import { CreditAccountCompressorV310Contract } from "./CreditAccountCompressorV310Contract.js";
19
19
  //#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressor.ts
20
20
  /**