@gearbox-protocol/sdk 16.0.0-next.50 → 16.0.0-next.52

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 (93) hide show
  1. package/dist/cjs/model/index.js +1 -0
  2. package/dist/cjs/model/result.js +10 -0
  3. package/dist/cjs/onchain/accounts/intents/leverage-band.js +1 -1
  4. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +8 -19
  5. package/dist/cjs/onchain/accounts/intents/open-strategy.js +1 -1
  6. package/dist/cjs/onchain/accounts/intents/realize.js +1 -1
  7. package/dist/cjs/onchain/accounts/intents/testing/market.js +6 -5
  8. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +21 -74
  9. package/dist/cjs/onchain/accounts/intents/utils/pick-token.js +1 -1
  10. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +2 -2
  11. package/dist/cjs/onchain/accounts/intents/utils/router-path.js +1 -1
  12. package/dist/cjs/onchain/accounts/intents/view.js +1 -1
  13. package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +3 -3
  14. package/dist/cjs/onchain/chain/chains.js +9 -3
  15. package/dist/cjs/onchain/index.js +1 -1
  16. package/dist/cjs/onchain/market/MarketSuite.js +0 -28
  17. package/dist/cjs/onchain/market/credit/collateralUtils.js +2 -2
  18. package/dist/cjs/onchain/market/index.js +1 -1
  19. package/dist/cjs/onchain/market/oracle/PriceOracleBaseContract.js +66 -13
  20. package/dist/cjs/onchain/market/oracle/TestPriceOracle.mock.js +215 -0
  21. package/dist/cjs/onchain/market/oracle/index.js +1 -1
  22. package/dist/cjs/onchain/positions/PositionsService.js +5 -7
  23. package/dist/cjs/onchain/positions/calcHealthFactor.js +4 -3
  24. package/dist/cjs/onchain/router/AbstractRouterContract.js +2 -24
  25. package/dist/cjs/onchain/router/RouterV310Contract.js +1 -12
  26. package/dist/cjs/preview/preview/buildDelayedStrategyPositionOperationPreview.js +26 -38
  27. package/dist/cjs/preview/preview/previewAdjustStrategyPosition.js +2 -3
  28. package/dist/cjs/preview/preview/previewExitOrRepayStrategyPosition.js +4 -5
  29. package/dist/cjs/preview/preview/previewOpenStrategyPosition.js +3 -7
  30. package/dist/cjs/preview/preview/previewOperation.js +1 -2
  31. package/dist/esm/dev/AccountOpener.js +1 -1
  32. package/dist/esm/dev/withdrawalUtils.js +1 -1
  33. package/dist/esm/model/index.js +2 -2
  34. package/dist/esm/model/result.js +10 -1
  35. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  36. package/dist/esm/onchain/accounts/intents/leverage-band.js +1 -1
  37. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +8 -19
  38. package/dist/esm/onchain/accounts/intents/open-strategy.js +1 -1
  39. package/dist/esm/onchain/accounts/intents/realize.js +1 -1
  40. package/dist/esm/onchain/accounts/intents/testing/market.js +6 -5
  41. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +22 -75
  42. package/dist/esm/onchain/accounts/intents/utils/pick-token.js +1 -1
  43. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +2 -2
  44. package/dist/esm/onchain/accounts/intents/utils/router-path.js +1 -1
  45. package/dist/esm/onchain/accounts/intents/view.js +1 -1
  46. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +4 -4
  47. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  48. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  49. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  50. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  51. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  52. package/dist/esm/onchain/chain/chains.js +9 -3
  53. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  54. package/dist/esm/onchain/index.js +1 -1
  55. package/dist/esm/onchain/market/MarketSuite.js +0 -28
  56. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  57. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  58. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  59. package/dist/esm/onchain/market/credit/collateralUtils.js +2 -2
  60. package/dist/esm/onchain/market/index.js +1 -1
  61. package/dist/esm/onchain/market/oracle/PriceOracleBaseContract.js +66 -13
  62. package/dist/esm/onchain/market/oracle/TestPriceOracle.mock.js +213 -0
  63. package/dist/esm/onchain/market/oracle/index.js +1 -1
  64. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  65. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  66. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  67. package/dist/esm/onchain/positions/PositionsService.js +5 -7
  68. package/dist/esm/onchain/positions/calcHealthFactor.js +4 -3
  69. package/dist/esm/onchain/router/AbstractRouterContract.js +2 -24
  70. package/dist/esm/onchain/router/RouterV310Contract.js +1 -12
  71. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  72. package/dist/esm/preview/preview/buildDelayedStrategyPositionOperationPreview.js +26 -38
  73. package/dist/esm/preview/preview/previewAdjustStrategyPosition.js +2 -3
  74. package/dist/esm/preview/preview/previewExitOrRepayStrategyPosition.js +4 -5
  75. package/dist/esm/preview/preview/previewOpenStrategyPosition.js +3 -7
  76. package/dist/esm/preview/preview/previewOperation.js +1 -2
  77. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  78. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  79. package/dist/types/model/index.d.ts +2 -2
  80. package/dist/types/model/previews.d.ts +4 -3
  81. package/dist/types/model/result.d.ts +16 -1
  82. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +5 -3
  83. package/dist/types/onchain/accounts/intents/testing/market.d.ts +5 -1
  84. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +1 -2
  85. package/dist/types/onchain/index.d.ts +2 -2
  86. package/dist/types/onchain/market/MarketSuite.d.ts +2 -29
  87. package/dist/types/onchain/market/index.d.ts +2 -2
  88. package/dist/types/onchain/market/oracle/PriceOracleBaseContract.d.ts +15 -5
  89. package/dist/types/onchain/market/oracle/types.d.ts +40 -28
  90. package/dist/types/onchain/positions/calcHealthFactor.d.ts +7 -3
  91. package/dist/types/onchain/router/AbstractRouterContract.d.ts +0 -4
  92. package/dist/types/preview/preview/buildDelayedStrategyPositionOperationPreview.d.ts +4 -6
  93. package/package.json +2 -10
@@ -128,6 +128,7 @@ exports.responseMetadataSchema = require_model_response_schema.responseMetadataS
128
128
  exports.responseSchema = require_model_response_schema.responseSchema;
129
129
  exports.rewardsPnLSchema = require_model_positions_schema.rewardsPnLSchema;
130
130
  exports.rewardsSchema = require_model_opportunities_schema.rewardsSchema;
131
+ exports.safeValue = require_model_result.safeValue;
131
132
  exports.sdkErr = require_model_result.sdkErr;
132
133
  exports.sdkOk = require_model_result.sdkOk;
133
134
  exports.strategyOpportunityChartMetricSchema = require_model_charts_schema.strategyOpportunityChartMetricSchema;
@@ -1,5 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  //#region src/model/result.ts
3
+ /**
4
+ * Builds a {@link SafeValue}. Omits `error` when the value was not degraded.
5
+ **/
6
+ function safeValue(value, error) {
7
+ return error === void 0 ? { value } : {
8
+ value,
9
+ error
10
+ };
11
+ }
3
12
  /** The success half, built. */
4
13
  function sdkOk(data) {
5
14
  return {
@@ -23,5 +32,6 @@ function isSDKError(answer) {
23
32
  }
24
33
  //#endregion
25
34
  exports.isSDKError = isSDKError;
35
+ exports.safeValue = safeValue;
26
36
  exports.sdkErr = sdkErr;
27
37
  exports.sdkOk = sdkOk;
@@ -37,7 +37,7 @@ function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
37
37
  if (!target) return;
38
38
  const ceiling = suite.creditManager.maxLeverage(target, targetHF);
39
39
  const underlying = market.pool.underlying;
40
- const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount) ?? 0n;
40
+ const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
41
41
  const netValue = collateral.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
42
42
  if (netValue <= 0n) return {
43
43
  min: 1,
@@ -12,9 +12,11 @@ const require_onchain_accounts_intents_utils_common = require("./utils/common.js
12
12
  * check counts: a holding backed by a quota contributes the lesser of the
13
13
  * quota and its threshold-weighted value, an unquoted one — the underlying —
14
14
  * its weighted value alone, and dust or a disabled balance nothing at all.
15
- * Collateral is valued at the lower of its two feeds, the way the facade
16
- * values a call that hands funds over; the debt is valued at the main feed,
17
- * as the check does. Zero debt frees the whole balance.
15
+ * Collateral is valued at the protocol safe price (`min` of the two feeds,
16
+ * 0 when there is no reserve), the way the facade values a call that hands
17
+ * funds over; the underlying is exempt and is valued at the main feed, as
18
+ * `CreditManagerV3._safeConvertToUSD` does. The debt is valued at the main
19
+ * feed, as the check does. Zero debt frees the whole balance.
18
20
  *
19
21
  * Rounding always favours the account, so the answer clears the check rather
20
22
  * than landing a wei short of it.
@@ -37,7 +39,7 @@ function maxWithdrawCollateral(props) {
37
39
  /** What a holding backs, in the check's units: USD × PERCENTAGE_FACTOR. */
38
40
  const weigh = (t) => {
39
41
  const lt = BigInt(creditManager.liquidationThresholds.get(t.token) ?? 0);
40
- const weighted = (safeUsd(priceOracle, t.token, t.balance) ?? 0n) * lt;
42
+ const weighted = (require_onchain_accounts_intents_utils_common.eq(t.token, underlying) ? usd(priceOracle, t.token, t.balance) ?? 0n : priceOracle.safeConvertMinUSD(t.token, t.balance).value) * lt;
41
43
  if (t.quota === 0n) return weighted;
42
44
  return require_onchain_utils_bigint_math.BigIntMath.min(quotaUsd(t) * require_onchain_constants_math.PERCENTAGE_FACTOR, weighted);
43
45
  };
@@ -55,8 +57,8 @@ function maxWithdrawCollateral(props) {
55
57
  const shortfall = required - otherMoney;
56
58
  if (target.quota > 0n && quotaUsd(target) * 10000n < shortfall) return 0n;
57
59
  const targetLt = BigInt(creditManager.liquidationThresholds.get(target.token) ?? 0);
58
- const targetUsd = safeUsd(priceOracle, target.token, target.balance);
59
- if (targetLt === 0n || !targetUsd) return 0n;
60
+ const targetUsd = require_onchain_accounts_intents_utils_common.eq(target.token, underlying) ? usd(priceOracle, target.token, target.balance) ?? 0n : priceOracle.safeConvertMinUSD(target.token, target.balance).value;
61
+ if (targetLt === 0n || targetUsd === 0n) return 0n;
60
62
  const keptUsd = require_onchain_utils_bigint_math.BigIntMath.ceilDiv(shortfall, targetLt);
61
63
  const kept = require_onchain_utils_bigint_math.BigIntMath.ceilDiv(target.balance * keptUsd, targetUsd);
62
64
  return kept >= target.balance ? 0n : target.balance - kept;
@@ -69,18 +71,5 @@ function usd(oracle, token, amount) {
69
71
  return;
70
72
  }
71
73
  }
72
- /**
73
- * USD value at the lower of the token's two feeds — what a call handing funds
74
- * over is judged at. Falls back to the main feed where there is no second one.
75
- **/
76
- function safeUsd(oracle, token, amount) {
77
- const main = usd(oracle, token, amount);
78
- if (main === void 0) return;
79
- try {
80
- return require_onchain_utils_bigint_math.BigIntMath.min(main, oracle.convertToUSD(token, amount, true));
81
- } catch {
82
- return main;
83
- }
84
- }
85
74
  //#endregion
86
75
  exports.maxWithdrawCollateral = maxWithdrawCollateral;
@@ -28,7 +28,7 @@ async function buildOpenStrategyState(props) {
28
28
  const market = sdk.marketRegister.findByCreditManager(creditManager);
29
29
  require_onchain_accounts_intents_guards.assertMarketOperable(suite);
30
30
  const underlying = market.pool.underlying.toLowerCase();
31
- const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount) ?? 0n;
31
+ const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
32
32
  const margin = collateral.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
33
33
  if (margin <= 0n) throw new require_onchain_validation_refusal.IntentPreviewError("insufficientSourceBalance", void 0, "openStrategy: collateral is worth nothing in underlying");
34
34
  const debt = require_onchain_accounts_intents_math.debtForLeverage(margin, leverage);
@@ -30,7 +30,7 @@ async function realize(steps, props) {
30
30
  slippage
31
31
  });
32
32
  const market = sdk.marketRegister.findByCreditManager(creditAccount.creditManager);
33
- const price = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount) ?? 0n;
33
+ const price = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
34
34
  const suite = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
35
35
  const start = {
36
36
  initialAssets: creditAccount.tokens,
@@ -78,12 +78,13 @@ const LIQUIDATION_THRESHOLDS = {
78
78
  const MAX_DEBT = require_onchain_utils_formatter.toBN("200000", 8);
79
79
  /** Mock SDK on the shared fixture market. */
80
80
  function buildMarketSdk(extras) {
81
+ const prices = {
82
+ ...PRICES,
83
+ ...extras?.extraPrices
84
+ };
81
85
  return require_sdk_mock.buildMockSdk({
82
- prices: {
83
- ...PRICES,
84
- ...extras?.extraPrices
85
- },
86
- reservePrices: extras?.reservePrices,
86
+ prices,
87
+ reservePrices: extras?.reservePrices ?? prices,
87
88
  decimals: {
88
89
  ...DECIMALS,
89
90
  ...extras?.extraDecimals
@@ -2,8 +2,8 @@ require("../../../constants/math.js");
2
2
  require("../../../constants/index.js");
3
3
  const require_onchain_market_math = require("../../../market/math.js");
4
4
  const require_onchain_market_credit_CreditSuite = require("../../../market/credit/CreditSuite.js");
5
- const require_onchain_market_MarketSuite = require("../../../market/MarketSuite.js");
6
5
  const require_onchain_positions_PositionsService = require("../../../positions/PositionsService.js");
6
+ const require_TestPriceOracle_mock = require("../../../market/oracle/TestPriceOracle.mock.js");
7
7
  let vitest = require("vitest");
8
8
  //#region src/onchain/accounts/intents/testing/sdk-mock.ts
9
9
  /**
@@ -94,27 +94,25 @@ function echoEncodableOpCalls(op) {
94
94
  /**
95
95
  * Mock `OnchainSDK` covering exactly what the intent-service touches:
96
96
  * price conversion, quota params, CM/facade lookup and call assembly.
97
- * Conversion mirrors the legacy price-based math:
98
- * `amount * price[from] * 10^dec(to) / (price[to] * 10^dec(from))`.
97
+ * Conversion is a real {@link TestPriceOracle} seeded from the fixture records.
99
98
  */
100
99
  function buildMockSdk(args) {
101
100
  const decimalsOf = (token) => args.decimals[token.toLowerCase()] ?? 18;
102
- const convert = (token, to, amount) => {
103
- const from = token.toLowerCase();
104
- const target = to.toLowerCase();
105
- if (from === target) return amount;
106
- const fromPrice = args.prices[from];
107
- const toPrice = args.prices[target];
108
- if (fromPrice === void 0 || toPrice === void 0) throw new Error(`mock priceOracle: missing price for ${from} or ${target}`);
109
- return amount * fromPrice * 10n ** BigInt(decimalsOf(target)) / (toPrice * 10n ** BigInt(decimalsOf(from)));
110
- };
111
- const safeConvert = (token, to, amount) => {
112
- try {
113
- return convert(token, to, amount);
114
- } catch {
115
- return null;
116
- }
101
+ const lookup = (record, token) => record?.[token.toLowerCase()] ?? record?.[token];
102
+ const tokenCfgs = {};
103
+ for (const token of /* @__PURE__ */ new Set([
104
+ ...Object.keys(args.decimals),
105
+ ...Object.keys(args.prices),
106
+ ...Object.keys(args.reservePrices ?? {})
107
+ ])) tokenCfgs[token] = {
108
+ decimals: lookup(args.decimals, token) ?? 18,
109
+ symbol: "TOKEN",
110
+ name: "TOKEN",
111
+ price: lookup(args.prices, token),
112
+ reservePrice: lookup(args.reservePrices, token)
117
113
  };
114
+ const priceOracle = new require_TestPriceOracle_mock.TestPriceOracle(tokenCfgs);
115
+ const convert = (from, to, amount) => priceOracle.convert(from, to, amount);
118
116
  const fullQuota = (q) => ({
119
117
  cumulativeIndexLU: 0n,
120
118
  totalQuoted: 0n,
@@ -133,18 +131,6 @@ function buildMockSdk(args) {
133
131
  entries: () => Object.entries(args.liquidationThresholds),
134
132
  get: (token) => args.liquidationThresholds[token.toLowerCase()] ?? args.liquidationThresholds[token]
135
133
  };
136
- const _convertToUSD = (token, amount, reserve = false) => {
137
- const key = token.toLowerCase();
138
- const price = reserve ? args.reservePrices?.[key] : args.prices[key];
139
- if (price === void 0) throw new Error(`mock priceOracle: missing ${reserve ? "reserve" : "main"} price for ${token}`);
140
- return amount * price / 10n ** BigInt(decimalsOf(token));
141
- };
142
- const safeUsd = (token, amount) => {
143
- const from = token.toLowerCase();
144
- const price = args.prices[from] ?? args.prices[token];
145
- if (price === void 0) return null;
146
- return amount * price / 10n ** BigInt(decimalsOf(from));
147
- };
148
134
  const tokenOf = (token) => ({
149
135
  chainId: 1,
150
136
  address: token,
@@ -152,57 +138,19 @@ function buildMockSdk(args) {
152
138
  name: "TOKEN",
153
139
  decimals: decimalsOf(token)
154
140
  });
155
- const mainPriceOf = (token) => {
156
- const key = token.toLowerCase();
157
- const price = args.prices[key] ?? args.prices[token];
158
- if (price === void 0) throw new Error(`mock priceOracle: missing main price for ${token}`);
159
- return price;
160
- };
161
- const reservePriceOf = (token) => {
162
- const key = token.toLowerCase();
163
- const price = args.reservePrices?.[key] ?? args.reservePrices?.[token];
164
- if (price === void 0) throw new Error(`mock priceOracle: missing reserve price for ${token}`);
165
- return price;
166
- };
167
141
  const poolPaused = args.poolPaused ?? false;
168
142
  /** {@inheritDoc MarketSuite.toUnderlyingAmount} */
169
- const toUnderlyingAmount = (value) => {
170
- const usd = safeUsd(args.underlying, value);
171
- return {
172
- token: tokenOf(args.rwaAssets?.[args.underlying.toLowerCase()] ?? args.underlying),
173
- value,
174
- valueUsd: usd === null ? null : require_onchain_market_math.usdToNumber(usd)
175
- };
176
- };
143
+ const toUnderlyingAmount = (value) => ({
144
+ token: tokenOf(args.rwaAssets?.[args.underlying.toLowerCase()] ?? args.underlying),
145
+ ...priceOracle.toAmount(args.underlying, value)
146
+ });
177
147
  const market = {
178
148
  toUnderlyingAmount,
179
149
  /** {@inheritDoc MarketSuite.curator} */
180
150
  curator: MOCK_CURATOR,
181
151
  /** {@inheritDoc MarketSuite.underlying} */
182
152
  underlying: args.underlying,
183
- priceOracle: {
184
- convert,
185
- safeConvert,
186
- mainPrice: mainPriceOf,
187
- reservePrice: reservePriceOf,
188
- convertToUSD: _convertToUSD,
189
- toAmount: (token, value) => {
190
- const usd = safeUsd(token, value);
191
- return {
192
- value,
193
- valueUsd: usd === null ? null : require_onchain_market_math.usdToNumber(usd)
194
- };
195
- },
196
- toTokenAmount: (token, value) => {
197
- const usd = safeUsd(token, value);
198
- return {
199
- token: tokenOf(token),
200
- value,
201
- valueUsd: usd === null ? null : require_onchain_market_math.usdToNumber(usd)
202
- };
203
- },
204
- safeConvertToUSD: safeUsd
205
- },
153
+ priceOracle,
206
154
  pool: {
207
155
  pqk: {
208
156
  quotas,
@@ -222,7 +170,6 @@ function buildMockSdk(args) {
222
170
  underlying: args.underlying
223
171
  }
224
172
  };
225
- Object.assign(market, { valueInUnderlying: require_onchain_market_MarketSuite.MarketSuite.prototype.valueInUnderlying });
226
173
  const collateralTokens = [args.underlying.toLowerCase(), ...Object.keys(args.liquidationThresholds).map((t) => t.toLowerCase()).filter((t) => t !== args.underlying.toLowerCase())];
227
174
  const forbidden = new Set((args.forbiddenTokens ?? []).map((t) => t.toLowerCase()));
228
175
  const forbiddenTokensMask = collateralTokens.reduce((mask, token, i) => forbidden.has(token) ? mask | 1n << BigInt(i) : mask, 0n);
@@ -37,7 +37,7 @@ function isRedemptionPhantomToken(sdk, token) {
37
37
  function rankAccountTokens(args) {
38
38
  const { creditAccount, sdk, exclude = [] } = args;
39
39
  const oracle = sdk.marketRegister.findByCreditManager(creditAccount.creditManager).priceOracle;
40
- const convert = (from, to, amount) => oracle.safeConvert(from, to, amount) ?? 0n;
40
+ const convert = (from, to, amount) => oracle.safeConvert(from, to, amount).value;
41
41
  const candidates = [];
42
42
  for (const t of creditAccount.tokens) {
43
43
  if (t.balance <= 0n) continue;
@@ -15,8 +15,8 @@ function probeBasket(balances, oracle) {
15
15
  let basketWad = 0n;
16
16
  for (const asset of balances) {
17
17
  if (asset.balance <= 0n) continue;
18
- const usd = oracle.safeConvertToUSD(asset.token, asset.balance);
19
- if (usd !== null && usd > 0n) basketWad += usd * require_onchain_constants_math.WAD / require_onchain_constants_math.PRICE_DECIMALS;
18
+ const usd = oracle.safeConvertToUSD(asset.token, asset.balance).value;
19
+ if (usd > 0n) basketWad += usd * require_onchain_constants_math.WAD / require_onchain_constants_math.PRICE_DECIMALS;
20
20
  }
21
21
  if (basketWad <= 0n) return;
22
22
  const probeWad = PROBE_UNIT_USD_WAD;
@@ -152,7 +152,7 @@ function createRouterPaths(args) {
152
152
  function createOraclePaths(args) {
153
153
  const { sdk, creditAccount } = args;
154
154
  const oracle = sdk.marketRegister.findByCreditManager(creditAccount.creditManager).priceOracle;
155
- const price = (from, to, amount) => oracle.safeConvert(from, to, amount) ?? 0n;
155
+ const price = (from, to, amount) => oracle.safeConvert(from, to, amount).value;
156
156
  const estimate = (amount) => ({
157
157
  amount,
158
158
  minAmount: amount,
@@ -12,7 +12,7 @@ const require_onchain_accounts_intents_utils_pick_token = require("./utils/pick-
12
12
  function accountView(creditAccount, sdk) {
13
13
  const { underlying, creditManager } = creditAccount;
14
14
  const oracle = sdk.marketRegister.findByCreditManager(creditManager).priceOracle;
15
- const price = (from, to, amount) => oracle.safeConvert(from, to, amount) ?? 0n;
15
+ const price = (from, to, amount) => oracle.safeConvert(from, to, amount).value;
16
16
  const { creditFacade } = sdk.marketRegister.findCreditManager(creditManager);
17
17
  let totalValue = 0n;
18
18
  for (const t of creditAccount.tokens) totalValue += price(t.token, underlying, t.balance);
@@ -149,11 +149,11 @@ var LiquidationsService = class extends require_onchain_base_SDKConstruct.SDKCon
149
149
  #anyMarketTokenAmount(token, value) {
150
150
  const meta = this.sdk.tokensMeta.mustGetToken(token);
151
151
  for (const market of this.sdk.marketRegister.markets) {
152
- const valueUsd = market.priceOracle.safeUsdValue(token, value);
153
- if (valueUsd !== null) return {
152
+ const priced = market.priceOracle.safeConvertToUSD(token, value);
153
+ if (!priced.error) return {
154
154
  token: meta,
155
155
  value,
156
- valueUsd
156
+ valueUsd: require_onchain_market_math.usdToNumber(priced.value)
157
157
  };
158
158
  }
159
159
  return {
@@ -114,7 +114,11 @@ const chains = {
114
114
  "0xa4c644f3180d10cd3b2121d455a2a88e1bda2928",
115
115
  "0xb79d6544839d169869476589d2e54014a074317b",
116
116
  "0xc307a074bd5aec2d6ad1d9b74465c24a59b490fd",
117
- "0xf5edc34204e67e592bdcb84114571c9e4bd0bdf7"
117
+ "0xf5edc34204e67e592bdcb84114571c9e4bd0bdf7",
118
+ "0x29350A3C2627FB78C7E915cd59AF754edf8998c5",
119
+ "0x5A93bc6983F80f5c55675eA4e77bb46DdC9665e8",
120
+ "0x5415092F06403F30486EF846dBAE0532c6Bd8759",
121
+ "0x9D866298f6B8E168a06e313D47059f2C097A92F1"
118
122
  ]),
119
123
  isPublic: true,
120
124
  wellKnownToken: {
@@ -226,7 +230,8 @@ const chains = {
226
230
  sunsetPools: new require_onchain_utils_AddressSet.AddressSet([
227
231
  "0x09cA6b76276eC0682adb896418b99CB7E44a58A0",
228
232
  "0x34752948B0dc28969485Df2066fFE86D5dc36689",
229
- "0x164A35F31e4E0F6c45D500962a6978D2cbD5a16b"
233
+ "0x164A35F31e4E0F6c45D500962a6978D2cbD5a16b",
234
+ "0xc4173359087CE643235420b7bC610d9B0CF2B82D"
230
235
  ]),
231
236
  sunsetStrategies: new require_onchain_utils_AddressSet.AddressSet([
232
237
  "0xA1F05494Dab74Eb9C352C3A042836579fE168aa7",
@@ -236,7 +241,8 @@ const chains = {
236
241
  "0xb21f766c193541305C18cE146DCD3Fdf642b40eF",
237
242
  "0x04620081bb818B8CD3996943D0A4a37Dbf296cF4",
238
243
  "0x5452971Fc17d025a1AFFDd5F7a44CCDD1BF0524C",
239
- "0x7ea06087C63568f1071c6BEA3AeB51e070ec68B9"
244
+ "0x7ea06087C63568f1071c6BEA3AeB51e070ec68B9",
245
+ "0x06F5b5062477DCf6723c30a76232A5C0B6FCb01A"
240
246
  ]),
241
247
  rwaFactories: [],
242
248
  isPublic: true,
@@ -170,9 +170,9 @@ const require_onchain_market_pricefeeds_WstETHPriceFeed = require("./market/pric
170
170
  const require_onchain_market_pricefeeds_YearnPriceFeed = require("./market/pricefeeds/YearnPriceFeed.js");
171
171
  const require_onchain_market_pricefeeds_ZeroPriceFeed = require("./market/pricefeeds/ZeroPriceFeed.js");
172
172
  const require_onchain_market_pricefeeds_PriceFeedsRegister = require("./market/pricefeeds/PriceFeedsRegister.js");
173
+ const require_onchain_market_oracle_errors = require("./market/oracle/errors.js");
173
174
  const require_onchain_market_oracle_PriceOracleV310Contract = require("./market/oracle/PriceOracleV310Contract.js");
174
175
  const require_onchain_market_oracle_createPriceOracle = require("./market/oracle/createPriceOracle.js");
175
- const require_onchain_market_oracle_errors = require("./market/oracle/errors.js");
176
176
  const require_onchain_market_pool_GaugeContract = require("./market/pool/GaugeContract.js");
177
177
  const require_onchain_market_pool_LinearInterestRateModelContract = require("./market/pool/LinearInterestRateModelContract.js");
178
178
  const require_onchain_market_pool_PoolV310Contract = require("./market/pool/PoolV310Contract.js");
@@ -1,8 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_utils_AddressMap = require("../utils/AddressMap.js");
3
3
  const require_onchain_chain_chains = require("../chain/chains.js");
4
- const require_onchain_constants_math = require("../constants/math.js");
5
- require("../constants/index.js");
6
4
  require("../utils/index.js");
7
5
  const require_onchain_base_SDKConstruct = require("../base/SDKConstruct.js");
8
6
  require("../base/index.js");
@@ -153,32 +151,6 @@ var MarketSuite = class extends require_onchain_base_SDKConstruct.SDKConstruct {
153
151
  ...this.priceOracle.toAmount(this.underlying, value)
154
152
  });
155
153
  /**
156
- * Sums `assets` in this market's underlying at latest oracle prices.
157
- *
158
- * Balances at or below `minBalance` are ignored. A token the oracle cannot
159
- * price contributes nothing; the first such token is {@link ValueInUnderlying.unpriceable}.
160
- *
161
- * The counterpart of {@link toUnderlyingAmount}: that method labels a figure
162
- * already in underlying, this one produces the figure from mixed holdings.
163
- **/
164
- valueInUnderlying(assets, minBalance = require_onchain_constants_math.DUST_THRESHOLD) {
165
- let unpriceable;
166
- let value = 0n;
167
- for (const { token, balance } of assets) {
168
- if (balance <= minBalance) continue;
169
- const converted = this.priceOracle.safeConvert(token, this.underlying, balance);
170
- if (converted === null) {
171
- unpriceable ??= token;
172
- continue;
173
- }
174
- value += converted;
175
- }
176
- return unpriceable === void 0 ? { value } : {
177
- value,
178
- unpriceable
179
- };
180
- }
181
- /**
182
154
  * Display name of this market's pool, e.g. `"USDC Pool"`.
183
155
  */
184
156
  get poolName() {
@@ -67,11 +67,11 @@ function pickStrategyTargetCollateral(tokens) {
67
67
  * nothing but its underlying, or nothing the oracle can price.
68
68
  **/
69
69
  function dominantCollateral(account, market) {
70
- let bestValue = 0;
70
+ let bestValue = 0n;
71
71
  let dominant;
72
72
  for (const t of account.tokens) {
73
73
  if ((0, viem.isAddressEqual)(t.token, account.underlying) || (t.mask & account.enabledTokensMask) === 0n || t.balance <= 10n) continue;
74
- const value = market.priceOracle.safeUsdValue(t.token, t.balance) ?? 0;
74
+ const value = market.priceOracle.safeConvertToUSD(t.token, t.balance).value;
75
75
  if (value > bestValue) {
76
76
  bestValue = value;
77
77
  dominant = t.token;
@@ -120,9 +120,9 @@ const require_onchain_market_pricefeeds_YearnPriceFeed = require("./pricefeeds/Y
120
120
  const require_onchain_market_pricefeeds_ZeroPriceFeed = require("./pricefeeds/ZeroPriceFeed.js");
121
121
  const require_onchain_market_pricefeeds_PriceFeedsRegister = require("./pricefeeds/PriceFeedsRegister.js");
122
122
  require("./pricefeeds/index.js");
123
+ const require_onchain_market_oracle_errors = require("./oracle/errors.js");
123
124
  const require_onchain_market_oracle_PriceOracleV310Contract = require("./oracle/PriceOracleV310Contract.js");
124
125
  const require_onchain_market_oracle_createPriceOracle = require("./oracle/createPriceOracle.js");
125
- const require_onchain_market_oracle_errors = require("./oracle/errors.js");
126
126
  require("./oracle/index.js");
127
127
  const require_onchain_market_pool_GaugeContract = require("./pool/GaugeContract.js");
128
128
  const require_onchain_market_pool_LinearInterestRateModelContract = require("./pool/LinearInterestRateModelContract.js");
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_utils_AddressMap = require("../../utils/AddressMap.js");
3
3
  const require_onchain_utils_AddressSet = require("../../utils/AddressSet.js");
4
+ const require_onchain_utils_bigint_math = require("../../utils/bigint-math.js");
4
5
  const require_onchain_constants_address_provider = require("../../constants/address-provider.js");
5
6
  const require_onchain_constants_addresses = require("../../constants/addresses.js");
6
7
  require("../../constants/math.js");
@@ -11,10 +12,13 @@ require("../../utils/index.js");
11
12
  const require_onchain_base_BaseContract = require("../../base/BaseContract.js");
12
13
  require("../../base/index.js");
13
14
  const require_onchain_market_math = require("../math.js");
15
+ const require_model_result = require("../../../model/result.js");
16
+ require("../../../model/index.js");
14
17
  const require_abi_compressors_priceFeedCompressor = require("../../../abi/compressors/priceFeedCompressor.js");
15
18
  const require_onchain_market_pricefeeds_PriceFeedRef = require("../pricefeeds/PriceFeedRef.js");
16
19
  const require_onchain_market_pricefeeds_getRawPriceUpdates = require("../pricefeeds/getRawPriceUpdates.js");
17
20
  require("../pricefeeds/index.js");
21
+ const require_onchain_market_oracle_errors = require("./errors.js");
18
22
  const require_onchain_market_oracle_PriceFeedAnswerMap = require("./PriceFeedAnswerMap.js");
19
23
  let viem = require("viem");
20
24
  let date_fns = require("date-fns");
@@ -142,10 +146,13 @@ var PriceOracleBaseContract = class extends require_onchain_base_BaseContract.Ba
142
146
  **/
143
147
  safeConvert(from, to, amount) {
144
148
  try {
145
- return this.convert(from, to, amount);
146
- } catch (e) {
147
- this.logger?.debug(`cannot convert ${this.labelAddress(from)} to ${this.labelAddress(to)}: ${e}`);
148
- return null;
149
+ return { value: this.convert(from, to, amount) };
150
+ } catch {
151
+ try {
152
+ return { value: this.convert(from, to, amount, true) };
153
+ } catch {
154
+ return require_model_result.safeValue(0n, require_onchain_market_oracle_errors.unpriceableTokenError(from));
155
+ }
149
156
  }
150
157
  }
151
158
  /**
@@ -153,26 +160,72 @@ var PriceOracleBaseContract = class extends require_onchain_base_BaseContract.Ba
153
160
  **/
154
161
  safeConvertToUSD(token, amount) {
155
162
  try {
156
- return this.convertToUSD(token, amount);
157
- } catch (e) {
158
- this.logger?.debug(`cannot price ${this.labelAddress(token)}: ${e}`);
159
- return null;
163
+ return { value: this.convertToUSD(token, amount) };
164
+ } catch {
165
+ try {
166
+ return { value: this.convertToUSD(token, amount, true) };
167
+ } catch {
168
+ return require_model_result.safeValue(0n, require_onchain_market_oracle_errors.unpriceableTokenError(token));
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * {@inheritDoc IPriceOracleContract.safeConvertMinUSD}
174
+ **/
175
+ safeConvertMinUSD(token, amount) {
176
+ let main;
177
+ try {
178
+ main = this.convertToUSD(token, amount);
179
+ } catch {
180
+ return require_model_result.safeValue(0n, require_onchain_market_oracle_errors.unpriceableTokenError(token));
181
+ }
182
+ let feedToken = token;
183
+ if ((0, viem.isAddressEqual)(token, "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE")) try {
184
+ feedToken = this.sdk.addressProvider.getAddress(require_onchain_constants_address_provider.AP_WETH_TOKEN, 0);
185
+ } catch {}
186
+ if (!this.reservePriceFeeds.has(feedToken)) return { value: 0n };
187
+ try {
188
+ return { value: require_onchain_utils_bigint_math.BigIntMath.min(main, this.convertToUSD(token, amount, true)) };
189
+ } catch {
190
+ return require_model_result.safeValue(0n, require_onchain_market_oracle_errors.unpriceableTokenError(token));
191
+ }
192
+ }
193
+ /**
194
+ * {@inheritDoc IPriceOracleContract.safeConvertFromUSD}
195
+ **/
196
+ safeConvertFromUSD(token, amount) {
197
+ try {
198
+ return { value: this.convertFromUSD(token, amount) };
199
+ } catch {
200
+ try {
201
+ return { value: this.convertFromUSD(token, amount, true) };
202
+ } catch {
203
+ return require_model_result.safeValue(0n, require_onchain_market_oracle_errors.unpriceableTokenError(token));
204
+ }
160
205
  }
161
206
  }
162
207
  /**
163
- * {@inheritDoc IPriceOracleContract.safeUsdValue}
208
+ * {@inheritDoc IPriceOracleContract.safeConvertAssets}
164
209
  **/
165
- safeUsdValue(token, amount) {
166
- const usd = this.safeConvertToUSD(token, amount);
167
- return usd === null ? null : require_onchain_market_math.usdToNumber(usd);
210
+ safeConvertAssets(assets, to) {
211
+ let value = 0n;
212
+ let error;
213
+ for (const { token, balance } of assets) {
214
+ if (balance <= 10n) continue;
215
+ const converted = this.safeConvert(token, to, balance);
216
+ value += converted.value;
217
+ error ??= converted.error;
218
+ }
219
+ return require_model_result.safeValue(value, error);
168
220
  }
169
221
  /**
170
222
  * {@inheritDoc IPriceOracleContract.toAmount}
171
223
  **/
172
224
  toAmount = (token, value) => {
225
+ const priced = this.safeConvertToUSD(token, value);
173
226
  return {
174
227
  value,
175
- valueUsd: this.safeUsdValue(token, value)
228
+ valueUsd: priced.error ? null : require_onchain_market_math.usdToNumber(priced.value)
176
229
  };
177
230
  };
178
231
  /**