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

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 (56) hide show
  1. package/dist/cjs/permissionless/api/index.js +30 -0
  2. package/dist/cjs/permissionless/api/oracles/PermissionlessOracles.js +191 -0
  3. package/dist/cjs/permissionless/api/oracles/index.js +32 -0
  4. package/dist/cjs/permissionless/api/oracles/schemas.js +17 -0
  5. package/dist/cjs/permissionless/api/oracles/score/formula.js +61 -0
  6. package/dist/cjs/permissionless/api/oracles/score/index.js +11 -0
  7. package/dist/cjs/permissionless/api/oracles/score/run.js +171 -0
  8. package/dist/cjs/permissionless/api/oracles/score/types.js +1 -0
  9. package/dist/cjs/permissionless/api/oracles/stress/classify.js +258 -0
  10. package/dist/cjs/permissionless/api/oracles/stress/index.js +23 -0
  11. package/dist/cjs/permissionless/api/oracles/stress/override.js +125 -0
  12. package/dist/cjs/permissionless/api/oracles/stress/run.js +435 -0
  13. package/dist/cjs/permissionless/api/oracles/stress/score.js +98 -0
  14. package/dist/cjs/permissionless/api/oracles/stress/types.js +1 -0
  15. package/dist/cjs/permissionless/index.js +31 -0
  16. package/dist/cjs/permissionless/utils/index.js +1 -0
  17. package/dist/cjs/permissionless/utils/price-update/get-prices.js +39 -0
  18. package/dist/cjs/permissionless/utils/price-update/index.js +1 -0
  19. package/dist/esm/permissionless/api/index.js +7 -1
  20. package/dist/esm/permissionless/api/oracles/PermissionlessOracles.js +193 -2
  21. package/dist/esm/permissionless/api/oracles/index.js +10 -1
  22. package/dist/esm/permissionless/api/oracles/schemas.js +16 -1
  23. package/dist/esm/permissionless/api/oracles/score/formula.js +55 -0
  24. package/dist/esm/permissionless/api/oracles/score/index.js +4 -0
  25. package/dist/esm/permissionless/api/oracles/score/run.js +170 -0
  26. package/dist/esm/permissionless/api/oracles/score/types.js +1 -0
  27. package/dist/esm/permissionless/api/oracles/stress/classify.js +256 -0
  28. package/dist/esm/permissionless/api/oracles/stress/index.js +6 -0
  29. package/dist/esm/permissionless/api/oracles/stress/override.js +119 -0
  30. package/dist/esm/permissionless/api/oracles/stress/run.js +429 -0
  31. package/dist/esm/permissionless/api/oracles/stress/score.js +95 -0
  32. package/dist/esm/permissionless/api/oracles/stress/types.js +1 -0
  33. package/dist/esm/permissionless/index.js +8 -2
  34. package/dist/esm/permissionless/utils/index.js +2 -2
  35. package/dist/esm/permissionless/utils/price-update/get-prices.js +39 -1
  36. package/dist/esm/permissionless/utils/price-update/index.js +2 -2
  37. package/dist/types/permissionless/api/index.d.ts +10 -2
  38. package/dist/types/permissionless/api/oracles/PermissionlessOracles.d.ts +115 -1
  39. package/dist/types/permissionless/api/oracles/index.d.ts +12 -2
  40. package/dist/types/permissionless/api/oracles/schemas.d.ts +47 -0
  41. package/dist/types/permissionless/api/oracles/score/formula.d.ts +39 -0
  42. package/dist/types/permissionless/api/oracles/score/index.d.ts +4 -0
  43. package/dist/types/permissionless/api/oracles/score/run.d.ts +24 -0
  44. package/dist/types/permissionless/api/oracles/score/types.d.ts +113 -0
  45. package/dist/types/permissionless/api/oracles/stress/classify.d.ts +57 -0
  46. package/dist/types/permissionless/api/oracles/stress/index.d.ts +6 -0
  47. package/dist/types/permissionless/api/oracles/stress/override.d.ts +59 -0
  48. package/dist/types/permissionless/api/oracles/stress/run.d.ts +89 -0
  49. package/dist/types/permissionless/api/oracles/stress/score.d.ts +57 -0
  50. package/dist/types/permissionless/api/oracles/stress/types.d.ts +272 -0
  51. package/dist/types/permissionless/api/oracles/types.d.ts +58 -0
  52. package/dist/types/permissionless/index.d.ts +11 -3
  53. package/dist/types/permissionless/utils/index.d.ts +2 -2
  54. package/dist/types/permissionless/utils/price-update/get-prices.d.ts +16 -0
  55. package/dist/types/permissionless/utils/price-update/index.d.ts +2 -2
  56. package/package.json +1 -1
@@ -32,6 +32,16 @@ const latestRoundDataAbi = [{
32
32
  stateMutability: "view",
33
33
  type: "function"
34
34
  }];
35
+ const decimalsAbi = [{
36
+ inputs: [],
37
+ name: "decimals",
38
+ outputs: [{
39
+ name: "",
40
+ type: "uint8"
41
+ }],
42
+ stateMutability: "view",
43
+ type: "function"
44
+ }];
35
45
  function getLatestRoundDataCall(priceFeed) {
36
46
  return {
37
47
  address: priceFeed,
@@ -41,6 +51,34 @@ function getLatestRoundDataCall(priceFeed) {
41
51
  };
42
52
  }
43
53
  /**
54
+ * The scale each feed's answer is in, in one multicall.
55
+ *
56
+ * Part of the Chainlink interface every feed in a Gearbox tree implements,
57
+ * and the only way to read an answer that is not an oracle's own: a feed an
58
+ * oracle holds reports 8 decimals by construction, while the feeds beneath a
59
+ * composite are whatever was deployed — an ETH/USD aggregator at 8 and a
60
+ * rate leg at 18 sit under the same parent.
61
+ *
62
+ * `null` is a feed that would not answer, which a caller should treat as
63
+ * unknown rather than defaulting it to 8.
64
+ */
65
+ async function getFeedDecimals({ client, priceFeeds }) {
66
+ if (priceFeeds.length === 0) return {};
67
+ const results = await client.multicall({
68
+ contracts: priceFeeds.map((priceFeed) => ({
69
+ address: priceFeed,
70
+ abi: decimalsAbi,
71
+ functionName: "decimals",
72
+ args: []
73
+ })),
74
+ allowFailure: true
75
+ });
76
+ return Object.fromEntries(priceFeeds.map((priceFeed, index) => {
77
+ const result = results[index];
78
+ return [priceFeed, result?.status === "success" ? Number(result.result) : null];
79
+ }));
80
+ }
81
+ /**
44
82
  * What the feeds report as they stand, in one multicall.
45
83
  *
46
84
  * What {@link getPrices} does without the part that makes it expensive: no
@@ -107,5 +145,6 @@ async function getPrices({ client, priceFeeds, chunkSize = 10, gasLimit }) {
107
145
  }), {});
108
146
  }
109
147
  //#endregion
148
+ exports.getFeedDecimals = getFeedDecimals;
110
149
  exports.getLatestPrices = getLatestPrices;
111
150
  exports.getPrices = getPrices;
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_permissionless_utils_price_update_get_prices = require("./get-prices.js");
3
3
  const require_permissionless_utils_price_update_get_updatable_feeds = require("./get-updatable-feeds.js");
4
4
  const require_permissionless_utils_price_update_get_price_update_tx = require("./get-price-update-tx.js");
5
+ exports.getFeedDecimals = require_permissionless_utils_price_update_get_prices.getFeedDecimals;
5
6
  exports.getLatestPrices = require_permissionless_utils_price_update_get_prices.getLatestPrices;
6
7
  exports.getPriceUpdateTx = require_permissionless_utils_price_update_get_price_update_tx.getPriceUpdateTx;
7
8
  exports.getPrices = require_permissionless_utils_price_update_get_prices.getPrices;
@@ -6,10 +6,16 @@ import "./chains/index.js";
6
6
  import { deriveEffectiveStalenessPeriod } from "./deploy/effective-staleness.js";
7
7
  import { DEFAULT_DEPLOY_SALT, PermissionlessDeploy, priceFeedSalt } from "./deploy/PermissionlessDeploy.js";
8
8
  import "./deploy/index.js";
9
+ import { classifySources, sourcesByFeed } from "./oracles/stress/classify.js";
10
+ import { UNBOUNDED_DOWN, UNBOUNDED_UP, groupOverride, perturb, rateStub, roundDataStub } from "./oracles/stress/override.js";
11
+ import { scoreGroup, slotHarm, verdictOf } from "./oracles/stress/score.js";
12
+ import { DEFAULT_SCENARIOS, RATE_FEED_TYPE, readForest, readRateTargets, readUnder, runStressTest } from "./oracles/stress/run.js";
13
+ import { REVERT_SCORE, SCORE_MULTIPLIER, factorOf, finalPrice, scoreOfFactor, worstOf } from "./oracles/score/formula.js";
14
+ import { runAssetScores } from "./oracles/score/run.js";
9
15
  import { GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, PermissionlessOracles } from "./oracles/PermissionlessOracles.js";
10
16
  import { InstanceOwnerTransactions } from "./transactions/InstanceOwnerTransactions.js";
11
17
  import { GearboxPermissionless } from "./GearboxPermissionless.js";
12
18
  import "./oracles/index.js";
13
19
  import "./transactions/index.js";
14
20
  import "./types.js";
15
- export { ChainsNamespace, DEFAULT_DEPLOY_SALT, GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, GearboxPermissionless, InstanceOwnerTransactions, PermissionlessAnalytics, PermissionlessChainUnreachableError, PermissionlessDeploy, PermissionlessNotAttachedError, PermissionlessOracles, PriceFeedNotInStoreError, PriceFeedSaltMissingError, PriceFeedStalenessUnknownError, deriveEffectiveStalenessPeriod, priceFeedSalt };
21
+ export { ChainsNamespace, DEFAULT_DEPLOY_SALT, DEFAULT_SCENARIOS, GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, GearboxPermissionless, InstanceOwnerTransactions, PermissionlessAnalytics, PermissionlessChainUnreachableError, PermissionlessDeploy, PermissionlessNotAttachedError, PermissionlessOracles, PriceFeedNotInStoreError, PriceFeedSaltMissingError, PriceFeedStalenessUnknownError, RATE_FEED_TYPE, REVERT_SCORE, SCORE_MULTIPLIER, UNBOUNDED_DOWN, UNBOUNDED_UP, classifySources, deriveEffectiveStalenessPeriod, factorOf, finalPrice, groupOverride, perturb, priceFeedSalt, rateStub, readForest, readRateTargets, readUnder, roundDataStub, runAssetScores, runStressTest, scoreGroup, scoreOfFactor, slotHarm, sourcesByFeed, verdictOf, worstOf };
@@ -6,9 +6,11 @@ import "../../../onchain/index.js";
6
6
  import { AbstractOffchainNamespace } from "../../../offchain/AbstractOffchainNamespace.js";
7
7
  import "../../deployment/addresses.js";
8
8
  import { AddressProviderContract } from "../../bindings/address-provider.js";
9
- import { getLatestPrices, getPrices } from "../../utils/price-update/get-prices.js";
9
+ import { getFeedDecimals, getLatestPrices, getPrices } from "../../utils/price-update/get-prices.js";
10
10
  import { byCentrality, feedKey, pricesByFeed, toCap, totalQuotas } from "./enrich.js";
11
- import { assetDetailsSchema, assetSummariesSchema, priceFeedDetailsSchema, priceFeedStoresSchema } from "./schemas.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";
12
14
  import { erc20Abi } from "viem";
13
15
  //#region src/permissionless/api/oracles/PermissionlessOracles.ts
14
16
  const GET_PRICES_GAS_LIMIT_BY_CHAIN_ID = { 143: 100000000n };
@@ -93,6 +95,31 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
93
95
  });
94
96
  }
95
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
120
+ });
121
+ }
122
+ /**
96
123
  * One feed of the store: what it is, which assets it may price, and which
97
124
  * market slots it currently fills.
98
125
  *
@@ -289,6 +316,111 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
289
316
  }).sort(byCentrality);
290
317
  }
291
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
+ * Each source group behind an asset's feeds — Chainlink, Redstone, Lido and
365
+ * so on — is made in turn to answer five times what it answers now, and a
366
+ * market scores by how far that moves its final price, `min(main,
367
+ * reserve)`: 10 for not at all, 0 for the full five times, on a log scale.
368
+ * A price that stops answering scores 5. An asset scores its worst running
369
+ * market that takes it as collateral.
370
+ *
371
+ * Simulated on the chain as it stands, through state overrides in
372
+ * `eth_call`: one call per source group per chain, so the node behind the
373
+ * client has to accept overrides. A chain with no client configured, or
374
+ * whose node refuses, 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
+ });
422
+ }
423
+ /**
292
424
  * The feeds one feed reads from, recursively.
293
425
  *
294
426
  * Answers for any feed the chain has indexed, store member or not: a
@@ -353,6 +485,65 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
353
485
  price: prices.get(chainId)?.[address.toLowerCase()] ?? null
354
486
  }));
355
487
  }
488
+ /**
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
+ * ```
509
+ *
510
+ * @returns One entry per feed asked for, in the order asked.
511
+ **/
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
+ }
356
547
  /** One chain's half of {@link getPrices}: the cheap pass, then the rest. */
357
548
  async #pricesOf(chainId, priceFeeds) {
358
549
  let client;
@@ -1,2 +1,11 @@
1
- export { GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, PermissionlessOracles } from "./PermissionlessOracles.js";
1
+ import { classifySources, sourcesByFeed } from "./stress/classify.js";
2
+ import { UNBOUNDED_DOWN, UNBOUNDED_UP, groupOverride, perturb, rateStub, roundDataStub } from "./stress/override.js";
3
+ import { scoreGroup, slotHarm, verdictOf } from "./stress/score.js";
4
+ import { DEFAULT_SCENARIOS, RATE_FEED_TYPE, readForest, readRateTargets, readUnder, runStressTest } from "./stress/run.js";
5
+ import { REVERT_SCORE, SCORE_MULTIPLIER, factorOf, finalPrice, scoreOfFactor, worstOf } from "./score/formula.js";
6
+ import { runAssetScores } from "./score/run.js";
7
+ import { GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, PermissionlessOracles } from "./PermissionlessOracles.js";
8
+ import "./score/index.js";
9
+ import "./stress/index.js";
2
10
  import "./types.js";
11
+ export { DEFAULT_SCENARIOS, GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, PermissionlessOracles, RATE_FEED_TYPE, REVERT_SCORE, SCORE_MULTIPLIER, UNBOUNDED_DOWN, UNBOUNDED_UP, classifySources, factorOf, finalPrice, groupOverride, perturb, rateStub, readForest, readRateTargets, readUnder, roundDataStub, runAssetScores, runStressTest, scoreGroup, scoreOfFactor, slotHarm, sourcesByFeed, verdictOf, worstOf };
@@ -75,6 +75,21 @@ const priceFeedMarketSchema = marketSchema.extend({
75
75
  reserve: z.boolean(),
76
76
  priceOracle: addressSchema
77
77
  });
78
+ /**
79
+ * {@link PermissionlessMarketSlot} — the same slot read from the chain's end,
80
+ * so the feed is a column rather than what was asked for.
81
+ **/
82
+ const marketSlotSchema = priceFeedMarketSchema.extend({
83
+ chainId: z.number(),
84
+ underlyingToken: addressSchema,
85
+ isShutdown: z.boolean(),
86
+ priceFeed: addressSchema,
87
+ priceFeedName: z.string().nullable(),
88
+ priceFeedInStore: z.boolean(),
89
+ underlyingPriceFeed: addressSchema.nullable()
90
+ });
91
+ /** Every slot in scope, across whichever chains the read covered. */
92
+ const marketSlotsSchema = z.array(marketSlotSchema);
78
93
  /** {@link PermissionlessIndexedPriceFeedDetails} */
79
94
  const priceFeedDetailsSchema = z.looseObject({
80
95
  chainId: z.number(),
@@ -121,4 +136,4 @@ const assetSummarySchema = z.looseObject({
121
136
  /** The list of {@link PermissionlessAssetSummary}, already ordered. */
122
137
  const assetSummariesSchema = z.array(assetSummarySchema);
123
138
  //#endregion
124
- export { assetDetailsSchema, assetMarketFeedSchema, assetMarketSchema, assetQuotaSchema, assetSchema, assetSummariesSchema, assetSummarySchema, priceFeedAssetSchema, priceFeedDetailsSchema, priceFeedMarketSchema, priceFeedSchema, priceFeedStoreSchema, priceFeedStoresSchema };
139
+ export { assetDetailsSchema, assetMarketFeedSchema, assetMarketSchema, assetQuotaSchema, assetSchema, assetSummariesSchema, assetSummarySchema, marketSlotSchema, marketSlotsSchema, priceFeedAssetSchema, priceFeedDetailsSchema, priceFeedMarketSchema, priceFeedSchema, priceFeedStoreSchema, priceFeedStoresSchema };
@@ -0,0 +1,55 @@
1
+ //#region src/permissionless/api/oracles/score/formula.ts
2
+ /** What every source of a group is made to answer, as a multiple of now. */
3
+ const SCORE_MULTIPLIER = 5;
4
+ /**
5
+ * The score of a price that stops answering under the lie.
6
+ *
7
+ * Half marks: nobody can borrow against a wrong number, but nobody can be
8
+ * liquidated either until the feed is replaced.
9
+ */
10
+ const REVERT_SCORE = 5;
11
+ /**
12
+ * 0 to 10 by how far the final price moved, on a log scale against the lie
13
+ * itself: 10 for a price that did not move, 0 for one that moved by the full
14
+ * {@link SCORE_MULTIPLIER} or more, either way. Rounded to a half point.
15
+ *
16
+ * A bound holding a price within a few percent keeps a 10; a price that let
17
+ * half the lie through, ×√5, scores 5.
18
+ */
19
+ function scoreOfFactor(factor) {
20
+ if (factor === null || !Number.isFinite(factor) || factor <= 0) return 5;
21
+ const moved = Math.abs(Math.log(factor)) / Math.log(5);
22
+ return Math.round(10 * Math.max(0, 1 - moved) * 2) / 2;
23
+ }
24
+ /**
25
+ * The price a market settles on: the lower of main and reserve, or the main
26
+ * feed's alone where there is no reserve to compare it with. `null` where a
27
+ * feed it needs does not answer.
28
+ */
29
+ function finalPrice(main, reserve) {
30
+ if (main === null || reserve === null) return null;
31
+ if (reserve === void 0) return main;
32
+ return main < reserve ? main : reserve;
33
+ }
34
+ /** `stressed / base` as a float, `null` where the stressed price is gone. */
35
+ function factorOf(base, stressed) {
36
+ if (stressed === null) return null;
37
+ return Number(stressed) / Number(base);
38
+ }
39
+ /**
40
+ * The market's score and the group it comes from: the lowest of its groups,
41
+ * ties going to the group that moved the price further. 10 where no source
42
+ * feeds the price at all, since nothing can be made to lie about it.
43
+ */
44
+ function worstOf(impacts) {
45
+ const distance = (impact) => impact.factor === null ? Infinity : Math.abs(Math.log(impact.factor));
46
+ const sorted = [...impacts].sort((a, b) => a.score - b.score || distance(b) - distance(a));
47
+ const worst = sorted[0] ?? null;
48
+ return {
49
+ score: worst?.score ?? 10,
50
+ impacts: sorted,
51
+ worst
52
+ };
53
+ }
54
+ //#endregion
55
+ export { REVERT_SCORE, SCORE_MULTIPLIER, factorOf, finalPrice, scoreOfFactor, worstOf };
@@ -0,0 +1,4 @@
1
+ import { REVERT_SCORE, SCORE_MULTIPLIER, factorOf, finalPrice, scoreOfFactor, worstOf } from "./formula.js";
2
+ import { runAssetScores } from "./run.js";
3
+ import "./types.js";
4
+ export { REVERT_SCORE, SCORE_MULTIPLIER, factorOf, finalPrice, runAssetScores, scoreOfFactor, worstOf };
@@ -0,0 +1,170 @@
1
+ import { classifySources, sourcesByFeed } from "../stress/classify.js";
2
+ import { RATE_FEED_TYPE, readForest, readRateTargets, readUnder } from "../stress/run.js";
3
+ import { factorOf, finalPrice, scoreOfFactor, worstOf } from "./formula.js";
4
+ import { formatUnits } from "viem";
5
+ //#region src/permissionless/api/oracles/score/run.ts
6
+ const ZERO_TYPE = "PRICE_FEED::ZERO";
7
+ /** Groups simulated at once: one `eth_call` each, all against one node. */
8
+ const CONCURRENCY = 6;
9
+ const feedOf = (slot) => slot.priceFeed.toLowerCase();
10
+ /**
11
+ * Every asset of one chain, scored by what each of its source groups can do
12
+ * to the price its running markets hold for it.
13
+ *
14
+ * One read of the oracles' feed trees, one of the LP feeds' rate contracts,
15
+ * one of every market feed as it stands — then one `eth_call` per source
16
+ * group, with the group's sources overridden to answer
17
+ * {@link SCORE_MULTIPLIER} times what they answer now and every market feed
18
+ * read under it.
19
+ **/
20
+ async function runAssetScores({ client, chainId, slots, compressor, logger }) {
21
+ const running = slots.filter((slot) => !slot.isShutdown);
22
+ const oracles = [...new Set(running.map((slot) => slot.priceOracle.toLowerCase()))];
23
+ const { nodes, answers, unreadableOracles } = await readForest(client, compressor, oracles);
24
+ for (const oracle of unreadableOracles) logger?.warn(`price oracle ${oracle} of chain ${chainId} would not report its feed tree; the markets on it are not scored`);
25
+ const { targets, baselines: rateBaselines } = await readRateTargets(client, [...nodes.values()].filter((node) => RATE_FEED_TYPE.test(node.contractType)).map((node) => node.address));
26
+ const { sources, unresolved } = classifySources(chainId, [...nodes.values()], targets, (target) => rateBaselines.get(target) ?? answers.get(target) ?? null);
27
+ for (const node of unresolved) logger?.warn(`feed ${node.address} of chain ${chainId} would not say what it reads its rate from; its protocol is not perturbed`);
28
+ const slotsByPosition = /* @__PURE__ */ new Map();
29
+ for (const slot of running) {
30
+ const key = `${slot.market.toLowerCase()}:${slot.token.toLowerCase()}`;
31
+ const entry = slotsByPosition.get(key) ?? {};
32
+ entry[slot.reserve ? "reserve" : "main"] = slot;
33
+ slotsByPosition.set(key, entry);
34
+ }
35
+ const positions = [];
36
+ for (const { main, reserve } of slotsByPosition.values()) {
37
+ if (!main || main.isUnderlying) continue;
38
+ const mainNode = nodes.get(feedOf(main));
39
+ if (!mainNode || mainNode.contractType === ZERO_TYPE) continue;
40
+ const notes = [];
41
+ let reserveFeed;
42
+ if (!reserve) notes.push("no reserve feed");
43
+ else if (nodes.get(feedOf(reserve))?.contractType === ZERO_TYPE) notes.push("reserve is a ZeroPriceFeed");
44
+ else {
45
+ reserveFeed = feedOf(reserve);
46
+ if (reserveFeed === feedOf(main)) notes.push("reserve is the main feed");
47
+ }
48
+ positions.push({
49
+ main,
50
+ reserve,
51
+ reserveFeed,
52
+ notes
53
+ });
54
+ }
55
+ const priced = [...new Set(positions.flatMap(({ main, reserveFeed }) => reserveFeed ? [feedOf(main), reserveFeed] : [feedOf(main)]))];
56
+ if (priced.length === 0) return [];
57
+ const underlyingOf = (slot) => slot.underlyingPriceFeed?.toLowerCase();
58
+ const roots = [.../* @__PURE__ */ new Set([...priced, ...positions.map(({ main }) => underlyingOf(main)).filter((feed) => feed !== void 0)])];
59
+ const updatedAt = BigInt(Math.floor(Date.now() / 1e3));
60
+ const drivable = (source) => source !== void 0 && source.perturbable && source.baseline !== null;
61
+ const fresh = sources.filter((source) => drivable(source) && source.kind === "feed");
62
+ const asIs = await readUnder(client, roots, [], 1, updatedAt);
63
+ const stale = roots.filter((root) => (asIs.get(root) ?? null) === null);
64
+ const freshened = stale.length > 0 ? await readUnder(client, stale, [], 1, updatedAt, fresh) : /* @__PURE__ */ new Map();
65
+ const base = new Map(roots.map((root) => [root, asIs.get(root) ?? freshened.get(root) ?? null]));
66
+ const asIsRoots = roots.filter((root) => (asIs.get(root) ?? null) !== null);
67
+ const freshRoots = stale.filter((root) => (freshened.get(root) ?? null) !== null);
68
+ /** Every root under a lie, each read the way its base was. */
69
+ const readLying = async (members) => {
70
+ const [plain, refreshed] = await Promise.all([asIsRoots.length > 0 ? readUnder(client, asIsRoots, members, 5, updatedAt) : /* @__PURE__ */ new Map(), freshRoots.length > 0 ? readUnder(client, freshRoots, members, 5, updatedAt, fresh) : /* @__PURE__ */ new Map()]);
71
+ return new Map([...plain, ...refreshed]);
72
+ };
73
+ for (const position of positions) if (position.reserveFeed && (base.get(position.reserveFeed) ?? null) === null) {
74
+ position.reserveFeed = void 0;
75
+ position.notes.push("reserve does not answer");
76
+ }
77
+ const reach = sourcesByFeed(roots, nodes, sources);
78
+ const sourceByTarget = new Map(sources.map((source) => [source.target, source]));
79
+ const byGroup = /* @__PURE__ */ new Map();
80
+ for (const source of sources.filter(drivable)) byGroup.set(source.group, [...byGroup.get(source.group) ?? [], source]);
81
+ const reachedGroups = /* @__PURE__ */ new Set();
82
+ for (const root of priced) for (const target of reach.get(root) ?? []) {
83
+ const source = sourceByTarget.get(target);
84
+ if (drivable(source)) reachedGroups.add(source.group);
85
+ }
86
+ const stressed = /* @__PURE__ */ new Map();
87
+ const queue = [...reachedGroups];
88
+ for (let i = 0; i < queue.length; i += CONCURRENCY) await Promise.all(queue.slice(i, i + CONCURRENCY).map(async (group) => {
89
+ stressed.set(group, await readLying(byGroup.get(group) ?? []));
90
+ }));
91
+ const groupsOf = (feed) => {
92
+ const out = /* @__PURE__ */ new Map();
93
+ for (const target of feed ? reach.get(feed) ?? [] : []) {
94
+ const source = sourceByTarget.get(target);
95
+ if (drivable(source)) out.set(source.group, [...out.get(source.group) ?? [], source]);
96
+ }
97
+ return out;
98
+ };
99
+ const byAsset = /* @__PURE__ */ new Map();
100
+ for (const { main, reserve, reserveFeed, notes } of positions) {
101
+ const mainFeed = feedOf(main);
102
+ const before = finalPrice(base.get(mainFeed) ?? null, reserveFeed ? base.get(reserveFeed) ?? null : void 0);
103
+ if (before === null || before <= 0n) {
104
+ logger?.warn(`feed ${mainFeed} of chain ${chainId} does not answer; ${main.tokenSymbol ?? main.token} in ${main.marketName ?? main.market} is not scored`);
105
+ continue;
106
+ }
107
+ const onMain = groupsOf(mainFeed);
108
+ const onReserve = groupsOf(reserveFeed);
109
+ const impacts = [.../* @__PURE__ */ new Set([...onMain.keys(), ...onReserve.keys()])].map((group) => {
110
+ const under = stressed.get(group) ?? /* @__PURE__ */ new Map();
111
+ const after = finalPrice(under.get(mainFeed) ?? null, reserveFeed ? under.get(reserveFeed) ?? null : void 0);
112
+ const factor = factorOf(before, after);
113
+ const underlying = underlyingOf(main);
114
+ const debtBefore = underlying ? base.get(underlying) ?? null : null;
115
+ const debtFactor = debtBefore === null || debtBefore <= 0n || !underlying ? null : factorOf(debtBefore, under.get(underlying) ?? null);
116
+ const ratioFactor = factor === null || debtFactor === null || debtFactor === 0 ? null : factor / debtFactor;
117
+ const members = [...onMain.get(group) ?? [], ...onReserve.get(group) ?? []];
118
+ return {
119
+ group,
120
+ identified: members.every((source) => source.identified),
121
+ feeds: [...new Set(members.map((source) => source.description))],
122
+ reaches: onMain.has(group) ? onReserve.has(group) ? "both" : "main" : "reserve",
123
+ factor,
124
+ ratioFactor,
125
+ score: scoreOfFactor(factor)
126
+ };
127
+ });
128
+ const unverified = reserveFeed !== void 0 && impacts.some((impact) => !impact.identified && impact.reaches !== "both");
129
+ const side = (slot) => ({
130
+ feed: feedOf(slot),
131
+ name: slot.priceFeedName,
132
+ contractType: nodes.get(feedOf(slot))?.contractType ?? "",
133
+ sources: [...groupsOf(feedOf(slot)).keys()]
134
+ });
135
+ const asset = main.token.toLowerCase();
136
+ const entry = byAsset.get(asset) ?? {
137
+ symbol: main.tokenSymbol,
138
+ markets: []
139
+ };
140
+ byAsset.set(asset, entry);
141
+ entry.markets.push({
142
+ market: main.market,
143
+ marketName: main.marketName,
144
+ marketConfigurator: main.marketConfigurator,
145
+ curatorName: main.curatorName,
146
+ main: side(main),
147
+ reserve: reserve ? side(reserve) : null,
148
+ hasReserve: reserveFeed !== void 0,
149
+ price: Number(formatUnits(before, 8)),
150
+ unverified,
151
+ notes,
152
+ ...worstOf(impacts)
153
+ });
154
+ }
155
+ return [...byAsset].map(([asset, { symbol, markets }]) => {
156
+ const sorted = markets.sort((a, b) => a.score - b.score);
157
+ const worst = sorted[0] ?? null;
158
+ return {
159
+ chainId,
160
+ asset,
161
+ symbol,
162
+ score: worst?.score ?? null,
163
+ unverified: sorted.some((market) => market.unverified),
164
+ worst,
165
+ markets: sorted
166
+ };
167
+ });
168
+ }
169
+ //#endregion
170
+ export { runAssetScores };
@@ -0,0 +1 @@
1
+ export {};