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

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 (81) 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/onchain/market/adapters/abi/actionAbi.js +1 -0
  5. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +3 -0
  6. package/dist/cjs/onchain/market/adapters/types.js +3 -0
  7. package/dist/cjs/permissionless/api/oracles/PermissionlessOracles.js +397 -50
  8. package/dist/cjs/permissionless/api/oracles/enrich.js +99 -0
  9. package/dist/cjs/permissionless/api/oracles/schemas.js +85 -35
  10. package/dist/cjs/permissionless/api/schemas.js +0 -3
  11. package/dist/cjs/permissionless/bindings/index.js +1 -1
  12. package/dist/cjs/permissionless/index.js +2 -1
  13. package/dist/cjs/permissionless/utils/index.js +1 -0
  14. package/dist/cjs/permissionless/utils/price-update/get-prices.js +25 -0
  15. package/dist/cjs/permissionless/utils/price-update/index.js +1 -0
  16. package/dist/cjs/testnets/TestnetsAPI.js +179 -0
  17. package/dist/cjs/testnets/errors/TestnetNotFoundError.js +15 -0
  18. package/dist/cjs/testnets/errors/TestnetRequestFailedError.js +24 -0
  19. package/dist/cjs/testnets/errors/TestnetStatusError.js +19 -0
  20. package/dist/cjs/testnets/errors/TestnetValidationError.js +24 -0
  21. package/dist/cjs/testnets/errors/TestnetWaitTimeoutError.js +30 -0
  22. package/dist/cjs/testnets/errors/TestnetsError.js +34 -0
  23. package/dist/cjs/testnets/errors/index.js +13 -0
  24. package/dist/cjs/testnets/index.js +32 -0
  25. package/dist/cjs/testnets/package.json +1 -0
  26. package/dist/cjs/testnets/schemas.js +242 -0
  27. package/dist/cjs/testnets/types.js +1 -0
  28. package/dist/esm/abi/compressors/subcompressors/liquidation/treehouseLiquidationSubcompressor.js +178 -0
  29. package/dist/esm/abi/compressors/subcompressors/withdrawal/treehouseWithdrawalSubcompressor.js +533 -0
  30. package/dist/esm/abi/router/treehouseWorker.js +884 -0
  31. package/dist/esm/onchain/market/adapters/abi/actionAbi.js +1 -0
  32. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +3 -0
  33. package/dist/esm/onchain/market/adapters/types.js +3 -0
  34. package/dist/esm/permissionless/api/oracles/PermissionlessOracles.js +399 -52
  35. package/dist/esm/permissionless/api/oracles/enrich.js +94 -0
  36. package/dist/esm/permissionless/api/oracles/schemas.js +80 -35
  37. package/dist/esm/permissionless/api/schemas.js +2 -4
  38. package/dist/esm/permissionless/bindings/index.js +1 -1
  39. package/dist/esm/permissionless/index.js +3 -3
  40. package/dist/esm/permissionless/utils/index.js +2 -2
  41. package/dist/esm/permissionless/utils/price-update/get-prices.js +25 -1
  42. package/dist/esm/permissionless/utils/price-update/index.js +2 -2
  43. package/dist/esm/testnets/TestnetsAPI.js +178 -0
  44. package/dist/esm/testnets/errors/TestnetNotFoundError.js +14 -0
  45. package/dist/esm/testnets/errors/TestnetRequestFailedError.js +23 -0
  46. package/dist/esm/testnets/errors/TestnetStatusError.js +18 -0
  47. package/dist/esm/testnets/errors/TestnetValidationError.js +23 -0
  48. package/dist/esm/testnets/errors/TestnetWaitTimeoutError.js +29 -0
  49. package/dist/esm/testnets/errors/TestnetsError.js +33 -0
  50. package/dist/esm/testnets/errors/index.js +7 -0
  51. package/dist/esm/testnets/index.js +11 -0
  52. package/dist/esm/testnets/package.json +1 -0
  53. package/dist/esm/testnets/schemas.js +228 -0
  54. package/dist/esm/testnets/types.js +1 -0
  55. package/dist/types/abi/compressors/subcompressors/liquidation/treehouseLiquidationSubcompressor.d.ts +148 -0
  56. package/dist/types/abi/compressors/subcompressors/withdrawal/treehouseWithdrawalSubcompressor.d.ts +440 -0
  57. package/dist/types/abi/router/treehouseWorker.d.ts +728 -0
  58. package/dist/types/onchain/market/adapters/types.d.ts +4 -1
  59. package/dist/types/permissionless/api/index.d.ts +2 -2
  60. package/dist/types/permissionless/api/oracles/PermissionlessOracles.d.ts +120 -37
  61. package/dist/types/permissionless/api/oracles/enrich.d.ts +59 -0
  62. package/dist/types/permissionless/api/oracles/index.d.ts +2 -2
  63. package/dist/types/permissionless/api/oracles/schemas.d.ts +164 -24
  64. package/dist/types/permissionless/api/oracles/types.d.ts +350 -63
  65. package/dist/types/permissionless/api/schemas.d.ts +0 -2
  66. package/dist/types/permissionless/index.d.ts +3 -3
  67. package/dist/types/permissionless/utils/index.d.ts +2 -2
  68. package/dist/types/permissionless/utils/price-update/get-prices.d.ts +17 -0
  69. package/dist/types/permissionless/utils/price-update/index.d.ts +2 -2
  70. package/dist/types/testnets/TestnetsAPI.d.ts +108 -0
  71. package/dist/types/testnets/errors/TestnetNotFoundError.d.ts +12 -0
  72. package/dist/types/testnets/errors/TestnetRequestFailedError.d.ts +11 -0
  73. package/dist/types/testnets/errors/TestnetStatusError.d.ts +15 -0
  74. package/dist/types/testnets/errors/TestnetValidationError.d.ts +16 -0
  75. package/dist/types/testnets/errors/TestnetWaitTimeoutError.d.ts +21 -0
  76. package/dist/types/testnets/errors/TestnetsError.d.ts +47 -0
  77. package/dist/types/testnets/errors/index.d.ts +7 -0
  78. package/dist/types/testnets/index.d.ts +11 -0
  79. package/dist/types/testnets/schemas.d.ts +554 -0
  80. package/dist/types/testnets/types.d.ts +717 -0
  81. package/package.json +9 -3
@@ -32,6 +32,7 @@ const adapterActionSignatures = {
32
32
  311: "function setPairStatusBatch((address,address,address,uint8,uint8)[])"
33
33
  },
34
34
  ["TRADERJOE_ROUTER"]: { 310: "function setPoolStatusBatch((address,address,uint256,uint8,bool)[])" },
35
+ ["TREEHOUSE_ROUTER"]: { 310: "function setAssetStatusBatch(address[],bool[])" },
35
36
  ["UNISWAP_V2_ROUTER"]: { 310: "function setPairStatusBatch((address,address,bool)[])" },
36
37
  ["UNISWAP_V3_ROUTER"]: { 310: "function setPoolStatusBatch((address,address,uint24,bool)[])" },
37
38
  ["UNISWAP_V4_GATEWAY"]: { 310: "function setPoolKeyStatusBatch(((address,address,uint24,int24,address),bool)[])" },
@@ -35,6 +35,9 @@ const adapterConstructorAbi = {
35
35
  ["UNISWAP_V4_GATEWAY"]: { 310: BASIC_ADAPTER_ABI },
36
36
  ["VELODROME_V2_ROUTER"]: { 310: BASIC_ADAPTER_ABI },
37
37
  ["SECURITIZE_ONRAMP"]: { 310: BASIC_ADAPTER_ABI },
38
+ ["TREEHOUSE_FASTLANE"]: { 310: BASIC_ADAPTER_ABI },
39
+ ["TREEHOUSE_GATEWAY"]: { 310: BASIC_ADAPTER_ABI },
40
+ ["TREEHOUSE_ROUTER"]: { 310: BASIC_ADAPTER_ABI },
38
41
  ["CURVE_V1_2ASSETS"]: { 311: CURVE_V1_ADAPTER_311_ABI },
39
42
  ["CURVE_V1_3ASSETS"]: { 311: CURVE_V1_ADAPTER_311_ABI },
40
43
  ["CURVE_V1_4ASSETS"]: { 311: CURVE_V1_ADAPTER_311_ABI },
@@ -33,6 +33,9 @@ let AdapterType = /* @__PURE__ */ function(AdapterType) {
33
33
  AdapterType["SECURITIZE_REDEMPTION"] = "SECURITIZE_REDEMPTION";
34
34
  AdapterType["STAKING_REWARDS"] = "STAKING_REWARDS";
35
35
  AdapterType["TRADERJOE_ROUTER"] = "TRADERJOE_ROUTER";
36
+ AdapterType["TREEHOUSE_FASTLANE"] = "TREEHOUSE_FASTLANE";
37
+ AdapterType["TREEHOUSE_GATEWAY"] = "TREEHOUSE_GATEWAY";
38
+ AdapterType["TREEHOUSE_ROUTER"] = "TREEHOUSE_ROUTER";
36
39
  AdapterType["UNISWAP_V2_ROUTER"] = "UNISWAP_V2_ROUTER";
37
40
  AdapterType["UNISWAP_V3_ROUTER"] = "UNISWAP_V3_ROUTER";
38
41
  AdapterType["UNISWAP_V4_GATEWAY"] = "UNISWAP_V4_GATEWAY";
@@ -1,19 +1,47 @@
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 { getLatestPrices, getPrices } from "../../utils/price-update/get-prices.js";
10
+ import { byCentrality, feedKey, pricesByFeed, toCap, totalQuotas } from "./enrich.js";
11
+ import { assetDetailsSchema, assetSummariesSchema, priceFeedDetailsSchema, priceFeedStoresSchema } from "./schemas.js";
12
+ import { erc20Abi } from "viem";
5
13
  //#region src/permissionless/api/oracles/PermissionlessOracles.ts
6
14
  const GET_PRICES_GAS_LIMIT_BY_CHAIN_ID = { 143: 100000000n };
7
15
  const GET_PRICES_CHUNK_SIZE = 200;
8
16
  /**
17
+ * What a market slot is: an oracle, a token, and whether it is the reserve
18
+ * one. Not the market — a market that has switched oracles has rows under
19
+ * each, and the slots are the old oracle's and the new one's separately.
20
+ */
21
+ function slotKey(oracle, token, reserve) {
22
+ return `${oracle.toLowerCase()}:${token.toLowerCase()}:${reserve}`;
23
+ }
24
+ /** An unknown thrown value, as something a log line can carry. */
25
+ function describe(e) {
26
+ return e instanceof Error ? e.message : String(e);
27
+ }
28
+ /**
9
29
  * The price feeds of one chain: the PriceFeedStore as the backend has indexed
10
30
  * it, and the prices behind it.
11
31
  *
12
32
  * ```ts
13
33
  * const store = await permissionless.oracles.store({ chainId: 1 });
14
- * const { prices } = await permissionless.oracles.prices({ chainId: 1 });
34
+ * const prices = await permissionless.oracles.getPrices(
35
+ * store.priceFeeds.map(({ address }) => ({ chainId: 1, address })),
36
+ * );
15
37
  * ```
16
38
  *
39
+ * The backend answers what it has indexed; anything that is only true at a
40
+ * block — a price, a market cap, a quota in one currency, the period an
41
+ * oracle holds for a slot — is read here, off the chain, and folded into what
42
+ * it answered. That is why these reads mix a request with a multicall rather
43
+ * than being either one.
44
+ *
17
45
  * Read-only. What the store carries is decided on chain, so putting a feed
18
46
  * there is a batch the instance owner executes — see
19
47
  * {@link InstanceOwnerTransactions} — not a row a client writes here.
@@ -29,11 +57,39 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
29
57
  }
30
58
  /**
31
59
  * The store with the assets and feeds of one chain.
60
+ *
61
+ * {@link stores} narrowed to one and unwrapped, which is the whole of it:
62
+ * there is one route either way, and a chain the backend does not serve has
63
+ * no store to answer with rather than an empty one.
64
+ *
65
+ * @throws When the backend serves no store for the chain.
32
66
  **/
33
67
  async store({ chainId }) {
68
+ const [store] = await this.stores({ chainId });
69
+ if (!store) throw new Error(`no PriceFeedStore served for chain ${chainId}`);
70
+ return store;
71
+ }
72
+ /**
73
+ * The same stores for every chain the backend serves.
74
+ *
75
+ * One request rather than {@link store} per chain, which is what a page
76
+ * showing all of them would otherwise do: the backend assembles them in the
77
+ * same few queries it assembles one in, so the chains cost little more than
78
+ * the largest of them.
79
+ *
80
+ * Each entry names its own chain, so a store is never attributed by
81
+ * position. `chainId` narrows it to one, for a caller that wants the list
82
+ * shape either way.
83
+ *
84
+ * ```ts
85
+ * const stores = await permissionless.oracles.stores();
86
+ * ```
87
+ **/
88
+ async stores({ chainId } = {}) {
34
89
  return this.getData({
35
- path: `/pfs/${chainId}`,
36
- schema: priceFeedStoreSchema
90
+ path: "/pfs/stores",
91
+ query: { chainId: chainId?.toString() },
92
+ schema: priceFeedStoresSchema
37
93
  });
38
94
  }
39
95
  /**
@@ -51,14 +107,186 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
51
107
  * });
52
108
  * ```
53
109
  *
110
+ * Each market row also carries the staleness period that market's own
111
+ * oracle holds for the slot, read off the chain here — see
112
+ * {@link PermissionlessPriceFeedMarket.marketStalenessPeriod}.
113
+ *
54
114
  * @throws When the store does not carry the feed. A private draft is not
55
115
  * here — it lives in whichever app wrote it.
56
116
  **/
57
117
  async feed({ chainId, address }) {
58
- return this.getData({
118
+ const feed = address.toLowerCase();
119
+ const indexed = await this.getData({
59
120
  path: `/pfs/${chainId}/price-feed/${address}`,
60
121
  schema: priceFeedDetailsSchema
61
122
  });
123
+ const periods = await this.#stalenessPeriods(chainId, feed, indexed.markets);
124
+ return {
125
+ ...indexed,
126
+ markets: indexed.markets.map((market) => ({
127
+ ...market,
128
+ marketStalenessPeriod: periods.get(slotKey(market.priceOracle, market.token, market.reserve)) ?? null
129
+ }))
130
+ };
131
+ }
132
+ /**
133
+ * Staleness period each market's own oracle holds for the feed's slots,
134
+ * keyed by {@link slotKey}.
135
+ *
136
+ * One call per oracle rather than per slot: the compressor answers for a
137
+ * whole oracle at once, and a feed in a dozen markets of the same curator
138
+ * would otherwise pay a round trip per token. Scoped to the tokens actually
139
+ * asked about, since the unscoped overload returns the oracle's entire feed
140
+ * tree as well.
141
+ *
142
+ * Failures are warnings and not errors. A slot missing from the answer keeps
143
+ * its `null`, which the caller reports as "the oracle would not say" — the
144
+ * alternative is failing a read whose indexed half is perfectly good.
145
+ */
146
+ async #stalenessPeriods(chainId, feed, rows) {
147
+ const periods = /* @__PURE__ */ new Map();
148
+ if (rows.length === 0) return periods;
149
+ const tokensByOracle = /* @__PURE__ */ new Map();
150
+ for (const row of rows) {
151
+ let tokens = tokensByOracle.get(row.priceOracle);
152
+ if (!tokens) {
153
+ tokens = /* @__PURE__ */ new Set();
154
+ tokensByOracle.set(row.priceOracle, tokens);
155
+ }
156
+ tokens.add(row.token);
157
+ }
158
+ let client;
159
+ let compressor;
160
+ try {
161
+ client = this.#chains.client(chainId);
162
+ compressor = await new AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(AP_PRICE_FEED_COMPRESSOR);
163
+ } catch (e) {
164
+ this.logger?.warn(`no PriceFeedCompressor for chain ${chainId}, reporting no market staleness periods: ${describe(e)}`);
165
+ return periods;
166
+ }
167
+ const oracles = [...tokensByOracle.keys()];
168
+ const results = await client.multicall({
169
+ contracts: oracles.map((oracle) => ({
170
+ address: compressor,
171
+ abi: priceFeedCompressorAbi,
172
+ functionName: "getPriceOracleState",
173
+ args: [oracle, [...tokensByOracle.get(oracle) ?? []]]
174
+ })),
175
+ allowFailure: true
176
+ });
177
+ oracles.forEach((oracle, i) => {
178
+ const result = results[i];
179
+ if (result?.status !== "success") {
180
+ this.logger?.warn(`price oracle ${oracle} of chain ${chainId} would not report its feed map`);
181
+ return;
182
+ }
183
+ const { priceFeedMap } = result.result;
184
+ for (const entry of priceFeedMap) {
185
+ if (entry.priceFeed.toLowerCase() !== feed) continue;
186
+ periods.set(slotKey(oracle, entry.token, entry.reserve), Number(entry.stalenessPeriod));
187
+ }
188
+ });
189
+ return periods;
190
+ }
191
+ /**
192
+ * One asset of the store: the feeds allowed for it, and the markets that
193
+ * take it as collateral.
194
+ *
195
+ * The mirror of {@link feed}, and the call to reach for when the question is
196
+ * "what prices this token and what is it backing" rather than "where is this
197
+ * feed used". Both read the same market slots; which end they are indexed
198
+ * from is the difference.
199
+ *
200
+ * ```ts
201
+ * const { priceFeeds, markets, quotaUsedUsd } =
202
+ * await permissionless.oracles.asset({ chainId: 1, address: token });
203
+ * ```
204
+ *
205
+ * The quota totals are worked out here, over the very market rows this
206
+ * answers with — see {@link PermissionlessQuotaTotals}.
207
+ *
208
+ * @throws When the chain has no metadata for the address. An asset nothing
209
+ * was indexed for has no symbol or decimals, so there is no row to answer.
210
+ **/
211
+ async asset({ chainId, address }) {
212
+ const indexed = await this.getData({
213
+ path: `/pfs/${chainId}/asset/${address}`,
214
+ schema: assetDetailsSchema
215
+ });
216
+ const priceOf = await this.#underlyingPrices(indexed.markets.map((market) => ({
217
+ chainId,
218
+ underlyingPriceFeed: market.underlyingPriceFeed
219
+ })));
220
+ return {
221
+ ...indexed,
222
+ ...totalQuotas(indexed.markets, (feed) => priceOf(chainId, feed))
223
+ };
224
+ }
225
+ /**
226
+ * The price of every underlying the given quota rows name, looked up by
227
+ * chain and feed.
228
+ *
229
+ * Distinct feeds only, because an asset in a dozen markets of the same
230
+ * underlying names the same feed a dozen times, and a list of every chain's
231
+ * assets names a handful of feeds per chain between them all.
232
+ */
233
+ async #underlyingPrices(rows) {
234
+ const refs = /* @__PURE__ */ new Map();
235
+ for (const { chainId, underlyingPriceFeed } of rows) {
236
+ if (underlyingPriceFeed === null) continue;
237
+ const address = underlyingPriceFeed.toLowerCase();
238
+ refs.set(feedKey(chainId, address), {
239
+ chainId,
240
+ address
241
+ });
242
+ }
243
+ const prices = pricesByFeed(await this.getPrices([...refs.values()]));
244
+ return (chainId, feed) => prices.get(feedKey(chainId, feed));
245
+ }
246
+ /**
247
+ * Every asset the store carries, with what its markets make of it.
248
+ *
249
+ * Enough on its own to render a list of assets: the alternative is the
250
+ * store's whole read for the names plus a call per row for the quotas, and
251
+ * this is one request either way you scope it.
252
+ *
253
+ * Ordered by how central each asset is — the markets it underlies first,
254
+ * then what is quoted against it, then what it is allowed — so a consumer
255
+ * renders the rows as they arrive. Omit `chainId` for every chain the
256
+ * backend serves, ordered the same way across all of them.
257
+ *
258
+ * Each row also carries its quota totals and what this SDK's tables say the
259
+ * asset is, neither of which is served — see
260
+ * {@link PermissionlessAssetSummary}. The totals are what the last two terms
261
+ * of the order are over, so this waits for them rather than handing back a
262
+ * list that would reshuffle a moment later.
263
+ *
264
+ * ```ts
265
+ * const assets = await permissionless.oracles.assets({ chainId: 1 });
266
+ * const everywhere = await permissionless.oracles.assets();
267
+ * ```
268
+ **/
269
+ async assets({ chainId } = {}) {
270
+ const indexed = await this.getData({
271
+ path: "/pfs/assets",
272
+ query: { chainId: chainId?.toString() },
273
+ schema: assetSummariesSchema
274
+ });
275
+ const networks = /* @__PURE__ */ new Map();
276
+ for (const { chainId: id } of indexed) if (!networks.has(id)) networks.set(id, isSupportedNetwork(id) ? getNetworkType(id) : void 0);
277
+ const priceOf = await this.#underlyingPrices(indexed.flatMap((asset) => asset.marketQuotas.map((quota) => ({
278
+ chainId: asset.chainId,
279
+ underlyingPriceFeed: quota.underlyingPriceFeed
280
+ }))));
281
+ return indexed.map((asset) => {
282
+ const network = networks.get(asset.chainId);
283
+ return {
284
+ ...asset,
285
+ ...totalQuotas(asset.marketQuotas, (feed) => priceOf(asset.chainId, feed)),
286
+ assetType: network === void 0 ? null : getAssetType(asset.address, network) ?? null,
287
+ isRwa: network === void 0 ? false : isRWAToken(asset.address, network)
288
+ };
289
+ }).sort(byCentrality);
62
290
  }
63
291
  /**
64
292
  * The feeds one feed reads from, recursively.
@@ -81,69 +309,188 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
81
309
  });
82
310
  }
83
311
  /**
84
- * What the market values each of one feed's assets at.
312
+ * What the named feeds price, read off the chain.
85
313
  *
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.
314
+ * Prices exactly what is asked for, at the current block, across as many
315
+ * chains as the list names — one read per chain, so a screen listing every
316
+ * chain's feeds pays per chain and not per row. A feed the store does not
317
+ * carry prices the same way, which is what makes this the call to reach for
318
+ * after a deploy, or while a form is still choosing between candidates.
319
+ *
320
+ * Read in two passes. The first asks every feed what it reports as it
321
+ * stands, which is one multicall per chain; a feed that will not answer
322
+ * until it has been given a fresh one is then priced inside a simulation
323
+ * that updates it first, so a push-based feed prices as readily as a
324
+ * pull-based one. The second pass costs an `OnchainSDK` to attach, hence
325
+ * only the feeds that need it rather than all of them.
326
+ *
327
+ * `null` is a feed neither pass could read, and a chain with no client
328
+ * configured is every one of its feeds reading `null` rather than a failed
329
+ * call — the figures built on them are floors either way.
90
330
  *
91
331
  * ```ts
92
- * const { marketCaps } = await permissionless.oracles.feedMarketCaps({
93
- * chainId: 1,
94
- * address: feed,
95
- * });
332
+ * const [{ price }] = await permissionless.oracles.getPrices([
333
+ * { chainId: 1, address: feed },
334
+ * ]);
96
335
  * ```
97
- **/
98
- async feedMarketCaps({ chainId, address }) {
99
- return this.getData({
100
- path: `/pfs/${chainId}/price-feed/${address}/market-caps`,
101
- schema: priceFeedMarketCapsSchema
102
- });
103
- }
104
- /**
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.
108
336
  *
109
- * Chain-wide, and priced accordingly — see {@link feedMarketCaps} for one
110
- * feed.
337
+ * @returns One entry per feed asked for, in the order asked, each price in
338
+ * the 8 decimals every Gearbox feed reports.
111
339
  **/
112
- async prices({ chainId }) {
113
- return this.getData({
114
- path: `/pfs/${chainId}/prices`,
115
- schema: pricesSchema
116
- });
340
+ async getPrices(feeds) {
341
+ const byChain = /* @__PURE__ */ new Map();
342
+ for (const { chainId, address } of feeds) {
343
+ const addresses = byChain.get(chainId) ?? /* @__PURE__ */ new Set();
344
+ addresses.add(address.toLowerCase());
345
+ byChain.set(chainId, addresses);
346
+ }
347
+ const chainIds = [...byChain.keys()];
348
+ const results = await Promise.all(chainIds.map((chainId) => this.#pricesOf(chainId, [...byChain.get(chainId) ?? []])));
349
+ const prices = new Map(chainIds.map((id, i) => [id, results[i] ?? {}]));
350
+ return feeds.map(({ chainId, address }) => ({
351
+ chainId,
352
+ address,
353
+ price: prices.get(chainId)?.[address.toLowerCase()] ?? null
354
+ }));
355
+ }
356
+ /** One chain's half of {@link getPrices}: the cheap pass, then the rest. */
357
+ async #pricesOf(chainId, priceFeeds) {
358
+ let client;
359
+ try {
360
+ client = this.#chains.client(chainId);
361
+ } catch (e) {
362
+ this.logger?.warn(`chain ${chainId} has no client, reporting its ${priceFeeds.length} feed(s) unpriced: ${describe(e)}`);
363
+ return {};
364
+ }
365
+ let prices;
366
+ try {
367
+ prices = await getLatestPrices({
368
+ client,
369
+ priceFeeds
370
+ });
371
+ } catch (e) {
372
+ this.logger?.warn(`chain ${chainId} would not answer for its ${priceFeeds.length} feed(s), trying each with an update: ${describe(e)}`);
373
+ prices = {};
374
+ }
375
+ const stale = priceFeeds.filter((feed) => (prices[feed] ?? null) === null);
376
+ if (stale.length === 0) return prices;
377
+ try {
378
+ return {
379
+ ...prices,
380
+ ...await getPrices({
381
+ client,
382
+ priceFeeds: stale,
383
+ chunkSize: 200,
384
+ gasLimit: GET_PRICES_GAS_LIMIT_BY_CHAIN_ID[chainId]
385
+ })
386
+ };
387
+ } catch (e) {
388
+ this.logger?.warn(`chain ${chainId} would not price ${stale.length} of its feed(s) even with an update, reporting them unpriced: ${describe(e)}`);
389
+ return prices;
390
+ }
117
391
  }
118
392
  /**
119
- * The price each of the named feeds reports, read off the chain.
393
+ * What one chain's feeds value one chain's assets at: `price × totalSupply`
394
+ * per pair.
120
395
  *
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.
396
+ * Asked from whichever side the caller is looking at — one asset through
397
+ * each of its feeds, or one feed over each of the assets it prices — because
398
+ * a screen shows one row per feed or one row per asset, never the full
399
+ * cross product. Both answer the same pairs in the same shape.
126
400
  *
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.
401
+ * Two reads per chain: the prices, and one multicall for the assets'
402
+ * supplies and decimals. Several scopes can be asked at once, which is how a
403
+ * table of every asset's feeds pays per chain rather than per row; the pairs
404
+ * come back in the order the scopes named them. A pair neither read could
405
+ * resolve has a `null` cap, which is not a zero.
130
406
  *
131
407
  * ```ts
132
- * const prices = await permissionless.oracles.getPrices({
408
+ * const caps = await permissionless.oracles.getMarketCap({
133
409
  * chainId: 1,
134
- * priceFeeds: [feed],
410
+ * asset: token,
411
+ * priceFeeds: [main, reserve],
135
412
  * });
136
413
  * ```
137
- *
138
- * @returns A price per feed, in the 8 decimals every Gearbox feed reports.
139
414
  **/
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]
415
+ async getMarketCap(scope) {
416
+ const pairs = (Array.isArray(scope) ? scope : [scope]).flatMap((one) => "asset" in one ? one.priceFeeds.map((priceFeed) => ({
417
+ chainId: one.chainId,
418
+ priceFeed: priceFeed.toLowerCase(),
419
+ asset: one.asset.toLowerCase()
420
+ })) : one.assets.map((asset) => ({
421
+ chainId: one.chainId,
422
+ priceFeed: one.priceFeed.toLowerCase(),
423
+ asset: asset.toLowerCase()
424
+ })));
425
+ if (pairs.length === 0) return [];
426
+ const feeds = /* @__PURE__ */ new Map();
427
+ const assetsByChain = /* @__PURE__ */ new Map();
428
+ for (const { chainId, priceFeed, asset } of pairs) {
429
+ feeds.set(feedKey(chainId, priceFeed), {
430
+ chainId,
431
+ address: priceFeed
432
+ });
433
+ const assets = assetsByChain.get(chainId) ?? /* @__PURE__ */ new Set();
434
+ assets.add(asset);
435
+ assetsByChain.set(chainId, assets);
436
+ }
437
+ const chainIds = [...assetsByChain.keys()];
438
+ const [prices, perChain] = await Promise.all([this.getPrices([...feeds.values()]), Promise.all(chainIds.map((chainId) => this.#supplies(chainId, [...assetsByChain.get(chainId) ?? []])))]);
439
+ const priced = pricesByFeed(prices);
440
+ const supplies = new Map(chainIds.map((id, i) => [id, perChain[i]]));
441
+ return pairs.map(({ chainId, priceFeed, asset }) => {
442
+ const supply = supplies.get(chainId)?.get(asset);
443
+ return {
444
+ chainId,
445
+ priceFeed,
446
+ asset,
447
+ cap: supply === void 0 ? null : toCap(priced.get(feedKey(chainId, priceFeed)), supply.totalSupply, supply.decimals)
448
+ };
449
+ });
450
+ }
451
+ /**
452
+ * Each asset's supply and the decimals it is counted in, which is what turns
453
+ * a supply into an amount.
454
+ *
455
+ * Both read rather than one of them taken from the index, so that a cap can
456
+ * be asked for an address nothing was indexed for at all — a token a form is
457
+ * still choosing, say. An asset missing from the answer is left out, and
458
+ * caps over it come back `null`.
459
+ */
460
+ async #supplies(chainId, assets) {
461
+ const supplies = /* @__PURE__ */ new Map();
462
+ let client;
463
+ try {
464
+ client = this.#chains.client(chainId);
465
+ } catch (e) {
466
+ this.logger?.warn(`chain ${chainId} has no client, reporting no market caps: ${describe(e)}`);
467
+ return supplies;
468
+ }
469
+ const results = await client.multicall({
470
+ contracts: assets.flatMap((address) => [{
471
+ address,
472
+ abi: erc20Abi,
473
+ functionName: "totalSupply"
474
+ }, {
475
+ address,
476
+ abi: erc20Abi,
477
+ functionName: "decimals"
478
+ }]),
479
+ allowFailure: true
480
+ });
481
+ assets.forEach((address, i) => {
482
+ const supply = results[2 * i];
483
+ const decimals = results[2 * i + 1];
484
+ if (decimals?.status !== "success") {
485
+ this.logger?.warn(`asset ${address} of chain ${chainId} would not report its decimals, reporting no market cap for it`);
486
+ return;
487
+ }
488
+ supplies.set(address, {
489
+ totalSupply: supply?.status === "success" ? supply.result : null,
490
+ decimals: Number(decimals.result)
491
+ });
146
492
  });
493
+ return supplies;
147
494
  }
148
495
  };
149
496
  //#endregion
@@ -0,0 +1,94 @@
1
+ import { formatUnits } from "viem";
2
+ //#region src/permissionless/api/oracles/enrich.ts
3
+ /**
4
+ * What the oracles namespace works out for itself once the backend has
5
+ * answered.
6
+ *
7
+ * All of it used to be the backend's, and all of it needs the chain: a quota
8
+ * is denominated in its market's own underlying and a market cap is a supply
9
+ * times a price, so none of these can be indexed — they can only be read at
10
+ * the block the reader is on. Keeping them here means one description of each
11
+ * rule rather than one per service that wants it, and a backend that holds no
12
+ * viem client at all.
13
+ **/
14
+ /** Identifies a feed across chains, since an address alone does not. */
15
+ function feedKey(chainId, address) {
16
+ return `${chainId}:${address.toLowerCase()}`;
17
+ }
18
+ /** Prices looked up the way {@link totalQuotas} and the caps need them. */
19
+ function pricesByFeed(prices) {
20
+ return new Map(prices.map(({ chainId, address, price }) => [feedKey(chainId, address), price]));
21
+ }
22
+ /**
23
+ * The asset's quota across its markets, totalled in USD.
24
+ *
25
+ * Each market's figures are converted at the price that market's own oracle
26
+ * holds for its underlying, which is the same number that market's accounting
27
+ * uses.
28
+ *
29
+ * Limits count only the markets still running, because a shut down market's
30
+ * limit is not borrowable; what is already quoted counts everywhere, because
31
+ * debt outstanding is exposure either way. A market whose underlying could not
32
+ * be priced is skipped, which makes both figures floors, and `null` is nothing
33
+ * to total rather than a zero.
34
+ *
35
+ * @param priceOf - The price each underlying feed reports, in the 8 decimals
36
+ * every Gearbox feed uses.
37
+ */
38
+ function totalQuotas(quotas, priceOf) {
39
+ let limit = 0;
40
+ let used = 0;
41
+ let anyLimit = false;
42
+ let anyUsed = false;
43
+ for (const quota of quotas) {
44
+ const raw = quota.underlyingPriceFeed === null ? null : priceOf(quota.underlyingPriceFeed);
45
+ if (raw === null || raw === void 0) continue;
46
+ const price = Number(formatUnits(raw, 8));
47
+ if (quota.quotaUsed !== null) {
48
+ used += quota.quotaUsed * price;
49
+ anyUsed = true;
50
+ }
51
+ if (quota.quotaLimit !== null && !quota.isShutdown) {
52
+ limit += quota.quotaLimit * price;
53
+ anyLimit = true;
54
+ }
55
+ }
56
+ return {
57
+ quotaLimitUsd: anyLimit ? limit : null,
58
+ quotaUsedUsd: anyUsed ? used : null
59
+ };
60
+ }
61
+ /**
62
+ * What one feed values one asset's supply at: `price × totalSupply`.
63
+ *
64
+ * Multiplied as integers and formatted once, rather than through two floats:
65
+ * an 8-decimal price times an 18-decimal supply loses its small end to a JS
66
+ * number long before it loses the large one, and the figure is a total rather
67
+ * than an estimate.
68
+ *
69
+ * `null` if either side could not be read — an asset nobody could price is
70
+ * not an asset worth nothing.
71
+ */
72
+ function toCap(price, totalSupply, decimals) {
73
+ if (price === null || price === void 0 || totalSupply === null || totalSupply === void 0) return null;
74
+ return formatUnits(price * totalSupply, 8 + decimals);
75
+ }
76
+ /** Larger first, with `null` after every figure including a real zero. */
77
+ function descending(a, b) {
78
+ return (b ?? -1) - (a ?? -1);
79
+ }
80
+ /**
81
+ * Assets ordered the way a reader scans them: what the protocol is built on
82
+ * first, then what is actually borrowed against it, then what it is merely
83
+ * allowed to be borrowed against.
84
+ *
85
+ * Applied here and not by the backend because the two middle terms are the
86
+ * converted quotas, which only exist once the chain has been read. The
87
+ * backend orders by the first term and the tie-breakers, so a caller reading
88
+ * the route directly still gets a stable order; this refines it.
89
+ */
90
+ function byCentrality(a, b) {
91
+ return b.underlyingMarketCount - a.underlyingMarketCount || descending(a.quotaUsedUsd, b.quotaUsedUsd) || descending(a.quotaLimitUsd, b.quotaLimitUsd) || a.symbol.localeCompare(b.symbol) || a.address.localeCompare(b.address) || a.chainId - b.chainId;
92
+ }
93
+ //#endregion
94
+ export { byCentrality, feedKey, pricesByFeed, toCap, totalQuotas };