@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
@@ -57,7 +57,8 @@ var GearboxPermissionless = class {
57
57
  **/
58
58
  analytics;
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
  transactions;
@@ -76,7 +77,7 @@ var GearboxPermissionless = class {
76
77
  this.oracles = new require_permissionless_api_oracles_PermissionlessOracles.PermissionlessOracles(options, this.chains);
77
78
  this.configurators = new require_permissionless_api_configurators_PermissionlessConfigurators.PermissionlessConfigurators(options, this.chains);
78
79
  this.analytics = new require_permissionless_api_analytics_PermissionlessAnalytics.PermissionlessAnalytics(options);
79
- this.transactions = new require_permissionless_api_transactions_InstanceOwnerTransactions.InstanceOwnerTransactions(this.chains, this.oracles);
80
+ this.transactions = new require_permissionless_api_transactions_InstanceOwnerTransactions.InstanceOwnerTransactions(this.chains, this.oracles, this.analytics);
80
81
  this.deploy = new require_permissionless_api_deploy_PermissionlessDeploy.PermissionlessDeploy(this.chains);
81
82
  this.curator = new require_permissionless_api_curator_PermissionlessCurator.PermissionlessCurator(this.chains);
82
83
  }
@@ -45,5 +45,25 @@ var PermissionlessAnalytics = class extends require_offchain_AbstractOffchainNam
45
45
  schema: require_permissionless_api_analytics_schemas.priceFeedChartSchema
46
46
  });
47
47
  }
48
+ /**
49
+ * The rate one feed's price grew at between its latest print and the newest
50
+ * print at least `minSpanSeconds` before it.
51
+ *
52
+ * Backend-only for the same reason as {@link priceChart}: finding the prints
53
+ * takes the feed's history.
54
+ *
55
+ * @throws When the PriceFeedStore does not carry the feed, see
56
+ * {@link priceChart}.
57
+ **/
58
+ async realizedRate({ chainId, address, minSpanSeconds, maxPrintGapSeconds }) {
59
+ return this.getData({
60
+ path: `/pfs/${chainId}/price-feed/${address}/realized-rate`,
61
+ query: {
62
+ minSpanSeconds: minSpanSeconds?.toString(),
63
+ maxPrintGapSeconds: maxPrintGapSeconds?.toString()
64
+ },
65
+ schema: require_permissionless_api_analytics_schemas.priceFeedRealizedRateSchema
66
+ });
67
+ }
48
68
  };
49
69
  exports.PermissionlessAnalytics = PermissionlessAnalytics;
@@ -22,5 +22,8 @@ const priceFeedChartSchema = zod_v4.z.looseObject({
22
22
  intervalSeconds: zod_v4.z.number(),
23
23
  points: zod_v4.z.array(priceFeedChartPointSchema)
24
24
  });
25
+ /** {@link PriceFeedRealizedRate} */
26
+ const priceFeedRealizedRateSchema = zod_v4.z.looseObject({ rate: zod_v4.z.number().nullable() });
25
27
  exports.priceFeedChartPointSchema = priceFeedChartPointSchema;
26
28
  exports.priceFeedChartSchema = priceFeedChartSchema;
29
+ exports.priceFeedRealizedRateSchema = priceFeedRealizedRateSchema;
@@ -186,18 +186,25 @@ var PermissionlessOracles = class extends require_offchain_AbstractOffchainNames
186
186
  /**
187
187
  * One feed as the PriceFeedCompressor reads it, or nothing when the chain
188
188
  * cannot be read or the compressor does not know the feed.
189
+ */
190
+ async #onchainNode(chainId, feed) {
191
+ return (await this.#onchainNodes(chainId, feed))?.get(feed);
192
+ }
193
+ /**
194
+ * Every node of the tree under one feed as the PriceFeedCompressor walks
195
+ * it, or nothing when the chain cannot be read.
189
196
  *
190
197
  * Failures are warnings and not errors: this only ever stands in for a
191
198
  * store that did not have the feed, and the caller reports that miss
192
199
  * rather than whatever kept the chain from answering in its place.
193
200
  */
194
- async #onchainNode(chainId, feed) {
201
+ async #onchainNodes(chainId, feed) {
195
202
  try {
196
203
  const client = this.#chains.client(chainId);
197
204
  const compressor = await new require_permissionless_bindings_address_provider.AddressProviderContract("0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38", client).getLatestVersionAddress(require_onchain_constants_address_provider.AP_PRICE_FEED_COMPRESSOR);
198
205
  if (compressor === viem.zeroAddress) return;
199
206
  const { nodes } = await require_permissionless_api_oracles_stress_run.readFeedTrees(client, compressor, [feed]);
200
- return nodes.get(feed);
207
+ return nodes;
201
208
  } catch (e) {
202
209
  this.logger?.warn(`could not read price feed ${feed} off chain ${chainId}: ${describe(e)}`);
203
210
  return;
@@ -509,18 +516,31 @@ var PermissionlessOracles = class extends require_offchain_AbstractOffchainNames
509
516
  * composite feed's children are rarely in the store themselves, and a tree
510
517
  * that stopped at the first of them would not be one.
511
518
  *
519
+ * A feed the backend has not indexed at all is walked through the
520
+ * PriceFeedCompressor instead, the same way {@link feed} reads it.
521
+ *
512
522
  * ```ts
513
523
  * const tree = await permissionless.oracles.dependencies({
514
524
  * chainId: 1,
515
525
  * address: feed,
516
526
  * });
517
527
  * ```
528
+ *
529
+ * @throws When neither the backend nor the chain knows the feed.
518
530
  **/
519
531
  async dependencies({ chainId, address }) {
520
- return this.getData({
521
- path: `/pfs/${chainId}/price-feed/${address}/graph`,
522
- schema: require_model_opportunities_schema.priceFeedDataSchema
523
- });
532
+ try {
533
+ return await this.getData({
534
+ path: `/pfs/${chainId}/price-feed/${address}/graph`,
535
+ schema: require_model_opportunities_schema.priceFeedDataSchema
536
+ });
537
+ } catch (e) {
538
+ const feed = address.toLowerCase();
539
+ const nodes = isNotFound(e) ? await this.#onchainNodes(chainId, feed) : void 0;
540
+ const tree = nodes && require_permissionless_api_oracles_onchain_feed.onchainPriceFeedData(nodes, feed);
541
+ if (!tree) throw e;
542
+ return tree;
543
+ }
524
544
  }
525
545
  /**
526
546
  * What the named feeds price, read off the chain.
@@ -21,4 +21,29 @@ function onchainPriceFeed(node) {
21
21
  name: node.description.trim()
22
22
  };
23
23
  }
24
+ /**
25
+ * The dependency tree under `feed`, from the nodes the compressor walked, or
26
+ * nothing when it did not reach the feed.
27
+ *
28
+ * Typed the way {@link onchainPriceFeed} types a node, and named after the
29
+ * feed's address when its description is empty, as the backend names a feed
30
+ * it never persisted a name for. A child the walk did not reach is left out,
31
+ * and one already on the path is not re-entered, so a cycle cannot recurse
32
+ * forever.
33
+ */
34
+ function onchainPriceFeedData(nodes, feed, path = /* @__PURE__ */ new Set()) {
35
+ const node = nodes.get(feed);
36
+ if (!node || path.has(feed)) return;
37
+ const below = new Set(path).add(feed);
38
+ return {
39
+ name: node.description.trim() || node.address,
40
+ type: onchainPriceFeed(node).contractType,
41
+ feedAddress: node.address,
42
+ dependencies: node.underlyingFeeds.flatMap((child) => {
43
+ const data = onchainPriceFeedData(nodes, child, below);
44
+ return data ? [data] : [];
45
+ })
46
+ };
47
+ }
24
48
  exports.onchainPriceFeed = onchainPriceFeed;
49
+ exports.onchainPriceFeedData = onchainPriceFeedData;
@@ -4,6 +4,7 @@ const require_onchain_chain_chains = require("../../../onchain/chain/chains.js")
4
4
  const require_onchain_constants_address_provider = require("../../../onchain/constants/address-provider.js");
5
5
  const require_onchain_constants_versions = require("../../../onchain/constants/versions.js");
6
6
  const require_onchain_base_ChainContractsRegister = require("../../../onchain/base/ChainContractsRegister.js");
7
+ const require_abi_compressors_priceFeedCompressor = require("../../../abi/compressors/priceFeedCompressor.js");
7
8
  const require_onchain_OnchainSDK = require("../../../onchain/OnchainSDK.js");
8
9
  require("../../../onchain/index.js");
9
10
  const require_permissionless_bindings_instance_manager = require("../../bindings/instance-manager.js");
@@ -12,20 +13,26 @@ require("../../deployment/addresses.js");
12
13
  const require_permissionless_utils_governance_batch = require("../../utils/governance/batch.js");
13
14
  const require_permissionless_utils_price_update_get_updatable_feeds = require("../../utils/price-update/get-updatable-feeds.js");
14
15
  const require_permissionless_api_errors = require("../errors.js");
16
+ const require_permissionless_api_transactions_fixedRateWindowFeeds = require("./fixedRateWindowFeeds.js");
15
17
  const require_permissionless_api_transactions_lp_price_feeds = require("./lp-price-feeds.js");
18
+ let viem = require("viem");
16
19
  // src/permissionless/api/transactions/InstanceOwnerTransactions.ts
17
20
  const lower = (value) => value.toLowerCase();
18
21
  /**
19
22
  * The Safe batches an instance owner executes to apply what a curator
20
23
  * prepared: adding their private feeds to the PriceFeedStore, renaming feeds,
21
- * changing staleness periods, forbidding feeds and refreshing LP bounds.
24
+ * changing staleness periods, forbidding feeds and refreshing LP bounds and
25
+ * fixed-rate windows.
22
26
  *
23
27
  * Every batch is wrapped with `wrapConfigureLocal`, so the InstanceManager is
24
28
  * the only caller the PriceFeedStore ever sees.
25
29
  *
26
- * Backend-free: a batch is built off the chain it will be executed on, and
27
- * the store it reads is the one {@link PermissionlessOracles} already
28
- * fetched. Nothing is sent either — a curator never executes these
30
+ * Backend-free but for one read: a batch is built off the chain it will be
31
+ * executed on, and the store it reads is the one {@link PermissionlessOracles}
32
+ * already fetched. The exception is the realized rate of a fixed-rate window,
33
+ * which takes the feed's price history and so comes from
34
+ * {@link PermissionlessAnalytics}; without it the window keeps its rate. Nothing
35
+ * is sent either — a curator never executes these
29
36
  * themselves. They prepare a batch and hand it to the instance owner, who
30
37
  * reviews and executes it from their Safe.
31
38
  *
@@ -41,9 +48,11 @@ const lower = (value) => value.toLowerCase();
41
48
  var InstanceOwnerTransactions = class {
42
49
  #chains;
43
50
  #oracles;
44
- constructor(chains, oracles) {
51
+ #analytics;
52
+ constructor(chains, oracles, analytics) {
45
53
  this.#chains = chains;
46
54
  this.#oracles = oracles;
55
+ this.#analytics = analytics;
47
56
  }
48
57
  /**
49
58
  * The batch that adds the named feeds to the store and allows the named
@@ -129,27 +138,51 @@ var InstanceOwnerTransactions = class {
129
138
  }
130
139
  /**
131
140
  * The batch that pulls every drifted LP feed's lower bound back under its
132
- * exchange rate. Unlike the others this takes no input: the whole store is
133
- * scanned and only the feeds that drifted produce a transaction, so this
134
- * one is slow.
141
+ * exchange rate, and every drifted fixed-rate window back around its
142
+ * underlying price, resetting the window's growth rate when the realized
143
+ * one moved away from it. Unlike the others this takes no input: the whole
144
+ * store is scanned and only the feeds that drifted produce a transaction,
145
+ * so this one is slow.
135
146
  **/
136
- async updateBounds({ chainId, owner }) {
147
+ async updateBoundsAndRates({ chainId, owner }) {
137
148
  const batch = await this.#batchContext(chainId);
138
- const pfCompressor = await this.#priceFeedCompressor(batch.client);
139
149
  const known = await batch.store.getKnownPriceFeeds();
140
150
  const isKnown = new Set(known.map(lower));
141
- const feeds = await require_permissionless_api_transactions_lp_price_feeds.getFeedsToUpdate(batch.client, pfCompressor, known);
151
+ const trees = await this.#loadPriceFeedTrees(batch.client, known);
152
+ const lpFeeds = await require_permissionless_api_transactions_lp_price_feeds.getFeedsToUpdate(batch.client, trees);
153
+ const windowFeeds = require_permissionless_api_transactions_fixedRateWindowFeeds.getFixedRateWindowFeeds(trees);
154
+ const windowContext = await require_permissionless_api_transactions_fixedRateWindowFeeds.rateWindowContext(batch.client, async (feed, lookbackSeconds) => {
155
+ const { rate } = await this.#analytics.realizedRate({
156
+ chainId,
157
+ address: feed,
158
+ minSpanSeconds: lookbackSeconds
159
+ });
160
+ return rate;
161
+ });
162
+ const updates = [];
163
+ for (const feed of lpFeeds) updates.push({
164
+ feed,
165
+ txs: await require_permissionless_api_transactions_lp_price_feeds.updateBounds(batch.client, feed.address)
166
+ });
167
+ const windows = [];
168
+ for (const feed of windowFeeds) {
169
+ const txs = await require_permissionless_api_transactions_fixedRateWindowFeeds.updateRateAndBounds(batch.client, feed.address, windowContext);
170
+ if (txs.length > 0) windows.push(feed.address);
171
+ updates.push({
172
+ feed,
173
+ txs
174
+ });
175
+ }
142
176
  const addTxs = [];
143
177
  const added = [];
144
178
  const configureTxs = [];
145
- for (const feed of feeds) {
146
- const boundTxs = await require_permissionless_api_transactions_lp_price_feeds.updateBounds(batch.client, feed.address);
147
- if (boundTxs.length === 0) continue;
179
+ for (const { feed, txs } of updates) {
180
+ if (txs.length === 0) continue;
148
181
  if (!isKnown.has(feed.address)) {
149
182
  addTxs.push(batch.store.addPriceFeedTx(feed.address, 0, feed.description));
150
183
  added.push(feed.address);
151
184
  }
152
- configureTxs.push(...boundTxs);
185
+ configureTxs.push(...txs);
153
186
  }
154
187
  const txs = [...addTxs, batch.store.configurePriceFeeds(configureTxs.map((tx) => ({
155
188
  target: tx.to,
@@ -158,9 +191,9 @@ var InstanceOwnerTransactions = class {
158
191
  return this.#envelope({
159
192
  batch,
160
193
  author: owner,
161
- name: "update-bounds",
194
+ name: "update-bounds-and-rates",
162
195
  txs,
163
- touchedFeeds: added
196
+ touchedFeeds: [.../* @__PURE__ */ new Set([...added, ...windows])]
164
197
  });
165
198
  }
166
199
  /**
@@ -216,6 +249,27 @@ var InstanceOwnerTransactions = class {
216
249
  async #priceFeedCompressor(client) {
217
250
  return this.#compressorFrom(await this.#sdk(client));
218
251
  }
252
+ /**
253
+ * Every node of the feed trees behind `feeds`. The trees reach past `feeds`
254
+ * themselves, so a feed read inside one of them is among the nodes whether
255
+ * or not it is one of `feeds`.
256
+ **/
257
+ async #loadPriceFeedTrees(client, feeds) {
258
+ const { data } = await client.call({
259
+ to: await this.#priceFeedCompressor(client),
260
+ data: (0, viem.encodeFunctionData)({
261
+ abi: require_abi_compressors_priceFeedCompressor.priceFeedCompressorAbi,
262
+ functionName: "loadPriceFeedTree",
263
+ args: [feeds]
264
+ }),
265
+ gas: 200000000n
266
+ });
267
+ return (0, viem.decodeFunctionResult)({
268
+ abi: require_abi_compressors_priceFeedCompressor.priceFeedCompressorAbi,
269
+ functionName: "loadPriceFeedTree",
270
+ data: data ?? "0x"
271
+ });
272
+ }
219
273
  #compressorFrom(sdk) {
220
274
  const [compressor] = sdk.addressProvider.mustGetLatest(require_onchain_constants_address_provider.AP_PRICE_FEED_COMPRESSOR, require_onchain_constants_versions.VERSION_RANGE_310);
221
275
  return compressor;
@@ -0,0 +1,134 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_abi_iPriceFeed = require("../../../abi/iPriceFeed.js");
3
+ const require_onchain_utils_bytes32ToString = require("../../../onchain/utils/bytes32ToString.js");
4
+ const require_onchain_utils_createRawTx = require("../../../onchain/utils/createRawTx.js");
5
+ const require_onchain_constants_math = require("../../../onchain/constants/math.js");
6
+ const require_onchain_utils_viem_simulateMulticall = require("../../../onchain/utils/viem/simulateMulticall.js");
7
+ const require_onchain_abi_oracles = require("../../../onchain/abi/oracles.js");
8
+ require("../../../onchain/abi/index.js");
9
+ require("../../../onchain/index.js");
10
+ const require_permissionless_api_transactions_nextLowerBound = require("./nextLowerBound.js");
11
+ // src/permissionless/api/transactions/fixedRateWindowFeeds.ts
12
+ const FIXED_RATE_WINDOW = "PRICE_FEED::FIXED_RATE_WINDOW";
13
+ /**
14
+ * Minimum span the realized rate is measured over. A feed whose underlying
15
+ * may go longer than this without printing is measured over its staleness
16
+ * period instead, so that the span still holds several prints.
17
+ **/
18
+ const MIN_RATE_LOOKBACK = 2592e3;
19
+ /**
20
+ * How far, in percent of the current rate, the realized rate has to differ
21
+ * before the rate is reset along with the bounds.
22
+ **/
23
+ const RATE_DEVIATION_PERCENT = 10;
24
+ /** Of the feed tree nodes, the ones that are fixed-rate window feeds. */
25
+ function getFixedRateWindowFeeds(trees) {
26
+ const feeds = /* @__PURE__ */ new Map();
27
+ for (const node of trees) if (require_onchain_utils_bytes32ToString.bytes32ToString(node.baseParams.contractType) === FIXED_RATE_WINDOW) feeds.set(node.baseParams.addr.toLowerCase(), node.description);
28
+ return Array.from(feeds, ([address, description]) => ({
29
+ address,
30
+ description
31
+ }));
32
+ }
33
+ /** Pins the batch to the latest block. */
34
+ async function rateWindowContext(client, realizedRate) {
35
+ const block = await client.getBlock();
36
+ return {
37
+ blockNumber: block.number,
38
+ now: block.timestamp,
39
+ realizedRate
40
+ };
41
+ }
42
+ /**
43
+ * Moves a fixed-rate window feed's lower bound back under its underlying
44
+ * price, by the same rule LP feeds follow. When the bound moves, the growth
45
+ * rate is reset too if the rate the price realized differs from it by more
46
+ * than {@link RATE_DEVIATION_PERCENT}. Returns nothing when the bound still
47
+ * fits.
48
+ *
49
+ * The realized rate is measured on the window feed's own history rather than
50
+ * the underlying's: only the store's feeds are indexed, which the underlying
51
+ * usually is not, and inside the window the two prices are the same.
52
+ **/
53
+ async function updateRateAndBounds(client, address, context) {
54
+ const { results } = await require_onchain_utils_viem_simulateMulticall.simulateMulticall(client, {
55
+ contracts: [
56
+ {
57
+ address,
58
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
59
+ functionName: "priceFeed"
60
+ },
61
+ {
62
+ address,
63
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
64
+ functionName: "stalenessPeriod"
65
+ },
66
+ {
67
+ address,
68
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
69
+ functionName: "growthRate"
70
+ },
71
+ {
72
+ address,
73
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
74
+ functionName: "lowerBoundBase"
75
+ },
76
+ {
77
+ address,
78
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
79
+ functionName: "timestampLU"
80
+ },
81
+ {
82
+ address,
83
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
84
+ functionName: "maxGrowthRate"
85
+ }
86
+ ],
87
+ allowFailure: false,
88
+ blockNumber: context.blockNumber
89
+ });
90
+ const [underlying, stalenessPeriod, growthRate, lowerBoundBase, timestampLU, maxGrowthRate] = results;
91
+ const [, value] = await client.readContract({
92
+ abi: require_abi_iPriceFeed.iPriceFeedAbi,
93
+ address: underlying,
94
+ functionName: "latestRoundData",
95
+ blockNumber: context.blockNumber
96
+ });
97
+ const next = require_permissionless_api_transactions_nextLowerBound.nextLowerBound(value, currentLowerBound(lowerBoundBase, growthRate, timestampLU, context.now));
98
+ if (!next) return [];
99
+ let rate = growthRate;
100
+ let rateNote;
101
+ try {
102
+ const realized = await context.realizedRate(address, Math.max(MIN_RATE_LOOKBACK, stalenessPeriod));
103
+ if (realized === null) rateNote = "realized rate unavailable, rate kept";
104
+ else {
105
+ const realizedBps = Math.round(realized * Number(require_onchain_constants_math.PERCENTAGE_FACTOR));
106
+ rate = nextRate(growthRate, realizedBps, maxGrowthRate);
107
+ rateNote = `realized rate: ${realizedBps} bps`;
108
+ }
109
+ } catch (error) {
110
+ rateNote = `realized rate unavailable (${error instanceof Error ? error.message : String(error)}), rate kept`;
111
+ }
112
+ return [require_onchain_utils_createRawTx.createRawTx(address, {
113
+ abi: require_onchain_abi_oracles.fixedRateWindowPriceFeedAbi,
114
+ functionName: "setRateAndBounds",
115
+ args: [rate, next.lowerBound]
116
+ }, `[${address}].setRateAndBounds(${rate}, ${next.lowerBound}); // deviationFromValue: ${(100 * next.deviationFromValue).toFixed(2)}%, ${rateNote}`)];
117
+ }
118
+ /** The lower bound the feed enforces at `now`, grown the way the contract grows it. */
119
+ function currentLowerBound(lowerBoundBase, growthRate, timestampLU, now) {
120
+ const growth = BigInt(growthRate) * (now - timestampLU) / BigInt(require_onchain_constants_math.SECONDS_PER_YEAR);
121
+ return lowerBoundBase * (require_onchain_constants_math.PERCENTAGE_FACTOR + growth) / require_onchain_constants_math.PERCENTAGE_FACTOR;
122
+ }
123
+ /**
124
+ * The realized rate, clamped into what the feed accepts, when it differs from
125
+ * the current one by more than {@link RATE_DEVIATION_PERCENT}; the current
126
+ * rate otherwise.
127
+ **/
128
+ function nextRate(current, realized, max) {
129
+ const candidate = Math.min(Math.max(realized, 0), max);
130
+ return Math.abs(candidate - current) * 100 > current * RATE_DEVIATION_PERCENT ? candidate : current;
131
+ }
132
+ exports.getFixedRateWindowFeeds = getFixedRateWindowFeeds;
133
+ exports.rateWindowContext = rateWindowContext;
134
+ exports.updateRateAndBounds = updateRateAndBounds;
@@ -1,12 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_utils_createRawTx = require("../../../onchain/utils/createRawTx.js");
3
3
  const require_onchain_utils_viem_simulateMulticall = require("../../../onchain/utils/viem/simulateMulticall.js");
4
- const require_abi_compressors_priceFeedCompressor = require("../../../abi/compressors/priceFeedCompressor.js");
5
4
  require("../../../onchain/index.js");
6
- let viem = require("viem");
5
+ const require_permissionless_api_transactions_nextLowerBound = require("./nextLowerBound.js");
7
6
  // src/permissionless/api/transactions/lp-price-feeds.ts
8
- const LOWER_BOUND_FACTOR = 999n;
9
- const ilpPriceFeedAbi = (0, viem.parseAbi)([
7
+ const ilpPriceFeedAbi = (0, require("viem").parseAbi)([
10
8
  "function contractType() external view returns (bytes32)",
11
9
  "function setLimiter(uint256 newLimiter) external",
12
10
  "function getLPExchangeRate() public view returns (uint256 exchangeRate)",
@@ -27,9 +25,6 @@ function getValue(client, address) {
27
25
  functionName: "getLPExchangeRate"
28
26
  });
29
27
  }
30
- function toLowerBound(value) {
31
- return value * LOWER_BOUND_FACTOR / 1000n;
32
- }
33
28
  /**
34
29
  * Moves an LP feed's lower bound back under its current exchange rate, when
35
30
  * the rate has outgrown the bound or drifted far enough from it to be worth a
@@ -38,40 +33,20 @@ function toLowerBound(value) {
38
33
  async function updateBounds(client, address) {
39
34
  const value = await getValue(client, address);
40
35
  const currentLowerBoundValue = await currentLowerBound(client, address);
41
- const lowerBound = toLowerBound(value);
42
- const deviationFromValue = Math.floor(Number(10000n * (value - currentLowerBoundValue) / currentLowerBoundValue)) / 1e4;
43
- const deviationFromBound = Math.floor(Number(10000n * (lowerBound - currentLowerBoundValue) / currentLowerBoundValue)) / 1e4;
44
- const txs = [];
45
- if (deviationFromValue < 0 || Math.abs(deviationFromBound) > .005) txs.push(require_onchain_utils_createRawTx.createRawTx(address, {
36
+ const next = require_permissionless_api_transactions_nextLowerBound.nextLowerBound(value, currentLowerBoundValue);
37
+ if (!next) return [];
38
+ return [require_onchain_utils_createRawTx.createRawTx(address, {
46
39
  abi: ilpPriceFeedAbi,
47
40
  functionName: "setLimiter",
48
- args: [lowerBound]
49
- }, `[${address}].setLimiter(${lowerBound}); // deviationFromValue: ${(100 * deviationFromValue).toFixed(2)}%`));
50
- return txs;
41
+ args: [next.lowerBound]
42
+ }, `[${address}].setLimiter(${next.lowerBound}); // deviationFromValue: ${(100 * next.deviationFromValue).toFixed(2)}%`)];
51
43
  }
52
44
  /**
53
- * Of the whole feed tree behind `feeds`, the ones that are LP feeds: the
54
- * probe keeps whatever answers `getLPExchangeRate`.
55
- *
56
- * The trees reach past `feeds` themselves, so an LP feed read inside one of
57
- * 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`.
58
47
  **/
59
- async function getFeedsToUpdate(client, pfCompressor, feeds) {
48
+ async function getFeedsToUpdate(client, trees) {
60
49
  const updateableFeeds = /* @__PURE__ */ new Map();
61
- const { data } = await client.call({
62
- to: pfCompressor,
63
- data: (0, viem.encodeFunctionData)({
64
- abi: require_abi_compressors_priceFeedCompressor.priceFeedCompressorAbi,
65
- functionName: "loadPriceFeedTree",
66
- args: [feeds]
67
- }),
68
- gas: 200000000n
69
- });
70
- const trees = (0, viem.decodeFunctionResult)({
71
- abi: require_abi_compressors_priceFeedCompressor.priceFeedCompressorAbi,
72
- functionName: "loadPriceFeedTree",
73
- data: data ?? "0x"
74
- });
75
50
  for (const tree of trees) updateableFeeds.set(tree.baseParams.addr.toLowerCase(), tree.description);
76
51
  const candidates = Array.from(updateableFeeds.keys());
77
52
  const { results } = await require_onchain_utils_viem_simulateMulticall.simulateMulticall(client, {
@@ -0,0 +1,18 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/permissionless/api/transactions/nextLowerBound.ts
3
+ const LOWER_BOUND_FACTOR = 999n;
4
+ /**
5
+ * Where a feed's lower bound should move to under `value`, when the value has
6
+ * outgrown the bound or drifted far enough from it to be worth a transaction.
7
+ * Returns nothing when the bound still fits.
8
+ **/
9
+ function nextLowerBound(value, currentLowerBound) {
10
+ const lowerBound = value * LOWER_BOUND_FACTOR / 1000n;
11
+ const deviationFromValue = Math.floor(Number(10000n * (value - currentLowerBound) / currentLowerBound)) / 1e4;
12
+ const deviationFromBound = Math.floor(Number(10000n * (lowerBound - currentLowerBound) / currentLowerBound)) / 1e4;
13
+ if (deviationFromValue < 0 || Math.abs(deviationFromBound) > .005) return {
14
+ lowerBound,
15
+ deviationFromValue
16
+ };
17
+ }
18
+ exports.nextLowerBound = nextLowerBound;
@@ -56,7 +56,8 @@ var GearboxPermissionless = class {
56
56
  **/
57
57
  analytics;
58
58
  /**
59
- * Namespace for the Safe batches an instance owner executes. Backend-free,
59
+ * Namespace for the Safe batches an instance owner executes. Backend-free
60
+ * except for the realized rates of fixed-rate windows,
60
61
  * see {@link InstanceOwnerTransactions}.
61
62
  **/
62
63
  transactions;
@@ -75,7 +76,7 @@ var GearboxPermissionless = class {
75
76
  this.oracles = new PermissionlessOracles(options, this.chains);
76
77
  this.configurators = new PermissionlessConfigurators(options, this.chains);
77
78
  this.analytics = new PermissionlessAnalytics(options);
78
- this.transactions = new InstanceOwnerTransactions(this.chains, this.oracles);
79
+ this.transactions = new InstanceOwnerTransactions(this.chains, this.oracles, this.analytics);
79
80
  this.deploy = new PermissionlessDeploy(this.chains);
80
81
  this.curator = new PermissionlessCurator(this.chains);
81
82
  }
@@ -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 };