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

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 (38) 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/transactions/InstanceOwnerTransactions.js +71 -17
  5. package/dist/cjs/permissionless/api/transactions/fixedRateWindowFeeds.js +134 -0
  6. package/dist/cjs/permissionless/api/transactions/lp-price-feeds.js +10 -35
  7. package/dist/cjs/permissionless/api/transactions/nextLowerBound.js +18 -0
  8. package/dist/esm/dev/withdrawalUtils.js +1 -1
  9. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +5 -5
  10. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +6 -6
  11. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +2 -2
  12. package/dist/esm/onchain/base/TokensMeta.js +4 -4
  13. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  14. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  15. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  16. package/dist/esm/onchain/market/pool/PoolV310Contract.js +3 -3
  17. package/dist/esm/onchain/market/rwa/createDegenNFT.js +1 -1
  18. package/dist/esm/onchain/market/zapper/ZapperContract.js +2 -2
  19. package/dist/esm/onchain/preview/preview/previewPoolPositionOperation.js +1 -1
  20. package/dist/esm/permissionless/api/GearboxPermissionless.js +3 -2
  21. package/dist/esm/permissionless/api/analytics/PermissionlessAnalytics.js +21 -1
  22. package/dist/esm/permissionless/api/analytics/schemas.js +3 -1
  23. package/dist/esm/permissionless/api/transactions/InstanceOwnerTransactions.js +71 -17
  24. package/dist/esm/permissionless/api/transactions/fixedRateWindowFeeds.js +131 -0
  25. package/dist/esm/permissionless/api/transactions/lp-price-feeds.js +10 -34
  26. package/dist/esm/permissionless/api/transactions/nextLowerBound.js +17 -0
  27. package/dist/types/permissionless/api/GearboxPermissionless.d.ts +2 -1
  28. package/dist/types/permissionless/api/analytics/PermissionlessAnalytics.d.ts +12 -1
  29. package/dist/types/permissionless/api/analytics/index.d.ts +2 -2
  30. package/dist/types/permissionless/api/analytics/schemas.d.ts +4 -0
  31. package/dist/types/permissionless/api/analytics/types.d.ts +29 -0
  32. package/dist/types/permissionless/api/index.d.ts +2 -2
  33. package/dist/types/permissionless/api/transactions/InstanceOwnerTransactions.d.ts +16 -9
  34. package/dist/types/permissionless/api/transactions/fixedRateWindowFeeds.d.ts +38 -0
  35. package/dist/types/permissionless/api/transactions/lp-price-feeds.d.ts +4 -6
  36. package/dist/types/permissionless/api/transactions/nextLowerBound.d.ts +15 -0
  37. package/dist/types/permissionless/index.d.ts +2 -2
  38. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { AbstractOffchainNamespace } from "../../../offchain/AbstractOffchainNamespace.js";
2
- import { priceFeedChartSchema } from "./schemas.js";
2
+ import { priceFeedChartSchema, priceFeedRealizedRateSchema } from "./schemas.js";
3
3
  // src/permissionless/api/analytics/PermissionlessAnalytics.ts
4
4
  /**
5
5
  * History of the permissionless stack: what a thing did, rather than what it
@@ -44,5 +44,25 @@ var PermissionlessAnalytics = class extends AbstractOffchainNamespace {
44
44
  schema: priceFeedChartSchema
45
45
  });
46
46
  }
47
+ /**
48
+ * The rate one feed's price grew at between its latest print and the newest
49
+ * print at least `minSpanSeconds` before it.
50
+ *
51
+ * Backend-only for the same reason as {@link priceChart}: finding the prints
52
+ * takes the feed's history.
53
+ *
54
+ * @throws When the PriceFeedStore does not carry the feed, see
55
+ * {@link priceChart}.
56
+ **/
57
+ async realizedRate({ chainId, address, minSpanSeconds, maxPrintGapSeconds }) {
58
+ return this.getData({
59
+ path: `/pfs/${chainId}/price-feed/${address}/realized-rate`,
60
+ query: {
61
+ minSpanSeconds: minSpanSeconds?.toString(),
62
+ maxPrintGapSeconds: maxPrintGapSeconds?.toString()
63
+ },
64
+ schema: priceFeedRealizedRateSchema
65
+ });
66
+ }
47
67
  };
48
68
  export { PermissionlessAnalytics };
@@ -21,4 +21,6 @@ const priceFeedChartSchema = z.looseObject({
21
21
  intervalSeconds: z.number(),
22
22
  points: z.array(priceFeedChartPointSchema)
23
23
  });
24
- export { priceFeedChartPointSchema, priceFeedChartSchema };
24
+ /** {@link PriceFeedRealizedRate} */
25
+ const priceFeedRealizedRateSchema = z.looseObject({ rate: z.number().nullable() });
26
+ export { priceFeedChartPointSchema, priceFeedChartSchema, priceFeedRealizedRateSchema };
@@ -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 { bytes32ToString } from "../../../onchain/utils/bytes32ToString.js";
2
+ import { createRawTx } from "../../../onchain/utils/createRawTx.js";
3
+ import { PERCENTAGE_FACTOR, SECONDS_PER_YEAR } from "../../../onchain/constants/math.js";
4
+ import { simulateMulticall } from "../../../onchain/utils/viem/simulateMulticall.js";
5
+ import { fixedRateWindowPriceFeedAbi } from "../../../onchain/abi/oracles.js";
6
+ import { iPriceFeedAbi } from "../../../abi/iPriceFeed.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 };
@@ -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 };
@@ -1,18 +1,23 @@
1
1
  import { InstanceTxs } from "../../utils/governance/types.js";
2
+ import { PermissionlessAnalytics } from "../analytics/PermissionlessAnalytics.js";
2
3
  import { ChainsNamespace } from "../chains/ChainsNamespace.js";
3
4
  import { PermissionlessOracles } from "../oracles/PermissionlessOracles.js";
4
5
  import { AddFeedsArgs, ChangeNamesArgs, ChangeStalenessPeriodsArgs, ForbidFeedsArgs, InstanceTxsArgs } from "./types.js";
5
6
  /**
6
7
  * The Safe batches an instance owner executes to apply what a curator
7
8
  * prepared: adding their private feeds to the PriceFeedStore, renaming feeds,
8
- * changing staleness periods, forbidding feeds and refreshing LP bounds.
9
+ * changing staleness periods, forbidding feeds and refreshing LP bounds and
10
+ * fixed-rate windows.
9
11
  *
10
12
  * Every batch is wrapped with `wrapConfigureLocal`, so the InstanceManager is
11
13
  * the only caller the PriceFeedStore ever sees.
12
14
  *
13
- * Backend-free: a batch is built off the chain it will be executed on, and
14
- * the store it reads is the one {@link PermissionlessOracles} already
15
- * fetched. Nothing is sent either — a curator never executes these
15
+ * Backend-free but for one read: a batch is built off the chain it will be
16
+ * executed on, and the store it reads is the one {@link PermissionlessOracles}
17
+ * already fetched. The exception is the realized rate of a fixed-rate window,
18
+ * which takes the feed's price history and so comes from
19
+ * {@link PermissionlessAnalytics}; without it the window keeps its rate. Nothing
20
+ * is sent either — a curator never executes these
16
21
  * themselves. They prepare a batch and hand it to the instance owner, who
17
22
  * reviews and executes it from their Safe.
18
23
  *
@@ -27,7 +32,7 @@ import { AddFeedsArgs, ChangeNamesArgs, ChangeStalenessPeriodsArgs, ForbidFeedsA
27
32
  **/
28
33
  export declare class InstanceOwnerTransactions {
29
34
  #private;
30
- constructor(chains: ChainsNamespace, oracles: PermissionlessOracles);
35
+ constructor(chains: ChainsNamespace, oracles: PermissionlessOracles, analytics: PermissionlessAnalytics);
31
36
  /**
32
37
  * The batch that adds the named feeds to the store and allows the named
33
38
  * edges on it.
@@ -57,9 +62,11 @@ export declare class InstanceOwnerTransactions {
57
62
  forbidFeeds({ chainId, owner, tokens }: ForbidFeedsArgs): Promise<InstanceTxs>;
58
63
  /**
59
64
  * The batch that pulls every drifted LP feed's lower bound back under its
60
- * exchange rate. Unlike the others this takes no input: the whole store is
61
- * scanned and only the feeds that drifted produce a transaction, so this
62
- * one is slow.
65
+ * exchange rate, and every drifted fixed-rate window back around its
66
+ * underlying price, resetting the window's growth rate when the realized
67
+ * one moved away from it. Unlike the others this takes no input: the whole
68
+ * store is scanned and only the feeds that drifted produce a transaction,
69
+ * so this one is slow.
63
70
  **/
64
- updateBounds({ chainId, owner }: InstanceTxsArgs): Promise<InstanceTxs>;
71
+ updateBoundsAndRates({ chainId, owner }: InstanceTxsArgs): Promise<InstanceTxs>;
65
72
  }
@@ -0,0 +1,38 @@
1
+ import { PriceFeedTreeNode } from "../../../onchain/base/types.js";
2
+ import { RawTx } from "../../../onchain/types/transactions.js";
3
+ import "../../../onchain/index.js";
4
+ import { Address, PublicClient } from "viem";
5
+ /** A fixed-rate window feed found in a feed tree, with its on-chain name. */
6
+ export interface FixedRateWindowFeed {
7
+ address: Address;
8
+ description: string;
9
+ }
10
+ /**
11
+ * The rate `feed`'s price realized over at least `lookbackSeconds`, as a
12
+ * simple annual decimal fraction, or `null` when its history does not
13
+ * qualify for one.
14
+ **/
15
+ export type RealizedRateSource = (feed: Address, lookbackSeconds: number) => Promise<number | null>;
16
+ /** Chain state every fixed-rate window feed of one batch is read against. */
17
+ export interface RateWindowContext {
18
+ blockNumber: bigint;
19
+ /** Timestamp of {@link blockNumber}. */
20
+ now: bigint;
21
+ realizedRate: RealizedRateSource;
22
+ }
23
+ /** Of the feed tree nodes, the ones that are fixed-rate window feeds. */
24
+ export declare function getFixedRateWindowFeeds(trees: PriceFeedTreeNode[]): FixedRateWindowFeed[];
25
+ /** Pins the batch to the latest block. */
26
+ export declare function rateWindowContext(client: PublicClient, realizedRate: RealizedRateSource): Promise<RateWindowContext>;
27
+ /**
28
+ * Moves a fixed-rate window feed's lower bound back under its underlying
29
+ * price, by the same rule LP feeds follow. When the bound moves, the growth
30
+ * rate is reset too if the rate the price realized differs from it by more
31
+ * than {@link RATE_DEVIATION_PERCENT}. Returns nothing when the bound still
32
+ * fits.
33
+ *
34
+ * The realized rate is measured on the window feed's own history rather than
35
+ * the underlying's: only the store's feeds are indexed, which the underlying
36
+ * usually is not, and inside the window the two prices are the same.
37
+ **/
38
+ export declare function updateRateAndBounds(client: PublicClient, address: Address, context: RateWindowContext): Promise<RawTx[]>;
@@ -1,3 +1,4 @@
1
+ import { PriceFeedTreeNode } from "../../../onchain/base/types.js";
1
2
  import { RawTx } from "../../../onchain/types/transactions.js";
2
3
  import "../../../onchain/index.js";
3
4
  import { Address, PublicClient } from "viem";
@@ -13,10 +14,7 @@ export interface LPFeed {
13
14
  description: string;
14
15
  }
15
16
  /**
16
- * Of the whole feed tree behind `feeds`, the ones that are LP feeds: the
17
- * probe keeps whatever answers `getLPExchangeRate`.
18
- *
19
- * The trees reach past `feeds` themselves, so an LP feed read inside one of
20
- * them is among the results whether or not it is one of `feeds`.
17
+ * Of the feed tree nodes, the ones that are LP feeds: the probe keeps
18
+ * whatever answers `getLPExchangeRate`.
21
19
  **/
22
- export declare function getFeedsToUpdate(client: PublicClient, pfCompressor: Address, feeds: Address[]): Promise<LPFeed[]>;
20
+ export declare function getFeedsToUpdate(client: PublicClient, trees: PriceFeedTreeNode[]): Promise<LPFeed[]>;