@gearbox-protocol/sdk 18.2.0-next.1 → 18.2.0-next.11

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 (135) hide show
  1. package/dist/cjs/abi/compressors/subcompressors/liquidation/treehouseLiquidationSubcompressor.js +179 -0
  2. package/dist/cjs/abi/compressors/subcompressors/withdrawal/treehouseWithdrawalSubcompressor.js +534 -0
  3. package/dist/cjs/abi/router/treehouseWorker.js +885 -0
  4. package/dist/cjs/dev/AccountOpener.js +1 -1
  5. package/dist/cjs/dev/withdrawalUtils.js +1 -1
  6. package/dist/cjs/history/trace/extractTransfers.js +1 -1
  7. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  8. package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  9. package/dist/cjs/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -2
  10. package/dist/cjs/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -2
  11. package/dist/cjs/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -2
  12. package/dist/cjs/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  13. package/dist/cjs/onchain/base/TokensMeta.js +3 -3
  14. package/dist/cjs/onchain/core/createAddressProvider.js +1 -1
  15. package/dist/cjs/onchain/market/adapters/abi/actionAbi.js +1 -0
  16. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +3 -0
  17. package/dist/cjs/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  18. package/dist/cjs/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  19. package/dist/cjs/onchain/market/adapters/types.js +3 -0
  20. package/dist/cjs/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  21. package/dist/cjs/onchain/market/pool/PoolV310Contract.js +1 -1
  22. package/dist/cjs/onchain/market/rwa/createDegenNFT.js +1 -1
  23. package/dist/cjs/onchain/market/zapper/IETHZapperContract.js +1 -2
  24. package/dist/cjs/onchain/market/zapper/ZapperContract.js +1 -1
  25. package/dist/cjs/onchain/preview/preview/previewPoolPositionOperation.js +2 -2
  26. package/dist/cjs/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  27. package/dist/cjs/permissionless/api/index.js +26 -0
  28. package/dist/cjs/permissionless/api/oracles/PermissionlessOracles.js +585 -47
  29. package/dist/cjs/permissionless/api/oracles/enrich.js +99 -0
  30. package/dist/cjs/permissionless/api/oracles/index.js +28 -0
  31. package/dist/cjs/permissionless/api/oracles/schemas.js +102 -35
  32. package/dist/cjs/permissionless/api/oracles/score/formula.js +99 -0
  33. package/dist/cjs/permissionless/api/oracles/score/index.js +8 -0
  34. package/dist/cjs/permissionless/api/oracles/score/run.js +88 -0
  35. package/dist/cjs/permissionless/api/oracles/score/types.js +1 -0
  36. package/dist/cjs/permissionless/api/oracles/stress/classify.js +258 -0
  37. package/dist/cjs/permissionless/api/oracles/stress/index.js +22 -0
  38. package/dist/cjs/permissionless/api/oracles/stress/override.js +125 -0
  39. package/dist/cjs/permissionless/api/oracles/stress/run.js +432 -0
  40. package/dist/cjs/permissionless/api/oracles/stress/score.js +98 -0
  41. package/dist/cjs/permissionless/api/oracles/stress/types.js +1 -0
  42. package/dist/cjs/permissionless/api/schemas.js +0 -3
  43. package/dist/cjs/permissionless/bindings/index.js +1 -1
  44. package/dist/cjs/permissionless/index.js +29 -1
  45. package/dist/cjs/permissionless/utils/index.js +2 -0
  46. package/dist/cjs/permissionless/utils/price-update/get-prices.js +64 -0
  47. package/dist/cjs/permissionless/utils/price-update/index.js +2 -0
  48. package/dist/cjs/testnets/TestnetsAPI.js +179 -0
  49. package/dist/cjs/testnets/errors/TestnetNotFoundError.js +15 -0
  50. package/dist/cjs/testnets/errors/TestnetRequestFailedError.js +24 -0
  51. package/dist/cjs/testnets/errors/TestnetStatusError.js +19 -0
  52. package/dist/cjs/testnets/errors/TestnetValidationError.js +24 -0
  53. package/dist/cjs/testnets/errors/TestnetWaitTimeoutError.js +30 -0
  54. package/dist/cjs/testnets/errors/TestnetsError.js +34 -0
  55. package/dist/cjs/testnets/errors/index.js +13 -0
  56. package/dist/cjs/testnets/index.js +32 -0
  57. package/dist/cjs/testnets/package.json +1 -0
  58. package/dist/cjs/testnets/schemas.js +242 -0
  59. package/dist/cjs/testnets/types.js +1 -0
  60. package/dist/esm/abi/compressors/subcompressors/liquidation/treehouseLiquidationSubcompressor.js +178 -0
  61. package/dist/esm/abi/compressors/subcompressors/withdrawal/treehouseWithdrawalSubcompressor.js +533 -0
  62. package/dist/esm/abi/router/treehouseWorker.js +884 -0
  63. package/dist/esm/onchain/market/adapters/abi/actionAbi.js +1 -0
  64. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +3 -0
  65. package/dist/esm/onchain/market/adapters/types.js +3 -0
  66. package/dist/esm/permissionless/api/index.js +7 -1
  67. package/dist/esm/permissionless/api/oracles/PermissionlessOracles.js +587 -49
  68. package/dist/esm/permissionless/api/oracles/enrich.js +94 -0
  69. package/dist/esm/permissionless/api/oracles/index.js +10 -1
  70. package/dist/esm/permissionless/api/oracles/schemas.js +95 -35
  71. package/dist/esm/permissionless/api/oracles/score/formula.js +96 -0
  72. package/dist/esm/permissionless/api/oracles/score/index.js +4 -0
  73. package/dist/esm/permissionless/api/oracles/score/run.js +87 -0
  74. package/dist/esm/permissionless/api/oracles/score/types.js +1 -0
  75. package/dist/esm/permissionless/api/oracles/stress/classify.js +256 -0
  76. package/dist/esm/permissionless/api/oracles/stress/index.js +6 -0
  77. package/dist/esm/permissionless/api/oracles/stress/override.js +119 -0
  78. package/dist/esm/permissionless/api/oracles/stress/run.js +427 -0
  79. package/dist/esm/permissionless/api/oracles/stress/score.js +95 -0
  80. package/dist/esm/permissionless/api/oracles/stress/types.js +1 -0
  81. package/dist/esm/permissionless/api/schemas.js +2 -4
  82. package/dist/esm/permissionless/bindings/index.js +1 -1
  83. package/dist/esm/permissionless/index.js +9 -3
  84. package/dist/esm/permissionless/utils/index.js +2 -2
  85. package/dist/esm/permissionless/utils/price-update/get-prices.js +63 -1
  86. package/dist/esm/permissionless/utils/price-update/index.js +2 -2
  87. package/dist/esm/testnets/TestnetsAPI.js +178 -0
  88. package/dist/esm/testnets/errors/TestnetNotFoundError.js +14 -0
  89. package/dist/esm/testnets/errors/TestnetRequestFailedError.js +23 -0
  90. package/dist/esm/testnets/errors/TestnetStatusError.js +18 -0
  91. package/dist/esm/testnets/errors/TestnetValidationError.js +23 -0
  92. package/dist/esm/testnets/errors/TestnetWaitTimeoutError.js +29 -0
  93. package/dist/esm/testnets/errors/TestnetsError.js +33 -0
  94. package/dist/esm/testnets/errors/index.js +7 -0
  95. package/dist/esm/testnets/index.js +11 -0
  96. package/dist/esm/testnets/package.json +1 -0
  97. package/dist/esm/testnets/schemas.js +228 -0
  98. package/dist/esm/testnets/types.js +1 -0
  99. package/dist/types/abi/compressors/subcompressors/liquidation/treehouseLiquidationSubcompressor.d.ts +148 -0
  100. package/dist/types/abi/compressors/subcompressors/withdrawal/treehouseWithdrawalSubcompressor.d.ts +440 -0
  101. package/dist/types/abi/router/treehouseWorker.d.ts +728 -0
  102. package/dist/types/onchain/market/adapters/types.d.ts +4 -1
  103. package/dist/types/permissionless/api/index.d.ts +10 -2
  104. package/dist/types/permissionless/api/oracles/PermissionlessOracles.d.ts +232 -35
  105. package/dist/types/permissionless/api/oracles/enrich.d.ts +59 -0
  106. package/dist/types/permissionless/api/oracles/index.d.ts +12 -2
  107. package/dist/types/permissionless/api/oracles/schemas.d.ts +209 -22
  108. package/dist/types/permissionless/api/oracles/score/formula.d.ts +46 -0
  109. package/dist/types/permissionless/api/oracles/score/index.d.ts +4 -0
  110. package/dist/types/permissionless/api/oracles/score/run.d.ts +21 -0
  111. package/dist/types/permissionless/api/oracles/score/types.d.ts +85 -0
  112. package/dist/types/permissionless/api/oracles/stress/classify.d.ts +57 -0
  113. package/dist/types/permissionless/api/oracles/stress/index.d.ts +6 -0
  114. package/dist/types/permissionless/api/oracles/stress/override.d.ts +59 -0
  115. package/dist/types/permissionless/api/oracles/stress/run.d.ts +73 -0
  116. package/dist/types/permissionless/api/oracles/stress/score.d.ts +57 -0
  117. package/dist/types/permissionless/api/oracles/stress/types.d.ts +272 -0
  118. package/dist/types/permissionless/api/oracles/types.d.ts +408 -63
  119. package/dist/types/permissionless/api/schemas.d.ts +0 -2
  120. package/dist/types/permissionless/index.d.ts +11 -3
  121. package/dist/types/permissionless/utils/index.d.ts +2 -2
  122. package/dist/types/permissionless/utils/price-update/get-prices.d.ts +33 -0
  123. package/dist/types/permissionless/utils/price-update/index.d.ts +2 -2
  124. package/dist/types/testnets/TestnetsAPI.d.ts +108 -0
  125. package/dist/types/testnets/errors/TestnetNotFoundError.d.ts +12 -0
  126. package/dist/types/testnets/errors/TestnetRequestFailedError.d.ts +11 -0
  127. package/dist/types/testnets/errors/TestnetStatusError.d.ts +15 -0
  128. package/dist/types/testnets/errors/TestnetValidationError.d.ts +16 -0
  129. package/dist/types/testnets/errors/TestnetWaitTimeoutError.d.ts +21 -0
  130. package/dist/types/testnets/errors/TestnetsError.d.ts +47 -0
  131. package/dist/types/testnets/errors/index.d.ts +7 -0
  132. package/dist/types/testnets/index.d.ts +11 -0
  133. package/dist/types/testnets/schemas.d.ts +554 -0
  134. package/dist/types/testnets/types.d.ts +717 -0
  135. package/package.json +9 -3
@@ -1,19 +1,49 @@
1
+ import { getAssetType, getNetworkType, isRWAToken, isSupportedNetwork } from "../../../onchain/chain/chains.js";
2
+ import { AP_PRICE_FEED_COMPRESSOR } from "../../../onchain/constants/address-provider.js";
1
3
  import { priceFeedDataSchema } from "../../../model/opportunities.schema.js";
4
+ import { priceFeedCompressorAbi } from "../../../abi/compressors/priceFeedCompressor.js";
5
+ import "../../../onchain/index.js";
2
6
  import { AbstractOffchainNamespace } from "../../../offchain/AbstractOffchainNamespace.js";
3
- import { getPrices } from "../../utils/price-update/get-prices.js";
4
- import { priceFeedDetailsSchema, priceFeedMarketCapsSchema, priceFeedStoreSchema, pricesSchema } from "./schemas.js";
7
+ import "../../deployment/addresses.js";
8
+ import { AddressProviderContract } from "../../bindings/address-provider.js";
9
+ import { getFeedDecimals, getLatestPrices, getPrices } from "../../utils/price-update/get-prices.js";
10
+ import { byCentrality, feedKey, pricesByFeed, toCap, totalQuotas } from "./enrich.js";
11
+ import { assetDetailsSchema, assetSummariesSchema, marketSlotsSchema, priceFeedDetailsSchema, priceFeedStoresSchema } from "./schemas.js";
12
+ import { runStressTest } from "./stress/run.js";
13
+ import { runAssetScores } from "./score/run.js";
14
+ import { erc20Abi } from "viem";
5
15
  //#region src/permissionless/api/oracles/PermissionlessOracles.ts
6
16
  const GET_PRICES_GAS_LIMIT_BY_CHAIN_ID = { 143: 100000000n };
7
17
  const GET_PRICES_CHUNK_SIZE = 200;
8
18
  /**
19
+ * What a market slot is: an oracle, a token, and whether it is the reserve
20
+ * one. Not the market — a market that has switched oracles has rows under
21
+ * each, and the slots are the old oracle's and the new one's separately.
22
+ */
23
+ function slotKey(oracle, token, reserve) {
24
+ return `${oracle.toLowerCase()}:${token.toLowerCase()}:${reserve}`;
25
+ }
26
+ /** An unknown thrown value, as something a log line can carry. */
27
+ function describe(e) {
28
+ return e instanceof Error ? e.message : String(e);
29
+ }
30
+ /**
9
31
  * The price feeds of one chain: the PriceFeedStore as the backend has indexed
10
32
  * it, and the prices behind it.
11
33
  *
12
34
  * ```ts
13
35
  * const store = await permissionless.oracles.store({ chainId: 1 });
14
- * const { prices } = await permissionless.oracles.prices({ chainId: 1 });
36
+ * const prices = await permissionless.oracles.getPrices(
37
+ * store.priceFeeds.map(({ address }) => ({ chainId: 1, address })),
38
+ * );
15
39
  * ```
16
40
  *
41
+ * The backend answers what it has indexed; anything that is only true at a
42
+ * block — a price, a market cap, a quota in one currency, the period an
43
+ * oracle holds for a slot — is read here, off the chain, and folded into what
44
+ * it answered. That is why these reads mix a request with a multicall rather
45
+ * than being either one.
46
+ *
17
47
  * Read-only. What the store carries is decided on chain, so putting a feed
18
48
  * there is a batch the instance owner executes — see
19
49
  * {@link InstanceOwnerTransactions} — not a row a client writes here.
@@ -29,11 +59,64 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
29
59
  }
30
60
  /**
31
61
  * The store with the assets and feeds of one chain.
62
+ *
63
+ * {@link stores} narrowed to one and unwrapped, which is the whole of it:
64
+ * there is one route either way, and a chain the backend does not serve has
65
+ * no store to answer with rather than an empty one.
66
+ *
67
+ * @throws When the backend serves no store for the chain.
32
68
  **/
33
69
  async store({ chainId }) {
70
+ const [store] = await this.stores({ chainId });
71
+ if (!store) throw new Error(`no PriceFeedStore served for chain ${chainId}`);
72
+ return store;
73
+ }
74
+ /**
75
+ * The same stores for every chain the backend serves.
76
+ *
77
+ * One request rather than {@link store} per chain, which is what a page
78
+ * showing all of them would otherwise do: the backend assembles them in the
79
+ * same few queries it assembles one in, so the chains cost little more than
80
+ * the largest of them.
81
+ *
82
+ * Each entry names its own chain, so a store is never attributed by
83
+ * position. `chainId` narrows it to one, for a caller that wants the list
84
+ * shape either way.
85
+ *
86
+ * ```ts
87
+ * const stores = await permissionless.oracles.stores();
88
+ * ```
89
+ **/
90
+ async stores({ chainId } = {}) {
34
91
  return this.getData({
35
- path: `/pfs/${chainId}`,
36
- schema: priceFeedStoreSchema
92
+ path: "/pfs/stores",
93
+ query: { chainId: chainId?.toString() },
94
+ schema: priceFeedStoresSchema
95
+ });
96
+ }
97
+ /**
98
+ * Every market slot in force, with the feed holding it and what the market
99
+ * has riding on it.
100
+ *
101
+ * The chain's whole slot table, which {@link feed} and {@link asset} answer
102
+ * one subject's slice of. What reads it this way is analysis over every
103
+ * market at once — which feed holds which slot, and what breaks if it
104
+ * lies — and asking a feed at a time would be a few hundred requests for
105
+ * the same rows.
106
+ *
107
+ * Served as indexed, with nothing folded in: the quotas are in each
108
+ * market's own underlying, as everywhere else, and pricing them is
109
+ * {@link getPrices} over the `underlyingPriceFeed` column.
110
+ *
111
+ * ```ts
112
+ * const slots = await permissionless.oracles.slots({ chainId: 1 });
113
+ * ```
114
+ **/
115
+ async slots({ chainId } = {}) {
116
+ return this.getData({
117
+ path: "/pfs/slots",
118
+ query: { chainId: chainId?.toString() },
119
+ schema: marketSlotsSchema
37
120
  });
38
121
  }
39
122
  /**
@@ -51,14 +134,291 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
51
134
  * });
52
135
  * ```
53
136
  *
137
+ * Each market row also carries the staleness period that market's own
138
+ * oracle holds for the slot, read off the chain here — see
139
+ * {@link PermissionlessPriceFeedMarket.marketStalenessPeriod}.
140
+ *
54
141
  * @throws When the store does not carry the feed. A private draft is not
55
142
  * here — it lives in whichever app wrote it.
56
143
  **/
57
144
  async feed({ chainId, address }) {
58
- return this.getData({
145
+ const feed = address.toLowerCase();
146
+ const indexed = await this.getData({
59
147
  path: `/pfs/${chainId}/price-feed/${address}`,
60
148
  schema: priceFeedDetailsSchema
61
149
  });
150
+ const periods = await this.#stalenessPeriods(chainId, feed, indexed.markets);
151
+ return {
152
+ ...indexed,
153
+ markets: indexed.markets.map((market) => ({
154
+ ...market,
155
+ marketStalenessPeriod: periods.get(slotKey(market.priceOracle, market.token, market.reserve)) ?? null
156
+ }))
157
+ };
158
+ }
159
+ /**
160
+ * Staleness period each market's own oracle holds for the feed's slots,
161
+ * keyed by {@link slotKey}.
162
+ *
163
+ * One call per oracle rather than per slot: the compressor answers for a
164
+ * whole oracle at once, and a feed in a dozen markets of the same curator
165
+ * would otherwise pay a round trip per token. Scoped to the tokens actually
166
+ * asked about, since the unscoped overload returns the oracle's entire feed
167
+ * tree as well.
168
+ *
169
+ * Failures are warnings and not errors. A slot missing from the answer keeps
170
+ * its `null`, which the caller reports as "the oracle would not say" — the
171
+ * alternative is failing a read whose indexed half is perfectly good.
172
+ */
173
+ async #stalenessPeriods(chainId, feed, rows) {
174
+ const periods = /* @__PURE__ */ new Map();
175
+ if (rows.length === 0) return periods;
176
+ const tokensByOracle = /* @__PURE__ */ new Map();
177
+ for (const row of rows) {
178
+ let tokens = tokensByOracle.get(row.priceOracle);
179
+ if (!tokens) {
180
+ tokens = /* @__PURE__ */ new Set();
181
+ tokensByOracle.set(row.priceOracle, tokens);
182
+ }
183
+ tokens.add(row.token);
184
+ }
185
+ let client;
186
+ let compressor;
187
+ try {
188
+ client = this.#chains.client(chainId);
189
+ compressor = await new AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(AP_PRICE_FEED_COMPRESSOR);
190
+ } catch (e) {
191
+ this.logger?.warn(`no PriceFeedCompressor for chain ${chainId}, reporting no market staleness periods: ${describe(e)}`);
192
+ return periods;
193
+ }
194
+ const oracles = [...tokensByOracle.keys()];
195
+ const results = await client.multicall({
196
+ contracts: oracles.map((oracle) => ({
197
+ address: compressor,
198
+ abi: priceFeedCompressorAbi,
199
+ functionName: "getPriceOracleState",
200
+ args: [oracle, [...tokensByOracle.get(oracle) ?? []]]
201
+ })),
202
+ allowFailure: true
203
+ });
204
+ oracles.forEach((oracle, i) => {
205
+ const result = results[i];
206
+ if (result?.status !== "success") {
207
+ this.logger?.warn(`price oracle ${oracle} of chain ${chainId} would not report its feed map`);
208
+ return;
209
+ }
210
+ const { priceFeedMap } = result.result;
211
+ for (const entry of priceFeedMap) {
212
+ if (entry.priceFeed.toLowerCase() !== feed) continue;
213
+ periods.set(slotKey(oracle, entry.token, entry.reserve), Number(entry.stalenessPeriod));
214
+ }
215
+ });
216
+ return periods;
217
+ }
218
+ /**
219
+ * One asset of the store: the feeds allowed for it, and the markets that
220
+ * take it as collateral.
221
+ *
222
+ * The mirror of {@link feed}, and the call to reach for when the question is
223
+ * "what prices this token and what is it backing" rather than "where is this
224
+ * feed used". Both read the same market slots; which end they are indexed
225
+ * from is the difference.
226
+ *
227
+ * ```ts
228
+ * const { priceFeeds, markets, quotaUsedUsd } =
229
+ * await permissionless.oracles.asset({ chainId: 1, address: token });
230
+ * ```
231
+ *
232
+ * The quota totals are worked out here, over the very market rows this
233
+ * answers with — see {@link PermissionlessQuotaTotals}.
234
+ *
235
+ * @throws When the chain has no metadata for the address. An asset nothing
236
+ * was indexed for has no symbol or decimals, so there is no row to answer.
237
+ **/
238
+ async asset({ chainId, address }) {
239
+ const indexed = await this.getData({
240
+ path: `/pfs/${chainId}/asset/${address}`,
241
+ schema: assetDetailsSchema
242
+ });
243
+ const priceOf = await this.#underlyingPrices(indexed.markets.map((market) => ({
244
+ chainId,
245
+ underlyingPriceFeed: market.underlyingPriceFeed
246
+ })));
247
+ return {
248
+ ...indexed,
249
+ ...totalQuotas(indexed.markets, (feed) => priceOf(chainId, feed))
250
+ };
251
+ }
252
+ /**
253
+ * The price of every underlying the given quota rows name, looked up by
254
+ * chain and feed.
255
+ *
256
+ * Distinct feeds only, because an asset in a dozen markets of the same
257
+ * underlying names the same feed a dozen times, and a list of every chain's
258
+ * assets names a handful of feeds per chain between them all.
259
+ */
260
+ async #underlyingPrices(rows) {
261
+ const refs = /* @__PURE__ */ new Map();
262
+ for (const { chainId, underlyingPriceFeed } of rows) {
263
+ if (underlyingPriceFeed === null) continue;
264
+ const address = underlyingPriceFeed.toLowerCase();
265
+ refs.set(feedKey(chainId, address), {
266
+ chainId,
267
+ address
268
+ });
269
+ }
270
+ const prices = pricesByFeed(await this.getPrices([...refs.values()]));
271
+ return (chainId, feed) => prices.get(feedKey(chainId, feed));
272
+ }
273
+ /**
274
+ * Every asset the store carries, with what its markets make of it.
275
+ *
276
+ * Enough on its own to render a list of assets: the alternative is the
277
+ * store's whole read for the names plus a call per row for the quotas, and
278
+ * this is one request either way you scope it.
279
+ *
280
+ * Ordered by how central each asset is — the markets it underlies first,
281
+ * then what is quoted against it, then what it is allowed — so a consumer
282
+ * renders the rows as they arrive. Omit `chainId` for every chain the
283
+ * backend serves, ordered the same way across all of them.
284
+ *
285
+ * Each row also carries its quota totals and what this SDK's tables say the
286
+ * asset is, neither of which is served — see
287
+ * {@link PermissionlessAssetSummary}. The totals are what the last two terms
288
+ * of the order are over, so this waits for them rather than handing back a
289
+ * list that would reshuffle a moment later.
290
+ *
291
+ * ```ts
292
+ * const assets = await permissionless.oracles.assets({ chainId: 1 });
293
+ * const everywhere = await permissionless.oracles.assets();
294
+ * ```
295
+ **/
296
+ async assets({ chainId } = {}) {
297
+ const indexed = await this.getData({
298
+ path: "/pfs/assets",
299
+ query: { chainId: chainId?.toString() },
300
+ schema: assetSummariesSchema
301
+ });
302
+ const networks = /* @__PURE__ */ new Map();
303
+ for (const { chainId: id } of indexed) if (!networks.has(id)) networks.set(id, isSupportedNetwork(id) ? getNetworkType(id) : void 0);
304
+ const priceOf = await this.#underlyingPrices(indexed.flatMap((asset) => asset.marketQuotas.map((quota) => ({
305
+ chainId: asset.chainId,
306
+ underlyingPriceFeed: quota.underlyingPriceFeed
307
+ }))));
308
+ return indexed.map((asset) => {
309
+ const network = networks.get(asset.chainId);
310
+ return {
311
+ ...asset,
312
+ ...totalQuotas(asset.marketQuotas, (feed) => priceOf(asset.chainId, feed)),
313
+ assetType: network === void 0 ? null : getAssetType(asset.address, network) ?? null,
314
+ isRwa: network === void 0 ? false : isRWAToken(asset.address, network)
315
+ };
316
+ }).sort(byCentrality);
317
+ }
318
+ /**
319
+ * What each source of price information can do to the chain's markets if it
320
+ * lies.
321
+ *
322
+ * The feeds under a chain's oracles are partitioned by where their numbers
323
+ * actually come from — Chainlink, Redstone, Pyth, Lido, Curve, each vault's
324
+ * own issuer — on the grounds that a source fails as a whole: whoever
325
+ * trusts one Chainlink aggregator trusts the operator behind all of them.
326
+ * Each group is then made to report a multiple of what it reports now, and
327
+ * every feed the markets read is read again inside that same call.
328
+ *
329
+ * No fork and no harness. The lie is a state override on an `eth_call`, so
330
+ * the composite feeds above it, their bounds and the oracle's own checks all
331
+ * run as deployed, against real state, at the current block — what comes
332
+ * back is what the market would have read.
333
+ *
334
+ * Each slot is scored by how its collateral moved *against its market's own
335
+ * underlying*, because that is what an account is valued by: a group that
336
+ * moves both legs has moved nothing. Beyond the two unbounded ends, each
337
+ * group is bisected for the multiple at which something first breaks, which
338
+ * is the figure that separates a source held in check by a bound from one
339
+ * nothing is checking.
340
+ *
341
+ * ```ts
342
+ * const report = await permissionless.oracles.stressTest({ chainId: 1 });
343
+ * for (const group of report.groups) {
344
+ * console.log(group.verdict);
345
+ * }
346
+ * ```
347
+ *
348
+ * Report {@link StressReport.unidentifiedUsd} alongside anything taken from
349
+ * this: it is the quota priced through a source the partition could only
350
+ * name after its own description, and nothing says what that fails with.
351
+ *
352
+ * Reads the chain directly, so the client has to have attached — see
353
+ * {@link GearboxPermissionless.attach}. Costs one request for the slots and
354
+ * then, per group, one `eth_call` per scenario plus the bisection's; a whole
355
+ * chain comes to a minute or so, and `thresholds: false` cuts it to seconds.
356
+ *
357
+ * @throws When the client has not attached, when the chain has no client
358
+ * configured, or when no PriceFeedCompressor is deployed on it — none of the
359
+ * three leaves anything to simulate.
360
+ **/
361
+ /**
362
+ * Every asset's score out of 10 for how its markets guard its price.
363
+ *
364
+ * A market scores 10 when its reserve feed is a second feed on other
365
+ * sources than the main one, and one of the two is bounded — a
366
+ * `BoundedPriceFeed` or a Gearbox LP feed. It loses 6 points as the two
367
+ * feeds' sources overlap — all of them if there is no reserve, it is a
368
+ * `ZeroPriceFeed`, or it is the main feed again — and 5 if neither is
369
+ * bounded. An asset scores its worst running market that takes it as
370
+ * collateral.
371
+ *
372
+ * Read off the chain, one multicall of feed trees per chain, so the score
373
+ * is of the trees as they stand rather than as last indexed. A chain with
374
+ * no client configured is left out with a warning rather than failing the
375
+ * rest.
376
+ *
377
+ * ```ts
378
+ * const scores = await permissionless.oracles.assetScores({ chainId: 1 });
379
+ * ```
380
+ *
381
+ * @throws {PermissionlessNotAttachedError} before
382
+ * {@link GearboxPermissionless.attach} has resolved.
383
+ **/
384
+ async assetScores({ chainId } = {}) {
385
+ const slots = await this.slots({ chainId });
386
+ const byChain = /* @__PURE__ */ new Map();
387
+ for (const slot of slots) byChain.set(slot.chainId, [...byChain.get(slot.chainId) ?? [], slot]);
388
+ return (await Promise.all([...byChain].map(async ([id, chainSlots]) => {
389
+ let client;
390
+ try {
391
+ client = this.#chains.client(id);
392
+ } catch (e) {
393
+ this.logger?.warn(`chain ${id} has no client, leaving its assets unscored: ${describe(e)}`);
394
+ return [];
395
+ }
396
+ try {
397
+ const compressor = await new AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(AP_PRICE_FEED_COMPRESSOR);
398
+ return await runAssetScores({
399
+ client,
400
+ chainId: id,
401
+ slots: chainSlots,
402
+ compressor,
403
+ logger: this.logger ?? void 0
404
+ });
405
+ } catch (e) {
406
+ this.logger?.warn(`chain ${id} would not report its feed trees, leaving its assets unscored: ${describe(e)}`);
407
+ return [];
408
+ }
409
+ }))).flat();
410
+ }
411
+ async stressTest({ chainId, ...options }) {
412
+ const client = this.#chains.client(chainId);
413
+ const compressor = await new AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(AP_PRICE_FEED_COMPRESSOR);
414
+ return runStressTest({
415
+ client,
416
+ chainId,
417
+ compressor,
418
+ slots: await this.slots({ chainId }),
419
+ logger: this.logger ?? void 0,
420
+ ...options
421
+ });
62
422
  }
63
423
  /**
64
424
  * The feeds one feed reads from, recursively.
@@ -81,69 +441,247 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
81
441
  });
82
442
  }
83
443
  /**
84
- * What the market values each of one feed's assets at.
444
+ * What the named feeds price, read off the chain.
85
445
  *
86
- * Prefer this over {@link prices} whenever the caller is looking at a single
87
- * feed. That one prices the whole store, which costs the backend one
88
- * `totalSupply` call per asset of every market on the chain; this costs it
89
- * one price lookup and one multicall over the feed's own assets.
446
+ * Prices exactly what is asked for, at the current block, across as many
447
+ * chains as the list names — one read per chain, so a screen listing every
448
+ * chain's feeds pays per chain and not per row. A feed the store does not
449
+ * carry prices the same way, which is what makes this the call to reach for
450
+ * after a deploy, or while a form is still choosing between candidates.
451
+ *
452
+ * Read in two passes. The first asks every feed what it reports as it
453
+ * stands, which is one multicall per chain; a feed that will not answer
454
+ * until it has been given a fresh one is then priced inside a simulation
455
+ * that updates it first, so a push-based feed prices as readily as a
456
+ * pull-based one. The second pass costs an `OnchainSDK` to attach, hence
457
+ * only the feeds that need it rather than all of them.
458
+ *
459
+ * `null` is a feed neither pass could read, and a chain with no client
460
+ * configured is every one of its feeds reading `null` rather than a failed
461
+ * call — the figures built on them are floors either way.
90
462
  *
91
463
  * ```ts
92
- * const { marketCaps } = await permissionless.oracles.feedMarketCaps({
93
- * chainId: 1,
94
- * address: feed,
95
- * });
464
+ * const [{ price }] = await permissionless.oracles.getPrices([
465
+ * { chainId: 1, address: feed },
466
+ * ]);
96
467
  * ```
468
+ *
469
+ * @returns One entry per feed asked for, in the order asked, each price in
470
+ * the 8 decimals every Gearbox feed reports.
97
471
  **/
98
- async feedMarketCaps({ chainId, address }) {
99
- return this.getData({
100
- path: `/pfs/${chainId}/price-feed/${address}/market-caps`,
101
- schema: priceFeedMarketCapsSchema
102
- });
472
+ async getPrices(feeds) {
473
+ const byChain = /* @__PURE__ */ new Map();
474
+ for (const { chainId, address } of feeds) {
475
+ const addresses = byChain.get(chainId) ?? /* @__PURE__ */ new Set();
476
+ addresses.add(address.toLowerCase());
477
+ byChain.set(chainId, addresses);
478
+ }
479
+ const chainIds = [...byChain.keys()];
480
+ const results = await Promise.all(chainIds.map((chainId) => this.#pricesOf(chainId, [...byChain.get(chainId) ?? []])));
481
+ const prices = new Map(chainIds.map((id, i) => [id, results[i] ?? {}]));
482
+ return feeds.map(({ chainId, address }) => ({
483
+ chainId,
484
+ address,
485
+ price: prices.get(chainId)?.[address.toLowerCase()] ?? null
486
+ }));
103
487
  }
104
488
  /**
105
- * A price per feed, and a market cap per feed and asset. The feeds the
106
- * indexer has not seen are read off the chain by the backend, so the store
107
- * is priced whole.
489
+ * The scale each of the named feeds answers in.
490
+ *
491
+ * The companion to {@link getPrices} for the callers whose feeds are not
492
+ * all an oracle's: everything an oracle holds reports 8 decimals, but the
493
+ * feeds under a composite are whatever was deployed, and a rate leg at 18
494
+ * read as 8 is wrong by ten orders of magnitude rather than visibly wrong.
495
+ *
496
+ * Separate from the price because the two keep different company: this is
497
+ * fixed for the life of the contract and worth caching for the session,
498
+ * while a price is re-read whenever the reader asks. One multicall per
499
+ * chain either way.
500
+ *
501
+ * `null` is a feed that would not answer, or one on a chain with no client
502
+ * configured.
503
+ *
504
+ * ```ts
505
+ * const [{ decimals }] = await permissionless.oracles.getDecimals([
506
+ * { chainId: 1, address: feed },
507
+ * ]);
508
+ * ```
108
509
  *
109
- * Chain-wide, and priced accordingly — see {@link feedMarketCaps} for one
110
- * feed.
510
+ * @returns One entry per feed asked for, in the order asked.
111
511
  **/
112
- async prices({ chainId }) {
113
- return this.getData({
114
- path: `/pfs/${chainId}/prices`,
115
- schema: pricesSchema
116
- });
512
+ async getDecimals(feeds) {
513
+ const byChain = /* @__PURE__ */ new Map();
514
+ for (const { chainId, address } of feeds) {
515
+ const addresses = byChain.get(chainId) ?? /* @__PURE__ */ new Set();
516
+ addresses.add(address.toLowerCase());
517
+ byChain.set(chainId, addresses);
518
+ }
519
+ const chainIds = [...byChain.keys()];
520
+ const results = await Promise.all(chainIds.map((chainId) => this.#decimalsOf(chainId, [...byChain.get(chainId) ?? []])));
521
+ const decimals = new Map(chainIds.map((id, i) => [id, results[i] ?? {}]));
522
+ return feeds.map(({ chainId, address }) => ({
523
+ chainId,
524
+ address,
525
+ decimals: decimals.get(chainId)?.[address.toLowerCase()] ?? null
526
+ }));
527
+ }
528
+ /** One chain's half of {@link getDecimals}. */
529
+ async #decimalsOf(chainId, priceFeeds) {
530
+ let client;
531
+ try {
532
+ client = this.#chains.client(chainId);
533
+ } catch (e) {
534
+ this.logger?.warn(`chain ${chainId} has no client, reporting its ${priceFeeds.length} feed(s) without a scale: ${describe(e)}`);
535
+ return {};
536
+ }
537
+ try {
538
+ return await getFeedDecimals({
539
+ client,
540
+ priceFeeds
541
+ });
542
+ } catch (e) {
543
+ this.logger?.warn(`chain ${chainId} would not answer decimals for its ${priceFeeds.length} feed(s): ${describe(e)}`);
544
+ return {};
545
+ }
546
+ }
547
+ /** One chain's half of {@link getPrices}: the cheap pass, then the rest. */
548
+ async #pricesOf(chainId, priceFeeds) {
549
+ let client;
550
+ try {
551
+ client = this.#chains.client(chainId);
552
+ } catch (e) {
553
+ this.logger?.warn(`chain ${chainId} has no client, reporting its ${priceFeeds.length} feed(s) unpriced: ${describe(e)}`);
554
+ return {};
555
+ }
556
+ let prices;
557
+ try {
558
+ prices = await getLatestPrices({
559
+ client,
560
+ priceFeeds
561
+ });
562
+ } catch (e) {
563
+ this.logger?.warn(`chain ${chainId} would not answer for its ${priceFeeds.length} feed(s), trying each with an update: ${describe(e)}`);
564
+ prices = {};
565
+ }
566
+ const stale = priceFeeds.filter((feed) => (prices[feed] ?? null) === null);
567
+ if (stale.length === 0) return prices;
568
+ try {
569
+ return {
570
+ ...prices,
571
+ ...await getPrices({
572
+ client,
573
+ priceFeeds: stale,
574
+ chunkSize: 200,
575
+ gasLimit: GET_PRICES_GAS_LIMIT_BY_CHAIN_ID[chainId]
576
+ })
577
+ };
578
+ } catch (e) {
579
+ this.logger?.warn(`chain ${chainId} would not price ${stale.length} of its feed(s) even with an update, reporting them unpriced: ${describe(e)}`);
580
+ return prices;
581
+ }
117
582
  }
118
583
  /**
119
- * The price each of the named feeds reports, read off the chain.
584
+ * What one chain's feeds value one chain's assets at: `price × totalSupply`
585
+ * per pair.
120
586
  *
121
- * Where {@link prices} answers for the store as a whole and at whatever
122
- * moment the backend priced it, this prices exactly the feeds asked for, at
123
- * the current block. A feed the store does not carry prices the same way,
124
- * which is what makes this the call to reach for after a deploy, or while a
125
- * form is still choosing between candidates.
587
+ * Asked from whichever side the caller is looking at — one asset through
588
+ * each of its feeds, or one feed over each of the assets it prices — because
589
+ * a screen shows one row per feed or one row per asset, never the full
590
+ * cross product. Both answer the same pairs in the same shape.
126
591
  *
127
- * Feeds needing a fresh answer before they can be read are updated inside
128
- * the same simulation, so a push-based feed prices as readily as a
129
- * pull-based one. `null` is a feed whose read reverted, not a zero.
592
+ * Two reads per chain: the prices, and one multicall for the assets'
593
+ * supplies and decimals. Several scopes can be asked at once, which is how a
594
+ * table of every asset's feeds pays per chain rather than per row; the pairs
595
+ * come back in the order the scopes named them. A pair neither read could
596
+ * resolve has a `null` cap, which is not a zero.
130
597
  *
131
598
  * ```ts
132
- * const prices = await permissionless.oracles.getPrices({
599
+ * const caps = await permissionless.oracles.getMarketCap({
133
600
  * chainId: 1,
134
- * priceFeeds: [feed],
601
+ * asset: token,
602
+ * priceFeeds: [main, reserve],
135
603
  * });
136
604
  * ```
137
- *
138
- * @returns A price per feed, in the 8 decimals every Gearbox feed reports.
139
605
  **/
140
- async getPrices({ chainId, priceFeeds }) {
141
- return getPrices({
142
- client: this.#chains.client(chainId),
143
- priceFeeds,
144
- chunkSize: 200,
145
- gasLimit: GET_PRICES_GAS_LIMIT_BY_CHAIN_ID[chainId]
606
+ async getMarketCap(scope) {
607
+ const pairs = (Array.isArray(scope) ? scope : [scope]).flatMap((one) => "asset" in one ? one.priceFeeds.map((priceFeed) => ({
608
+ chainId: one.chainId,
609
+ priceFeed: priceFeed.toLowerCase(),
610
+ asset: one.asset.toLowerCase()
611
+ })) : one.assets.map((asset) => ({
612
+ chainId: one.chainId,
613
+ priceFeed: one.priceFeed.toLowerCase(),
614
+ asset: asset.toLowerCase()
615
+ })));
616
+ if (pairs.length === 0) return [];
617
+ const feeds = /* @__PURE__ */ new Map();
618
+ const assetsByChain = /* @__PURE__ */ new Map();
619
+ for (const { chainId, priceFeed, asset } of pairs) {
620
+ feeds.set(feedKey(chainId, priceFeed), {
621
+ chainId,
622
+ address: priceFeed
623
+ });
624
+ const assets = assetsByChain.get(chainId) ?? /* @__PURE__ */ new Set();
625
+ assets.add(asset);
626
+ assetsByChain.set(chainId, assets);
627
+ }
628
+ const chainIds = [...assetsByChain.keys()];
629
+ const [prices, perChain] = await Promise.all([this.getPrices([...feeds.values()]), Promise.all(chainIds.map((chainId) => this.#supplies(chainId, [...assetsByChain.get(chainId) ?? []])))]);
630
+ const priced = pricesByFeed(prices);
631
+ const supplies = new Map(chainIds.map((id, i) => [id, perChain[i]]));
632
+ return pairs.map(({ chainId, priceFeed, asset }) => {
633
+ const supply = supplies.get(chainId)?.get(asset);
634
+ return {
635
+ chainId,
636
+ priceFeed,
637
+ asset,
638
+ cap: supply === void 0 ? null : toCap(priced.get(feedKey(chainId, priceFeed)), supply.totalSupply, supply.decimals)
639
+ };
640
+ });
641
+ }
642
+ /**
643
+ * Each asset's supply and the decimals it is counted in, which is what turns
644
+ * a supply into an amount.
645
+ *
646
+ * Both read rather than one of them taken from the index, so that a cap can
647
+ * be asked for an address nothing was indexed for at all — a token a form is
648
+ * still choosing, say. An asset missing from the answer is left out, and
649
+ * caps over it come back `null`.
650
+ */
651
+ async #supplies(chainId, assets) {
652
+ const supplies = /* @__PURE__ */ new Map();
653
+ let client;
654
+ try {
655
+ client = this.#chains.client(chainId);
656
+ } catch (e) {
657
+ this.logger?.warn(`chain ${chainId} has no client, reporting no market caps: ${describe(e)}`);
658
+ return supplies;
659
+ }
660
+ const results = await client.multicall({
661
+ contracts: assets.flatMap((address) => [{
662
+ address,
663
+ abi: erc20Abi,
664
+ functionName: "totalSupply"
665
+ }, {
666
+ address,
667
+ abi: erc20Abi,
668
+ functionName: "decimals"
669
+ }]),
670
+ allowFailure: true
671
+ });
672
+ assets.forEach((address, i) => {
673
+ const supply = results[2 * i];
674
+ const decimals = results[2 * i + 1];
675
+ if (decimals?.status !== "success") {
676
+ this.logger?.warn(`asset ${address} of chain ${chainId} would not report its decimals, reporting no market cap for it`);
677
+ return;
678
+ }
679
+ supplies.set(address, {
680
+ totalSupply: supply?.status === "success" ? supply.result : null,
681
+ decimals: Number(decimals.result)
682
+ });
146
683
  });
684
+ return supplies;
147
685
  }
148
686
  };
149
687
  //#endregion