@gearbox-protocol/sdk 18.6.0-next.2 → 18.6.0-next.4

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 (34) hide show
  1. package/dist/cjs/permissionless/api/GearboxPermissionless.js +3 -2
  2. package/dist/cjs/permissionless/api/analytics/PermissionlessAnalytics.js +20 -0
  3. package/dist/cjs/permissionless/api/analytics/schemas.js +3 -0
  4. package/dist/cjs/permissionless/api/oracles/PermissionlessOracles.js +26 -6
  5. package/dist/cjs/permissionless/api/oracles/onchain-feed.js +25 -0
  6. package/dist/cjs/permissionless/api/transactions/InstanceOwnerTransactions.js +71 -17
  7. package/dist/cjs/permissionless/api/transactions/fixedRateWindowFeeds.js +134 -0
  8. package/dist/cjs/permissionless/api/transactions/lp-price-feeds.js +10 -35
  9. package/dist/cjs/permissionless/api/transactions/nextLowerBound.js +18 -0
  10. package/dist/esm/permissionless/api/GearboxPermissionless.js +3 -2
  11. package/dist/esm/permissionless/api/analytics/PermissionlessAnalytics.js +21 -1
  12. package/dist/esm/permissionless/api/analytics/schemas.js +3 -1
  13. package/dist/esm/permissionless/api/oracles/PermissionlessOracles.js +27 -7
  14. package/dist/esm/permissionless/api/oracles/onchain-feed.js +25 -1
  15. package/dist/esm/permissionless/api/transactions/InstanceOwnerTransactions.js +71 -17
  16. package/dist/esm/permissionless/api/transactions/fixedRateWindowFeeds.js +131 -0
  17. package/dist/esm/permissionless/api/transactions/lp-price-feeds.js +10 -34
  18. package/dist/esm/permissionless/api/transactions/nextLowerBound.js +17 -0
  19. package/dist/types/onchain/accounts/liquidations/types.d.ts +3 -3
  20. package/dist/types/onchain/accounts/withdrawal-compressor/AbstractWithdrawalCompressorContract.d.ts +2 -2
  21. package/dist/types/permissionless/api/GearboxPermissionless.d.ts +2 -1
  22. package/dist/types/permissionless/api/analytics/PermissionlessAnalytics.d.ts +12 -1
  23. package/dist/types/permissionless/api/analytics/index.d.ts +2 -2
  24. package/dist/types/permissionless/api/analytics/schemas.d.ts +4 -0
  25. package/dist/types/permissionless/api/analytics/types.d.ts +29 -0
  26. package/dist/types/permissionless/api/index.d.ts +2 -2
  27. package/dist/types/permissionless/api/oracles/PermissionlessOracles.d.ts +5 -0
  28. package/dist/types/permissionless/api/oracles/onchain-feed.d.ts +14 -1
  29. package/dist/types/permissionless/api/transactions/InstanceOwnerTransactions.d.ts +16 -9
  30. package/dist/types/permissionless/api/transactions/fixedRateWindowFeeds.d.ts +38 -0
  31. package/dist/types/permissionless/api/transactions/lp-price-feeds.d.ts +4 -6
  32. package/dist/types/permissionless/api/transactions/nextLowerBound.d.ts +15 -0
  33. package/dist/types/permissionless/index.d.ts +2 -2
  34. package/package.json +1 -1
@@ -9,7 +9,7 @@ import { AddressProviderContract } from "../../bindings/address-provider.js";
9
9
  import "../../deployment/addresses.js";
10
10
  import { getFeedDecimals, getLatestPrices, getPrices } from "../../utils/price-update/get-prices.js";
11
11
  import { byCentrality, feedKey, pricesByFeed, toCap, totalQuotas } from "./enrich.js";
12
- import { onchainPriceFeed } from "./onchain-feed.js";
12
+ import { onchainPriceFeed, onchainPriceFeedData } from "./onchain-feed.js";
13
13
  import { assetDetailsSchema, assetSummariesSchema, marketSlotsSchema, priceFeedDetailsSchema, priceFeedStoresSchema } from "./schemas.js";
14
14
  import { runAssetScores, runFeedPairScore } from "./score/run.js";
15
15
  import { readFeedTrees, runStressTest } from "./stress/run.js";
@@ -185,18 +185,25 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
185
185
  /**
186
186
  * One feed as the PriceFeedCompressor reads it, or nothing when the chain
187
187
  * cannot be read or the compressor does not know the feed.
188
+ */
189
+ async #onchainNode(chainId, feed) {
190
+ return (await this.#onchainNodes(chainId, feed))?.get(feed);
191
+ }
192
+ /**
193
+ * Every node of the tree under one feed as the PriceFeedCompressor walks
194
+ * it, or nothing when the chain cannot be read.
188
195
  *
189
196
  * Failures are warnings and not errors: this only ever stands in for a
190
197
  * store that did not have the feed, and the caller reports that miss
191
198
  * rather than whatever kept the chain from answering in its place.
192
199
  */
193
- async #onchainNode(chainId, feed) {
200
+ async #onchainNodes(chainId, feed) {
194
201
  try {
195
202
  const client = this.#chains.client(chainId);
196
203
  const compressor = await new AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(AP_PRICE_FEED_COMPRESSOR);
197
204
  if (compressor === zeroAddress) return;
198
205
  const { nodes } = await readFeedTrees(client, compressor, [feed]);
199
- return nodes.get(feed);
206
+ return nodes;
200
207
  } catch (e) {
201
208
  this.logger?.warn(`could not read price feed ${feed} off chain ${chainId}: ${describe(e)}`);
202
209
  return;
@@ -508,18 +515,31 @@ var PermissionlessOracles = class extends AbstractOffchainNamespace {
508
515
  * composite feed's children are rarely in the store themselves, and a tree
509
516
  * that stopped at the first of them would not be one.
510
517
  *
518
+ * A feed the backend has not indexed at all is walked through the
519
+ * PriceFeedCompressor instead, the same way {@link feed} reads it.
520
+ *
511
521
  * ```ts
512
522
  * const tree = await permissionless.oracles.dependencies({
513
523
  * chainId: 1,
514
524
  * address: feed,
515
525
  * });
516
526
  * ```
527
+ *
528
+ * @throws When neither the backend nor the chain knows the feed.
517
529
  **/
518
530
  async dependencies({ chainId, address }) {
519
- return this.getData({
520
- path: `/pfs/${chainId}/price-feed/${address}/graph`,
521
- schema: priceFeedDataSchema
522
- });
531
+ try {
532
+ return await this.getData({
533
+ path: `/pfs/${chainId}/price-feed/${address}/graph`,
534
+ schema: priceFeedDataSchema
535
+ });
536
+ } catch (e) {
537
+ const feed = address.toLowerCase();
538
+ const nodes = isNotFound(e) ? await this.#onchainNodes(chainId, feed) : void 0;
539
+ const tree = nodes && onchainPriceFeedData(nodes, feed);
540
+ if (!tree) throw e;
541
+ return tree;
542
+ }
523
543
  }
524
544
  /**
525
545
  * What the named feeds price, read off the chain.
@@ -20,4 +20,28 @@ function onchainPriceFeed(node) {
20
20
  name: node.description.trim()
21
21
  };
22
22
  }
23
- export { onchainPriceFeed };
23
+ /**
24
+ * The dependency tree under `feed`, from the nodes the compressor walked, or
25
+ * nothing when it did not reach the feed.
26
+ *
27
+ * Typed the way {@link onchainPriceFeed} types a node, and named after the
28
+ * feed's address when its description is empty, as the backend names a feed
29
+ * it never persisted a name for. A child the walk did not reach is left out,
30
+ * and one already on the path is not re-entered, so a cycle cannot recurse
31
+ * forever.
32
+ */
33
+ function onchainPriceFeedData(nodes, feed, path = /* @__PURE__ */ new Set()) {
34
+ const node = nodes.get(feed);
35
+ if (!node || path.has(feed)) return;
36
+ const below = new Set(path).add(feed);
37
+ return {
38
+ name: node.description.trim() || node.address,
39
+ type: onchainPriceFeed(node).contractType,
40
+ feedAddress: node.address,
41
+ dependencies: node.underlyingFeeds.flatMap((child) => {
42
+ const data = onchainPriceFeedData(nodes, child, below);
43
+ return data ? [data] : [];
44
+ })
45
+ };
46
+ }
47
+ export { onchainPriceFeed, onchainPriceFeedData };
@@ -3,6 +3,7 @@ import { getNetworkType } from "../../../onchain/chain/chains.js";
3
3
  import { AP_PRICE_FEED_COMPRESSOR } from "../../../onchain/constants/address-provider.js";
4
4
  import { VERSION_RANGE_310 } from "../../../onchain/constants/versions.js";
5
5
  import { ChainContractsRegister } from "../../../onchain/base/ChainContractsRegister.js";
6
+ import { priceFeedCompressorAbi } from "../../../abi/compressors/priceFeedCompressor.js";
6
7
  import { OnchainSDK } from "../../../onchain/OnchainSDK.js";
7
8
  import "../../../onchain/index.js";
8
9
  import { InstanceManagerContract } from "../../bindings/instance-manager.js";
@@ -11,20 +12,26 @@ import "../../deployment/addresses.js";
11
12
  import { convertRawTxToSafeMultisigTx, getSafeBatch } from "../../utils/governance/batch.js";
12
13
  import { getUpdatablePriceFeeds } from "../../utils/price-update/get-updatable-feeds.js";
13
14
  import { PriceFeedNotInStoreError } from "../errors.js";
15
+ import { getFixedRateWindowFeeds, rateWindowContext, updateRateAndBounds } from "./fixedRateWindowFeeds.js";
14
16
  import { getFeedsToUpdate, updateBounds } from "./lp-price-feeds.js";
17
+ import { decodeFunctionResult, encodeFunctionData } from "viem";
15
18
  // src/permissionless/api/transactions/InstanceOwnerTransactions.ts
16
19
  const lower = (value) => value.toLowerCase();
17
20
  /**
18
21
  * The Safe batches an instance owner executes to apply what a curator
19
22
  * prepared: adding their private feeds to the PriceFeedStore, renaming feeds,
20
- * changing staleness periods, forbidding feeds and refreshing LP bounds.
23
+ * changing staleness periods, forbidding feeds and refreshing LP bounds and
24
+ * fixed-rate windows.
21
25
  *
22
26
  * Every batch is wrapped with `wrapConfigureLocal`, so the InstanceManager is
23
27
  * the only caller the PriceFeedStore ever sees.
24
28
  *
25
- * Backend-free: a batch is built off the chain it will be executed on, and
26
- * the store it reads is the one {@link PermissionlessOracles} already
27
- * fetched. Nothing is sent either — a curator never executes these
29
+ * Backend-free but for one read: a batch is built off the chain it will be
30
+ * executed on, and the store it reads is the one {@link PermissionlessOracles}
31
+ * already fetched. The exception is the realized rate of a fixed-rate window,
32
+ * which takes the feed's price history and so comes from
33
+ * {@link PermissionlessAnalytics}; without it the window keeps its rate. Nothing
34
+ * is sent either — a curator never executes these
28
35
  * themselves. They prepare a batch and hand it to the instance owner, who
29
36
  * reviews and executes it from their Safe.
30
37
  *
@@ -40,9 +47,11 @@ const lower = (value) => value.toLowerCase();
40
47
  var InstanceOwnerTransactions = class {
41
48
  #chains;
42
49
  #oracles;
43
- constructor(chains, oracles) {
50
+ #analytics;
51
+ constructor(chains, oracles, analytics) {
44
52
  this.#chains = chains;
45
53
  this.#oracles = oracles;
54
+ this.#analytics = analytics;
46
55
  }
47
56
  /**
48
57
  * The batch that adds the named feeds to the store and allows the named
@@ -128,27 +137,51 @@ var InstanceOwnerTransactions = class {
128
137
  }
129
138
  /**
130
139
  * The batch that pulls every drifted LP feed's lower bound back under its
131
- * exchange rate. Unlike the others this takes no input: the whole store is
132
- * scanned and only the feeds that drifted produce a transaction, so this
133
- * one is slow.
140
+ * exchange rate, and every drifted fixed-rate window back around its
141
+ * underlying price, resetting the window's growth rate when the realized
142
+ * one moved away from it. Unlike the others this takes no input: the whole
143
+ * store is scanned and only the feeds that drifted produce a transaction,
144
+ * so this one is slow.
134
145
  **/
135
- async updateBounds({ chainId, owner }) {
146
+ async updateBoundsAndRates({ chainId, owner }) {
136
147
  const batch = await this.#batchContext(chainId);
137
- const pfCompressor = await this.#priceFeedCompressor(batch.client);
138
148
  const known = await batch.store.getKnownPriceFeeds();
139
149
  const isKnown = new Set(known.map(lower));
140
- const feeds = await getFeedsToUpdate(batch.client, pfCompressor, known);
150
+ const trees = await this.#loadPriceFeedTrees(batch.client, known);
151
+ const lpFeeds = await getFeedsToUpdate(batch.client, trees);
152
+ const windowFeeds = getFixedRateWindowFeeds(trees);
153
+ const windowContext = await rateWindowContext(batch.client, async (feed, lookbackSeconds) => {
154
+ const { rate } = await this.#analytics.realizedRate({
155
+ chainId,
156
+ address: feed,
157
+ minSpanSeconds: lookbackSeconds
158
+ });
159
+ return rate;
160
+ });
161
+ const updates = [];
162
+ for (const feed of lpFeeds) updates.push({
163
+ feed,
164
+ txs: await updateBounds(batch.client, feed.address)
165
+ });
166
+ const windows = [];
167
+ for (const feed of windowFeeds) {
168
+ const txs = await updateRateAndBounds(batch.client, feed.address, windowContext);
169
+ if (txs.length > 0) windows.push(feed.address);
170
+ updates.push({
171
+ feed,
172
+ txs
173
+ });
174
+ }
141
175
  const addTxs = [];
142
176
  const added = [];
143
177
  const configureTxs = [];
144
- for (const feed of feeds) {
145
- const boundTxs = await updateBounds(batch.client, feed.address);
146
- if (boundTxs.length === 0) continue;
178
+ for (const { feed, txs } of updates) {
179
+ if (txs.length === 0) continue;
147
180
  if (!isKnown.has(feed.address)) {
148
181
  addTxs.push(batch.store.addPriceFeedTx(feed.address, 0, feed.description));
149
182
  added.push(feed.address);
150
183
  }
151
- configureTxs.push(...boundTxs);
184
+ configureTxs.push(...txs);
152
185
  }
153
186
  const txs = [...addTxs, batch.store.configurePriceFeeds(configureTxs.map((tx) => ({
154
187
  target: tx.to,
@@ -157,9 +190,9 @@ var InstanceOwnerTransactions = class {
157
190
  return this.#envelope({
158
191
  batch,
159
192
  author: owner,
160
- name: "update-bounds",
193
+ name: "update-bounds-and-rates",
161
194
  txs,
162
- touchedFeeds: added
195
+ touchedFeeds: [.../* @__PURE__ */ new Set([...added, ...windows])]
163
196
  });
164
197
  }
165
198
  /**
@@ -215,6 +248,27 @@ var InstanceOwnerTransactions = class {
215
248
  async #priceFeedCompressor(client) {
216
249
  return this.#compressorFrom(await this.#sdk(client));
217
250
  }
251
+ /**
252
+ * Every node of the feed trees behind `feeds`. The trees reach past `feeds`
253
+ * themselves, so a feed read inside one of them is among the nodes whether
254
+ * or not it is one of `feeds`.
255
+ **/
256
+ async #loadPriceFeedTrees(client, feeds) {
257
+ const { data } = await client.call({
258
+ to: await this.#priceFeedCompressor(client),
259
+ data: encodeFunctionData({
260
+ abi: priceFeedCompressorAbi,
261
+ functionName: "loadPriceFeedTree",
262
+ args: [feeds]
263
+ }),
264
+ gas: 200000000n
265
+ });
266
+ return decodeFunctionResult({
267
+ abi: priceFeedCompressorAbi,
268
+ functionName: "loadPriceFeedTree",
269
+ data: data ?? "0x"
270
+ });
271
+ }
218
272
  #compressorFrom(sdk) {
219
273
  const [compressor] = sdk.addressProvider.mustGetLatest(AP_PRICE_FEED_COMPRESSOR, VERSION_RANGE_310);
220
274
  return compressor;
@@ -0,0 +1,131 @@
1
+ import { iPriceFeedAbi } from "../../../abi/iPriceFeed.js";
2
+ import { bytes32ToString } from "../../../onchain/utils/bytes32ToString.js";
3
+ import { createRawTx } from "../../../onchain/utils/createRawTx.js";
4
+ import { PERCENTAGE_FACTOR, SECONDS_PER_YEAR } from "../../../onchain/constants/math.js";
5
+ import { simulateMulticall } from "../../../onchain/utils/viem/simulateMulticall.js";
6
+ import { fixedRateWindowPriceFeedAbi } from "../../../onchain/abi/oracles.js";
7
+ import "../../../onchain/abi/index.js";
8
+ import "../../../onchain/index.js";
9
+ import { nextLowerBound } from "./nextLowerBound.js";
10
+ // src/permissionless/api/transactions/fixedRateWindowFeeds.ts
11
+ const FIXED_RATE_WINDOW = "PRICE_FEED::FIXED_RATE_WINDOW";
12
+ /**
13
+ * Minimum span the realized rate is measured over. A feed whose underlying
14
+ * may go longer than this without printing is measured over its staleness
15
+ * period instead, so that the span still holds several prints.
16
+ **/
17
+ const MIN_RATE_LOOKBACK = 2592e3;
18
+ /**
19
+ * How far, in percent of the current rate, the realized rate has to differ
20
+ * before the rate is reset along with the bounds.
21
+ **/
22
+ const RATE_DEVIATION_PERCENT = 10;
23
+ /** Of the feed tree nodes, the ones that are fixed-rate window feeds. */
24
+ function getFixedRateWindowFeeds(trees) {
25
+ const feeds = /* @__PURE__ */ new Map();
26
+ for (const node of trees) if (bytes32ToString(node.baseParams.contractType) === FIXED_RATE_WINDOW) feeds.set(node.baseParams.addr.toLowerCase(), node.description);
27
+ return Array.from(feeds, ([address, description]) => ({
28
+ address,
29
+ description
30
+ }));
31
+ }
32
+ /** Pins the batch to the latest block. */
33
+ async function rateWindowContext(client, realizedRate) {
34
+ const block = await client.getBlock();
35
+ return {
36
+ blockNumber: block.number,
37
+ now: block.timestamp,
38
+ realizedRate
39
+ };
40
+ }
41
+ /**
42
+ * Moves a fixed-rate window feed's lower bound back under its underlying
43
+ * price, by the same rule LP feeds follow. When the bound moves, the growth
44
+ * rate is reset too if the rate the price realized differs from it by more
45
+ * than {@link RATE_DEVIATION_PERCENT}. Returns nothing when the bound still
46
+ * fits.
47
+ *
48
+ * The realized rate is measured on the window feed's own history rather than
49
+ * the underlying's: only the store's feeds are indexed, which the underlying
50
+ * usually is not, and inside the window the two prices are the same.
51
+ **/
52
+ async function updateRateAndBounds(client, address, context) {
53
+ const { results } = await simulateMulticall(client, {
54
+ contracts: [
55
+ {
56
+ address,
57
+ abi: fixedRateWindowPriceFeedAbi,
58
+ functionName: "priceFeed"
59
+ },
60
+ {
61
+ address,
62
+ abi: fixedRateWindowPriceFeedAbi,
63
+ functionName: "stalenessPeriod"
64
+ },
65
+ {
66
+ address,
67
+ abi: fixedRateWindowPriceFeedAbi,
68
+ functionName: "growthRate"
69
+ },
70
+ {
71
+ address,
72
+ abi: fixedRateWindowPriceFeedAbi,
73
+ functionName: "lowerBoundBase"
74
+ },
75
+ {
76
+ address,
77
+ abi: fixedRateWindowPriceFeedAbi,
78
+ functionName: "timestampLU"
79
+ },
80
+ {
81
+ address,
82
+ abi: fixedRateWindowPriceFeedAbi,
83
+ functionName: "maxGrowthRate"
84
+ }
85
+ ],
86
+ allowFailure: false,
87
+ blockNumber: context.blockNumber
88
+ });
89
+ const [underlying, stalenessPeriod, growthRate, lowerBoundBase, timestampLU, maxGrowthRate] = results;
90
+ const [, value] = await client.readContract({
91
+ abi: iPriceFeedAbi,
92
+ address: underlying,
93
+ functionName: "latestRoundData",
94
+ blockNumber: context.blockNumber
95
+ });
96
+ const next = nextLowerBound(value, currentLowerBound(lowerBoundBase, growthRate, timestampLU, context.now));
97
+ if (!next) return [];
98
+ let rate = growthRate;
99
+ let rateNote;
100
+ try {
101
+ const realized = await context.realizedRate(address, Math.max(MIN_RATE_LOOKBACK, stalenessPeriod));
102
+ if (realized === null) rateNote = "realized rate unavailable, rate kept";
103
+ else {
104
+ const realizedBps = Math.round(realized * Number(PERCENTAGE_FACTOR));
105
+ rate = nextRate(growthRate, realizedBps, maxGrowthRate);
106
+ rateNote = `realized rate: ${realizedBps} bps`;
107
+ }
108
+ } catch (error) {
109
+ rateNote = `realized rate unavailable (${error instanceof Error ? error.message : String(error)}), rate kept`;
110
+ }
111
+ return [createRawTx(address, {
112
+ abi: fixedRateWindowPriceFeedAbi,
113
+ functionName: "setRateAndBounds",
114
+ args: [rate, next.lowerBound]
115
+ }, `[${address}].setRateAndBounds(${rate}, ${next.lowerBound}); // deviationFromValue: ${(100 * next.deviationFromValue).toFixed(2)}%, ${rateNote}`)];
116
+ }
117
+ /** The lower bound the feed enforces at `now`, grown the way the contract grows it. */
118
+ function currentLowerBound(lowerBoundBase, growthRate, timestampLU, now) {
119
+ const growth = BigInt(growthRate) * (now - timestampLU) / BigInt(SECONDS_PER_YEAR);
120
+ return lowerBoundBase * (PERCENTAGE_FACTOR + growth) / PERCENTAGE_FACTOR;
121
+ }
122
+ /**
123
+ * The realized rate, clamped into what the feed accepts, when it differs from
124
+ * the current one by more than {@link RATE_DEVIATION_PERCENT}; the current
125
+ * rate otherwise.
126
+ **/
127
+ function nextRate(current, realized, max) {
128
+ const candidate = Math.min(Math.max(realized, 0), max);
129
+ return Math.abs(candidate - current) * 100 > current * RATE_DEVIATION_PERCENT ? candidate : current;
130
+ }
131
+ export { getFixedRateWindowFeeds, rateWindowContext, updateRateAndBounds };
@@ -1,10 +1,9 @@
1
1
  import { createRawTx } from "../../../onchain/utils/createRawTx.js";
2
2
  import { simulateMulticall } from "../../../onchain/utils/viem/simulateMulticall.js";
3
- import { priceFeedCompressorAbi } from "../../../abi/compressors/priceFeedCompressor.js";
4
3
  import "../../../onchain/index.js";
5
- import { decodeFunctionResult, encodeFunctionData, parseAbi } from "viem";
4
+ import { nextLowerBound } from "./nextLowerBound.js";
5
+ import { parseAbi } from "viem";
6
6
  // src/permissionless/api/transactions/lp-price-feeds.ts
7
- const LOWER_BOUND_FACTOR = 999n;
8
7
  const ilpPriceFeedAbi = parseAbi([
9
8
  "function contractType() external view returns (bytes32)",
10
9
  "function setLimiter(uint256 newLimiter) external",
@@ -26,9 +25,6 @@ function getValue(client, address) {
26
25
  functionName: "getLPExchangeRate"
27
26
  });
28
27
  }
29
- function toLowerBound(value) {
30
- return value * LOWER_BOUND_FACTOR / 1000n;
31
- }
32
28
  /**
33
29
  * Moves an LP feed's lower bound back under its current exchange rate, when
34
30
  * the rate has outgrown the bound or drifted far enough from it to be worth a
@@ -37,40 +33,20 @@ function toLowerBound(value) {
37
33
  async function updateBounds(client, address) {
38
34
  const value = await getValue(client, address);
39
35
  const currentLowerBoundValue = await currentLowerBound(client, address);
40
- const lowerBound = toLowerBound(value);
41
- const deviationFromValue = Math.floor(Number(10000n * (value - currentLowerBoundValue) / currentLowerBoundValue)) / 1e4;
42
- const deviationFromBound = Math.floor(Number(10000n * (lowerBound - currentLowerBoundValue) / currentLowerBoundValue)) / 1e4;
43
- const txs = [];
44
- if (deviationFromValue < 0 || Math.abs(deviationFromBound) > .005) txs.push(createRawTx(address, {
36
+ const next = nextLowerBound(value, currentLowerBoundValue);
37
+ if (!next) return [];
38
+ return [createRawTx(address, {
45
39
  abi: ilpPriceFeedAbi,
46
40
  functionName: "setLimiter",
47
- args: [lowerBound]
48
- }, `[${address}].setLimiter(${lowerBound}); // deviationFromValue: ${(100 * deviationFromValue).toFixed(2)}%`));
49
- return txs;
41
+ args: [next.lowerBound]
42
+ }, `[${address}].setLimiter(${next.lowerBound}); // deviationFromValue: ${(100 * next.deviationFromValue).toFixed(2)}%`)];
50
43
  }
51
44
  /**
52
- * Of the whole feed tree behind `feeds`, the ones that are LP feeds: the
53
- * probe keeps whatever answers `getLPExchangeRate`.
54
- *
55
- * The trees reach past `feeds` themselves, so an LP feed read inside one of
56
- * them is among the results whether or not it is one of `feeds`.
45
+ * Of the feed tree nodes, the ones that are LP feeds: the probe keeps
46
+ * whatever answers `getLPExchangeRate`.
57
47
  **/
58
- async function getFeedsToUpdate(client, pfCompressor, feeds) {
48
+ async function getFeedsToUpdate(client, trees) {
59
49
  const updateableFeeds = /* @__PURE__ */ new Map();
60
- const { data } = await client.call({
61
- to: pfCompressor,
62
- data: encodeFunctionData({
63
- abi: priceFeedCompressorAbi,
64
- functionName: "loadPriceFeedTree",
65
- args: [feeds]
66
- }),
67
- gas: 200000000n
68
- });
69
- const trees = decodeFunctionResult({
70
- abi: priceFeedCompressorAbi,
71
- functionName: "loadPriceFeedTree",
72
- data: data ?? "0x"
73
- });
74
50
  for (const tree of trees) updateableFeeds.set(tree.baseParams.addr.toLowerCase(), tree.description);
75
51
  const candidates = Array.from(updateableFeeds.keys());
76
52
  const { results } = await simulateMulticall(client, {
@@ -0,0 +1,17 @@
1
+ // src/permissionless/api/transactions/nextLowerBound.ts
2
+ const LOWER_BOUND_FACTOR = 999n;
3
+ /**
4
+ * Where a feed's lower bound should move to under `value`, when the value has
5
+ * outgrown the bound or drifted far enough from it to be worth a transaction.
6
+ * Returns nothing when the bound still fits.
7
+ **/
8
+ function nextLowerBound(value, currentLowerBound) {
9
+ const lowerBound = value * LOWER_BOUND_FACTOR / 1000n;
10
+ const deviationFromValue = Math.floor(Number(10000n * (value - currentLowerBound) / currentLowerBound)) / 1e4;
11
+ const deviationFromBound = Math.floor(Number(10000n * (lowerBound - currentLowerBound) / currentLowerBound)) / 1e4;
12
+ if (deviationFromValue < 0 || Math.abs(deviationFromBound) > .005) return {
13
+ lowerBound,
14
+ deviationFromValue
15
+ };
16
+ }
17
+ export { nextLowerBound };
@@ -1,10 +1,10 @@
1
- import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
2
1
  import { LiquidatableAccountFilter } from "../../../model/liquidations.js";
3
- import "../../../model/index.js";
2
+ import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
4
3
  import { MultichainChainIdsProps, MultichainNetworkProps, WithBlock, WithMultichain } from "../../types/multichain.js";
5
4
  import { RouterCASlice, RouterCloseResult } from "../../router/types.js";
6
- import "../../router/index.js";
5
+ import "../../../model/index.js";
7
6
  import { MultiCall, RawTx } from "../../types/transactions.js";
7
+ import "../../router/index.js";
8
8
  import "../../types/index.js";
9
9
  import { Address, ContractFunctionReturnType } from "viem";
10
10
  /**
@@ -1,9 +1,9 @@
1
- import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
2
1
  import { MulticallBatch } from "../../utils/viem/executeMulticallBatches.js";
2
+ import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
3
3
  import "../../base/index.js";
4
4
  import { OnchainSDK } from "../../OnchainSDK.js";
5
- import "../../utils/viem/index.js";
6
5
  import { BaseContract, BaseContractArgs } from "../../base/BaseContract.js";
6
+ import "../../utils/viem/index.js";
7
7
  import { ClaimableWithdrawal, CurrentWithdrawals, GetExternalAccountCurrentWithdrawalsProps, GetWithdrawalRequestResultProps, IWithdrawalCompressorContract, PendingWithdrawal, RequestableWithdrawal, WithdrawableAsset, WithdrawalStatus, WithdrawalsState } from "./types.js";
8
8
  import { Abi, Address, ContractFunctionReturnType } from "viem";
9
9
  export declare const iCreditAccountAbi: readonly [{
@@ -57,7 +57,8 @@ export declare class GearboxPermissionless {
57
57
  **/
58
58
  readonly analytics: PermissionlessAnalytics;
59
59
  /**
60
- * Namespace for the Safe batches an instance owner executes. Backend-free,
60
+ * Namespace for the Safe batches an instance owner executes. Backend-free
61
+ * except for the realized rates of fixed-rate windows,
61
62
  * see {@link InstanceOwnerTransactions}.
62
63
  **/
63
64
  readonly transactions: InstanceOwnerTransactions;
@@ -1,6 +1,6 @@
1
1
  import { AbstractOffchainNamespace } from "../../../offchain/AbstractOffchainNamespace.js";
2
2
  import { GearboxPermissionlessOptions } from "../types.js";
3
- import { PriceChartArgs, PriceFeedPriceChart } from "./types.js";
3
+ import { PriceChartArgs, PriceFeedPriceChart, PriceFeedRealizedRate, RealizedRateArgs } from "./types.js";
4
4
  /**
5
5
  * History of the permissionless stack: what a thing did, rather than what it
6
6
  * is.
@@ -33,4 +33,15 @@ export declare class PermissionlessAnalytics extends AbstractOffchainNamespace {
33
33
  * would read as "no price yet" rather than as the mistake it is.
34
34
  **/
35
35
  priceChart({ chainId, address, range }: PriceChartArgs): Promise<PriceFeedPriceChart>;
36
+ /**
37
+ * The rate one feed's price grew at between its latest print and the newest
38
+ * print at least `minSpanSeconds` before it.
39
+ *
40
+ * Backend-only for the same reason as {@link priceChart}: finding the prints
41
+ * takes the feed's history.
42
+ *
43
+ * @throws When the PriceFeedStore does not carry the feed, see
44
+ * {@link priceChart}.
45
+ **/
46
+ realizedRate({ chainId, address, minSpanSeconds, maxPrintGapSeconds }: RealizedRateArgs): Promise<PriceFeedRealizedRate>;
36
47
  }
@@ -1,3 +1,3 @@
1
1
  import { PermissionlessAnalytics } from "./PermissionlessAnalytics.js";
2
- import { PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart } from "./types.js";
3
- export { PermissionlessAnalytics, PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart };
2
+ import { PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart, PriceFeedRealizedRate, RealizedRateArgs } from "./types.js";
3
+ export { PermissionlessAnalytics, PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart, PriceFeedRealizedRate, RealizedRateArgs };
@@ -27,4 +27,8 @@ export declare const priceFeedChartSchema: z.ZodObject<{
27
27
  timestamp: z.ZodNumber;
28
28
  value: z.ZodNumber;
29
29
  }, z.core.$loose>>;
30
+ }, z.core.$loose>;
31
+ /** {@link PriceFeedRealizedRate} */
32
+ export declare const priceFeedRealizedRateSchema: z.ZodObject<{
33
+ rate: z.ZodNullable<z.ZodNumber>;
30
34
  }, z.core.$loose>;
@@ -33,4 +33,33 @@ export interface PriceChartArgs {
33
33
  address: Address;
34
34
  /** Window to cover. The same set every other Gearbox chart offers. */
35
35
  range: ChartRange;
36
+ }
37
+ /**
38
+ * The rate a feed's price grew at between two of its prints, by the same
39
+ * definition the backend's NAV-step collateral APY uses. A print is a stored
40
+ * price that differs from the stored price before it.
41
+ **/
42
+ export interface PriceFeedRealizedRate {
43
+ /**
44
+ * Simple annualized growth to the latest print from the newest print at
45
+ * least {@link RealizedRateArgs.minSpanSeconds} before it, as a decimal
46
+ * fraction (`0.05` is 5% a year).
47
+ *
48
+ * `null` when the prints do not qualify: either is missing, the latest is
49
+ * older than {@link RealizedRateArgs.maxPrintGapSeconds}, or the earlier
50
+ * one sits more than that beyond the minimum span.
51
+ **/
52
+ rate: number | null;
53
+ }
54
+ /** Args of {@link PermissionlessAnalytics.realizedRate}. */
55
+ export interface RealizedRateArgs {
56
+ chainId: number;
57
+ address: Address;
58
+ /** Minimum time between the two prints. The backend defaults to 30 days. */
59
+ minSpanSeconds?: number;
60
+ /**
61
+ * Oldest the latest print may be, and the furthest the anchor may sit
62
+ * beyond {@link minSpanSeconds}. The backend defaults to the span.
63
+ **/
64
+ maxPrintGapSeconds?: number;
36
65
  }
@@ -3,7 +3,7 @@
3
3
  * backend at all. See {@link GearboxPermissionless}.
4
4
  **/
5
5
  import "./analytics/index.js";
6
- import { PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart } from "./analytics/types.js";
6
+ import { PriceChartArgs, PriceFeedChartPoint, PriceFeedPriceChart, PriceFeedRealizedRate, RealizedRateArgs } from "./analytics/types.js";
7
7
  import { PermissionlessAnalytics } from "./analytics/PermissionlessAnalytics.js";
8
8
  import "./chains/index.js";
9
9
  import { AttachChainsArgs, ChainScope, ChainSummaryArgs, PermissionlessChain, PermissionlessChainSummary } from "./chains/types.js";
@@ -35,4 +35,4 @@ import { DEFAULT_SCENARIOS, RATE_FEED_TYPE, readFeedTrees, readForest, readRateT
35
35
  import { scoreGroup, slotHarm, verdictOf } from "./oracles/stress/score.js";
36
36
  import "./transactions/index.js";
37
37
  import { GearboxPermissionlessOptions } from "./types.js";
38
- export { AddFeedsArgs, AssetArgs, AssetCap, AssetScore, AssetScoresArgs, AssetsArgs, AttachChainsArgs, BreakingPoint, ChainScope, ChainSummaryArgs, ChainsNamespace, ChangeNamesArgs, ChangeStalenessPeriodsArgs, ConfiguratorArgs, DEFAULT_DEPLOY_SALT, DEFAULT_SCENARIOS, DeployArgs, DeployContractArgs, DeployPriceFeedArgs, FeedCap, FeedOutcome, FeedPairScore, FeedPairScoreArgs, ForbidFeedsArgs, GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, GearboxPermissionless, GearboxPermissionlessOptions, GroupImpact, GroupReport, GroupScenarioOutcome, InstanceOwnerTransactions, InstanceTxsArgs, ListConfiguratorsArgs, MarketCap, MarketScore, OpenCuratorSessionArgs, PermissionlessAnalytics, PermissionlessAsset, PermissionlessAssetDetails, PermissionlessAssetMarket, PermissionlessAssetMarketFeed, PermissionlessAssetQuota, PermissionlessAssetSummary, PermissionlessChain, PermissionlessChainSummary, PermissionlessChainUnreachableError, PermissionlessConfigurator, PermissionlessConfiguratorMarket, PermissionlessConfiguratorRoles, PermissionlessConfiguratorTimelock, PermissionlessConfigurators, PermissionlessCurator, PermissionlessDeploy, PermissionlessIndexedAssetDetails, PermissionlessIndexedAssetSummary, PermissionlessIndexedPriceFeedDetails, PermissionlessIndexedPriceFeedMarket, PermissionlessLifecycle, PermissionlessMarket, PermissionlessMarketSlot, PermissionlessNotAttachedError, PermissionlessOracles, PermissionlessPriceFeedAsset, PermissionlessPriceFeedDetails, PermissionlessPriceFeedMarket, PermissionlessPriceFeedStore, PermissionlessQuotaTotals, PermissionlessTimelockEvent, PermissionlessTimelockEventStatus, PreparedDeployment, PreparedPriceFeedDeployment, PriceChartArgs, PriceFeedArgs, PriceFeedChartPoint, PriceFeedDecimals, PriceFeedNotInStoreError, PriceFeedPair, PriceFeedPrice, PriceFeedPriceChart, PriceFeedRef, PriceFeedSaltMissingError, PriceFeedStalenessUnknownError, RATE_FEED_TYPE, SCORE_MULTIPLIER, ScoredFeed, SlotOutcome, StressReport, StressScenario, StressSource, StressSourceKind, StressTestArgs, TIMELOCK_EVENTS_CHUNK_SIZE, TimelockEventsArgs, TreeNode, UNBOUNDED_DOWN, UNBOUNDED_UP, classifySources, deriveEffectiveStalenessPeriod, factorOf, finalPrice, groupOverride, perturb, priceFeedSalt, rateStub, readFeedTrees, readForest, readRateTargets, readUnder, roundDataStub, runAssetScores, runFeedPairScore, runStressTest, scoreGroup, scoreOfFactor, slotHarm, sourcesByFeed, verdictOf, worstOf };
38
+ export { AddFeedsArgs, AssetArgs, AssetCap, AssetScore, AssetScoresArgs, AssetsArgs, AttachChainsArgs, BreakingPoint, ChainScope, ChainSummaryArgs, ChainsNamespace, ChangeNamesArgs, ChangeStalenessPeriodsArgs, ConfiguratorArgs, DEFAULT_DEPLOY_SALT, DEFAULT_SCENARIOS, DeployArgs, DeployContractArgs, DeployPriceFeedArgs, FeedCap, FeedOutcome, FeedPairScore, FeedPairScoreArgs, ForbidFeedsArgs, GET_PRICES_CHUNK_SIZE, GET_PRICES_GAS_LIMIT_BY_CHAIN_ID, GearboxPermissionless, GearboxPermissionlessOptions, GroupImpact, GroupReport, GroupScenarioOutcome, InstanceOwnerTransactions, InstanceTxsArgs, ListConfiguratorsArgs, MarketCap, MarketScore, OpenCuratorSessionArgs, PermissionlessAnalytics, PermissionlessAsset, PermissionlessAssetDetails, PermissionlessAssetMarket, PermissionlessAssetMarketFeed, PermissionlessAssetQuota, PermissionlessAssetSummary, PermissionlessChain, PermissionlessChainSummary, PermissionlessChainUnreachableError, PermissionlessConfigurator, PermissionlessConfiguratorMarket, PermissionlessConfiguratorRoles, PermissionlessConfiguratorTimelock, PermissionlessConfigurators, PermissionlessCurator, PermissionlessDeploy, PermissionlessIndexedAssetDetails, PermissionlessIndexedAssetSummary, PermissionlessIndexedPriceFeedDetails, PermissionlessIndexedPriceFeedMarket, PermissionlessLifecycle, PermissionlessMarket, PermissionlessMarketSlot, PermissionlessNotAttachedError, PermissionlessOracles, PermissionlessPriceFeedAsset, PermissionlessPriceFeedDetails, PermissionlessPriceFeedMarket, PermissionlessPriceFeedStore, PermissionlessQuotaTotals, PermissionlessTimelockEvent, PermissionlessTimelockEventStatus, PreparedDeployment, PreparedPriceFeedDeployment, PriceChartArgs, PriceFeedArgs, PriceFeedChartPoint, PriceFeedDecimals, PriceFeedNotInStoreError, PriceFeedPair, PriceFeedPrice, PriceFeedPriceChart, PriceFeedRealizedRate, PriceFeedRef, PriceFeedSaltMissingError, PriceFeedStalenessUnknownError, RATE_FEED_TYPE, RealizedRateArgs, SCORE_MULTIPLIER, ScoredFeed, SlotOutcome, StressReport, StressScenario, StressSource, StressSourceKind, StressTestArgs, TIMELOCK_EVENTS_CHUNK_SIZE, TimelockEventsArgs, TreeNode, UNBOUNDED_DOWN, UNBOUNDED_UP, classifySources, deriveEffectiveStalenessPeriod, factorOf, finalPrice, groupOverride, perturb, priceFeedSalt, rateStub, readFeedTrees, readForest, readRateTargets, readUnder, roundDataStub, runAssetScores, runFeedPairScore, runStressTest, scoreGroup, scoreOfFactor, slotHarm, sourcesByFeed, verdictOf, worstOf };
@@ -252,12 +252,17 @@ export declare class PermissionlessOracles extends AbstractOffchainNamespace {
252
252
  * composite feed's children are rarely in the store themselves, and a tree
253
253
  * that stopped at the first of them would not be one.
254
254
  *
255
+ * A feed the backend has not indexed at all is walked through the
256
+ * PriceFeedCompressor instead, the same way {@link feed} reads it.
257
+ *
255
258
  * ```ts
256
259
  * const tree = await permissionless.oracles.dependencies({
257
260
  * chainId: 1,
258
261
  * address: feed,
259
262
  * });
260
263
  * ```
264
+ *
265
+ * @throws When neither the backend nor the chain knows the feed.
261
266
  **/
262
267
  dependencies({ chainId, address }: PriceFeedArgs): Promise<PriceFeedData>;
263
268
  /**