@gearbox-protocol/sdk 18.3.1 → 18.4.0

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