@gearbox-protocol/sdk 13.5.0 → 13.6.0-apy-plugin.1

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/plugins/pools-history/ApyPlugin.js +328 -0
  2. package/dist/cjs/plugins/pools-history/apy-cache.js +120 -0
  3. package/dist/cjs/plugins/pools-history/apy-parser.js +169 -0
  4. package/dist/cjs/plugins/pools-history/constants.js +31 -0
  5. package/dist/cjs/plugins/pools-history/index.js +12 -2
  6. package/dist/cjs/plugins/pools-history/pool-apy-types.js +16 -0
  7. package/dist/cjs/plugins/pools-history/pool-apy-utils.js +141 -0
  8. package/dist/cjs/rewards/rewards/extra-apy.js +10 -8
  9. package/dist/cjs/sdk/GearboxSDK.js +11 -0
  10. package/dist/esm/plugins/pools-history/ApyPlugin.js +317 -0
  11. package/dist/esm/plugins/pools-history/apy-cache.js +86 -0
  12. package/dist/esm/plugins/pools-history/apy-parser.js +143 -0
  13. package/dist/esm/plugins/pools-history/constants.js +6 -0
  14. package/dist/esm/plugins/pools-history/index.js +6 -1
  15. package/dist/esm/plugins/pools-history/pool-apy-types.js +0 -0
  16. package/dist/esm/plugins/pools-history/pool-apy-utils.js +113 -0
  17. package/dist/esm/rewards/rewards/extra-apy.js +10 -8
  18. package/dist/esm/sdk/GearboxSDK.js +11 -0
  19. package/dist/types/plugins/pools-history/ApyPlugin.d.ts +70 -0
  20. package/dist/types/plugins/pools-history/apy-cache.d.ts +28 -0
  21. package/dist/types/plugins/pools-history/apy-parser.d.ts +5 -0
  22. package/dist/types/plugins/pools-history/constants.d.ts +2 -0
  23. package/dist/types/plugins/pools-history/index.d.ts +6 -1
  24. package/dist/types/plugins/pools-history/pool-apy-types.d.ts +39 -0
  25. package/dist/types/plugins/pools-history/pool-apy-utils.d.ts +71 -0
  26. package/dist/types/plugins/pools-history/types.d.ts +28 -0
  27. package/dist/types/rewards/rewards/api.d.ts +10 -1
  28. package/dist/types/rewards/rewards/common.d.ts +0 -10
  29. package/dist/types/rewards/rewards/extra-apy.d.ts +4 -6
  30. package/dist/types/sdk/GearboxSDK.d.ts +19 -0
  31. package/package.json +1 -1
  32. package/dist/cjs/plugins/pools-history/Pools7DAgoPlugin.js +0 -108
  33. package/dist/esm/plugins/pools-history/Pools7DAgoPlugin.js +0 -90
  34. package/dist/types/plugins/pools-history/Pools7DAgoPlugin.d.ts +0 -20
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var pool_apy_utils_exports = {};
20
+ __export(pool_apy_utils_exports, {
21
+ calculatePoolFullAPY: () => calculatePoolFullAPY,
22
+ calculatePoolFullAPY7DAgo: () => calculatePoolFullAPY7DAgo,
23
+ calculatePoolPoints: () => calculatePoolPoints,
24
+ calculateSupplyApy7d: () => calculateSupplyApy7d,
25
+ getPoolExtraAPY: () => getPoolExtraAPY
26
+ });
27
+ module.exports = __toCommonJS(pool_apy_utils_exports);
28
+ var import_constants = require("../../sdk/constants/index.js");
29
+ var import_formatter = require("../../sdk/utils/formatter.js");
30
+ const SCALE = 1000000n;
31
+ const WEEKS_PER_YEAR = 54n;
32
+ function getPoolExtraAPY(lookupAddresses, poolExtraAPYList) {
33
+ if (!poolExtraAPYList) return [];
34
+ const result = [];
35
+ for (const addr of lookupAddresses) {
36
+ const extra = poolExtraAPYList[addr.toLowerCase()];
37
+ if (extra) {
38
+ result.push(...extra);
39
+ }
40
+ }
41
+ return result;
42
+ }
43
+ function calculateSupplyApy7d(currentDieselRate, currentSupplyRate, dieselRate7DAgo) {
44
+ if (dieselRate7DAgo > currentDieselRate) {
45
+ return (0, import_formatter.rayToNumber)(currentSupplyRate * SCALE) / Number(import_constants.PERCENTAGE_FACTOR);
46
+ }
47
+ const apy = (currentDieselRate * import_constants.RAY / dieselRate7DAgo - import_constants.RAY) * WEEKS_PER_YEAR;
48
+ return (0, import_formatter.rayToNumber)(apy * SCALE) / Number(import_constants.PERCENTAGE_FACTOR);
49
+ }
50
+ function calculatePoolFullAPY({
51
+ depositAPY,
52
+ underlyingAPY,
53
+ extraAPY,
54
+ currentExternalList
55
+ }) {
56
+ const baseAPY = [
57
+ { type: "supplyAPY", apy: depositAPY },
58
+ ...underlyingAPY > 0 ? [
59
+ {
60
+ type: "tokenYield",
61
+ apy: Number(underlyingAPY) / Number(import_constants.PERCENTAGE_FACTOR)
62
+ }
63
+ ] : []
64
+ ];
65
+ const filteredExtra = [...extraAPY ?? []].filter((r) => r.apy > 0);
66
+ const baseAPYTotal = baseAPY.reduce((s, r) => s + (r.apy || 0), 0);
67
+ const extraAPYTotal = filteredExtra.reduce((s, r) => s + (r.apy || 0), 0);
68
+ const total = baseAPYTotal + extraAPYTotal;
69
+ const externalAPY = resolveExternalAPY(currentExternalList, total);
70
+ return {
71
+ totalAPY: total,
72
+ baseAPY,
73
+ extraAPY: filteredExtra,
74
+ extraAPYTotal,
75
+ externalAPY
76
+ };
77
+ }
78
+ function resolveExternalAPY(list, baseTotal) {
79
+ const first = list?.[0];
80
+ if (!first) return void 0;
81
+ return {
82
+ ...first,
83
+ totalValue: baseTotal + first.value
84
+ };
85
+ }
86
+ function calculatePoolFullAPY7DAgo({
87
+ supplyAPY7DAgo,
88
+ depositAPY,
89
+ poolAPY
90
+ }) {
91
+ const {
92
+ baseAPY = [],
93
+ extraAPYTotal = 0,
94
+ extraAPY = [],
95
+ externalAPY
96
+ } = poolAPY ?? {};
97
+ const base = [
98
+ { apy: supplyAPY7DAgo || depositAPY, type: "supplyAPY" },
99
+ ...baseAPY.filter((r) => r.type !== "supplyAPY")
100
+ ];
101
+ const baseTotal = base.reduce((acc, r) => acc + r.apy, 0);
102
+ const total = baseTotal + extraAPYTotal;
103
+ return {
104
+ totalAPY: total,
105
+ extraAPYTotal,
106
+ baseAPY: base,
107
+ extraAPY,
108
+ externalAPY,
109
+ loading7DAgo: supplyAPY7DAgo === void 0
110
+ };
111
+ }
112
+ function calculatePoolPoints({
113
+ poolTokenSymbol,
114
+ points,
115
+ tokensList
116
+ }) {
117
+ return points?.map(({ info, points: pts }) => {
118
+ const { decimals = 18 } = tokensList.get(info.token) || {};
119
+ const amount = (0, import_formatter.formatBN)(pts, decimals);
120
+ const { name = "Points", duration } = info ?? {};
121
+ return {
122
+ reward: info,
123
+ name,
124
+ amount,
125
+ tokenTitle: poolTokenSymbol,
126
+ fullTip: [
127
+ `${amount} ${name}`,
128
+ ...duration ? [duration] : [],
129
+ ...poolTokenSymbol ? [poolTokenSymbol] : []
130
+ ].join(" per ")
131
+ };
132
+ });
133
+ }
134
+ // Annotate the CommonJS export names for ESM import in node:
135
+ 0 && (module.exports = {
136
+ calculatePoolFullAPY,
137
+ calculatePoolFullAPY7DAgo,
138
+ calculatePoolPoints,
139
+ calculateSupplyApy7d,
140
+ getPoolExtraAPY
141
+ });
@@ -82,11 +82,13 @@ class PoolPointsAPI {
82
82
  tokensList
83
83
  }) {
84
84
  const r = pools.reduce((acc, p) => {
85
- const pointsInfo = poolRewards[p.address] || [];
85
+ const poolAddress = p.pool.pool.address.toLowerCase();
86
+ const pointsInfo = poolRewards[poolAddress] || [];
86
87
  const poolPointsList = pointsInfo.reduce(
87
88
  (acc2, pointsInfo2) => {
88
- const { address: tokenAddress } = tokensList[pointsInfo2.token] || {};
89
- const tokenBalance = totalTokenBalances[tokenAddress || ""];
89
+ const { addr: tokenAddress } = tokensList.get(pointsInfo2.token) || {};
90
+ const tokenAddressLower = (tokenAddress || "").toLowerCase();
91
+ const tokenBalance = totalTokenBalances[tokenAddressLower];
90
92
  const points = PoolPointsAPI.getPoolTokenPoints(
91
93
  tokenBalance,
92
94
  p,
@@ -104,22 +106,22 @@ class PoolPointsAPI {
104
106
  },
105
107
  []
106
108
  );
107
- acc[p.address] = poolPointsList;
109
+ acc[poolAddress] = poolPointsList;
108
110
  return acc;
109
111
  }, {});
110
112
  return r;
111
113
  }
112
114
  static getPoolTokenPoints(tokenBalanceInPool, pool, tokensList, pointsInfo) {
113
- if (pool.expectedLiquidity <= 0) return 0n;
115
+ if (pool.pool.pool.expectedLiquidity <= 0) return 0n;
114
116
  if (pointsInfo.estimation === "relative" && !tokenBalanceInPool)
115
117
  return null;
116
- const { decimals = 18 } = tokensList[pointsInfo.token] || {};
118
+ const { decimals = 18 } = tokensList.get(pointsInfo.token) || {};
117
119
  const targetFactor = 10n ** BigInt(decimals);
118
120
  const defaultPoints = pointsInfo.amount * targetFactor / import_sdk.PERCENTAGE_FACTOR;
119
121
  if (pointsInfo.estimation === "absolute") return defaultPoints;
120
- const { decimals: underlyingDecimals = 18 } = tokensList[pool.underlyingToken] || {};
122
+ const { decimals: underlyingDecimals = 18 } = tokensList.get(pool.pool.pool.underlying) || {};
121
123
  const underlyingFactor = 10n ** BigInt(underlyingDecimals);
122
- const points = (tokenBalanceInPool?.balance || 0n) * defaultPoints / (pool.expectedLiquidity * targetFactor / underlyingFactor);
124
+ const points = (tokenBalanceInPool?.balance || 0n) * defaultPoints / (pool.pool.pool.expectedLiquidity * targetFactor / underlyingFactor);
123
125
  return import_common_utils.BigIntMath.min(points, defaultPoints);
124
126
  }
125
127
  }
@@ -110,6 +110,17 @@ class GearboxSDK extends import_base.ChainContractsRegister {
110
110
  * @see {@link SDKHooks} for available event names.
111
111
  **/
112
112
  removeHook = this.#hooks.removeHook.bind(this.#hooks);
113
+ /**
114
+ * Triggers the `pluginUpdate` hook.
115
+ *
116
+ * Intended to be called by plugins when they update their internal state
117
+ * outside of the normal `syncState`/`rehydrate` cycle (e.g. via an
118
+ * internal timer). Frontend listeners registered with
119
+ * `sdk.addHook("pluginUpdate", …)` will be notified.
120
+ **/
121
+ async triggerPluginUpdate(plugin) {
122
+ await this.#hooks.triggerHooks("pluginUpdate", { plugin });
123
+ }
113
124
  /**
114
125
  * Creates and initialises a new SDK instance by reading live on-chain state.
115
126
  *
@@ -0,0 +1,317 @@
1
+ import { marketCompressorAbi } from "../../abi/compressors/marketCompressor.js";
2
+ import { PoolPointsAPI } from "../../rewards/rewards/extra-apy.js";
3
+ import {
4
+ AddressMap,
5
+ AP_MARKET_COMPRESSOR,
6
+ BasePlugin,
7
+ BLOCKS_PER_WEEK_BY_NETWORK,
8
+ PERCENTAGE_DECIMALS,
9
+ VERSION_RANGE_310
10
+ } from "../../sdk/index.js";
11
+ import { rayToNumber } from "../../sdk/utils/formatter.js";
12
+ import { hexEq } from "../../sdk/utils/hex.js";
13
+ import { ApyOutputCache } from "./apy-cache.js";
14
+ import { parseGearStats, parseNetworkApy } from "./apy-parser.js";
15
+ import { APY_STATE_CACHE_URL, DEFAULT_APY_INTERVAL_MS } from "./constants.js";
16
+ import {
17
+ calculatePoolFullAPY,
18
+ calculatePoolFullAPY7DAgo,
19
+ calculatePoolPoints,
20
+ calculateSupplyApy7d,
21
+ getPoolExtraAPY
22
+ } from "./pool-apy-utils.js";
23
+ const MAP_LABEL = "pools7DAgo";
24
+ const PLUGIN_KEY = "ApyPlugin";
25
+ class ApyPlugin extends BasePlugin {
26
+ #timerInterval;
27
+ #apyUrl;
28
+ #cacheTtlMs;
29
+ #pools7DAgo;
30
+ #apySnapshot;
31
+ /**
32
+ * Default timer options
33
+ * @see PluginTimerOptions
34
+ */
35
+ #defaultTimerOptions;
36
+ /**
37
+ * When `true`, the timer is started eagerly during the `attach` phase
38
+ * rather than waiting for an explicit `load` call.
39
+ **/
40
+ startTimerOnAttach;
41
+ constructor(loadOnAttach = false, startTimerOnAttach = false, options) {
42
+ super(loadOnAttach);
43
+ this.startTimerOnAttach = startTimerOnAttach;
44
+ this.#apyUrl = options?.apyUrl ?? APY_STATE_CACHE_URL;
45
+ this.#cacheTtlMs = options?.cacheTtlMs ?? DEFAULT_APY_INTERVAL_MS;
46
+ this.#defaultTimerOptions = options?.timer ?? {
47
+ refreshPools7DAgoOnTick: false,
48
+ intervalMs: DEFAULT_APY_INTERVAL_MS,
49
+ onChange: () => {
50
+ }
51
+ };
52
+ }
53
+ async attach() {
54
+ await super.attach();
55
+ if (this.startTimerOnAttach) {
56
+ this.startTimer();
57
+ }
58
+ }
59
+ // ---------------------------------------------------------------------------
60
+ // Load — single entry point for all data (on-chain + state-cache)
61
+ // ---------------------------------------------------------------------------
62
+ async load(force, loadOptions) {
63
+ if (!force && this.loaded) {
64
+ return this.state;
65
+ }
66
+ const targetBlock = this.sdk.currentBlock - BLOCKS_PER_WEEK_BY_NETWORK[this.sdk.networkType];
67
+ const [marketCompressorAddress] = this.sdk.addressProvider.mustGetLatest(
68
+ AP_MARKET_COMPRESSOR,
69
+ VERSION_RANGE_310
70
+ );
71
+ this.#logger?.debug(
72
+ `loading pools 7d ago with market compressor ${marketCompressorAddress}`
73
+ );
74
+ const markets = this.sdk.marketRegister.markets;
75
+ const shouldLoadPools7DAgo = !this.#pools7DAgo || !!loadOptions?.loadPools7DAgo;
76
+ const [multicallResp, apySnapshot] = await Promise.all([
77
+ shouldLoadPools7DAgo ? this.client.multicall({
78
+ allowFailure: true,
79
+ contracts: markets.map(
80
+ (m) => ({
81
+ address: marketCompressorAddress,
82
+ abi: marketCompressorAbi,
83
+ functionName: "getPoolState",
84
+ args: [m.pool.pool.address]
85
+ })
86
+ ),
87
+ blockNumber: targetBlock > 0n ? targetBlock : void 0,
88
+ batchSize: 0
89
+ }) : null,
90
+ this.#fetchApy()
91
+ ]);
92
+ if (multicallResp !== null) {
93
+ this.#pools7DAgo = new AddressMap(void 0, MAP_LABEL);
94
+ multicallResp.forEach((r, index) => {
95
+ const m = markets[index];
96
+ const cfg = m.configurator.address;
97
+ const pool = m.pool.pool.address;
98
+ if (r.status === "success") {
99
+ this.#pools7DAgo?.upsert(m.pool.pool.address, {
100
+ dieselRate: r.result.dieselRate,
101
+ pool
102
+ });
103
+ } else {
104
+ this.#logger?.error(
105
+ `failed to load pools 7d ago for market configurator ${this.labelAddress(cfg)} and pool ${this.labelAddress(pool)}: ${r.error}`
106
+ );
107
+ }
108
+ });
109
+ }
110
+ if (apySnapshot) {
111
+ this.#apySnapshot = apySnapshot;
112
+ }
113
+ return this.state;
114
+ }
115
+ get loaded() {
116
+ return !!this.#pools7DAgo && !!this.#apySnapshot;
117
+ }
118
+ // ---------------------------------------------------------------------------
119
+ // Accessors
120
+ // ---------------------------------------------------------------------------
121
+ /**
122
+ * @throws if plugin is not loaded
123
+ */
124
+ get pools7DAgo() {
125
+ if (!this.#pools7DAgo) {
126
+ throw new Error("apy plugin not loaded");
127
+ }
128
+ return this.#pools7DAgo;
129
+ }
130
+ /**
131
+ * @throws if plugin is not loaded
132
+ */
133
+ get apySnapshot() {
134
+ if (!this.#apySnapshot) {
135
+ throw new Error("apy plugin not loaded");
136
+ }
137
+ return this.#apySnapshot;
138
+ }
139
+ // ---------------------------------------------------------------------------
140
+ // Aggregated APY / points
141
+ // ---------------------------------------------------------------------------
142
+ /**
143
+ * Computes per-pool APY (current + 7d-ago) and points for all markets.
144
+ *
145
+ * @throws if plugin is not loaded
146
+ */
147
+ getPoolsAPY() {
148
+ if (!this.loaded) {
149
+ throw new Error("apy plugin not loaded");
150
+ }
151
+ const markets = this.sdk.marketRegister.markets;
152
+ const { apy } = this.apySnapshot;
153
+ const totalTokenBalances = {};
154
+ const poolPointsBase = apy.poolRewardsList && Object.keys(apy.poolRewardsList).length > 0 ? PoolPointsAPI.getPointsByPool({
155
+ poolRewards: apy.poolRewardsList,
156
+ totalTokenBalances,
157
+ pools: markets,
158
+ tokensList: this.sdk.tokensMeta
159
+ }) : {};
160
+ const data = {};
161
+ const data7DAgo = {};
162
+ const points = {};
163
+ for (const market of markets) {
164
+ const pool = market.pool.pool;
165
+ const poolAddr = pool.address.toLowerCase();
166
+ const depositAPY = rayToNumber(pool.supplyRate) * Number(PERCENTAGE_DECIMALS);
167
+ const underlyingAPY = apy.apyList?.[pool.underlying] ?? 0;
168
+ const lookupAddresses = this.#getExtraAPYLookupAddresses(poolAddr);
169
+ const extraAPY = getPoolExtraAPY(lookupAddresses, apy.poolExtraAPYList);
170
+ const currentExternalList = apy.poolExternalAPYList?.[poolAddr];
171
+ const poolAPY = calculatePoolFullAPY({
172
+ depositAPY,
173
+ underlyingAPY,
174
+ extraAPY,
175
+ currentExternalList
176
+ });
177
+ data[poolAddr] = poolAPY;
178
+ const pool7DAgo = this.#pools7DAgo?.get(poolAddr);
179
+ const supplyAPY7DAgo = pool7DAgo ? calculateSupplyApy7d(
180
+ pool.dieselRate,
181
+ pool.supplyRate,
182
+ pool7DAgo.dieselRate
183
+ ) : void 0;
184
+ data7DAgo[poolAddr] = calculatePoolFullAPY7DAgo({
185
+ supplyAPY7DAgo,
186
+ depositAPY,
187
+ poolAPY
188
+ });
189
+ const poolTokenMeta = this.sdk.tokensMeta.get(pool.underlying);
190
+ points[poolAddr] = calculatePoolPoints({
191
+ poolTokenSymbol: poolTokenMeta?.symbol,
192
+ points: poolPointsBase[poolAddr],
193
+ tokensList: this.sdk.tokensMeta
194
+ });
195
+ }
196
+ return { data, data7DAgo, points };
197
+ }
198
+ // ---------------------------------------------------------------------------
199
+ // Periodic full refresh
200
+ // ---------------------------------------------------------------------------
201
+ /**
202
+ * Starts a periodic timer that performs a full plugin state refresh.
203
+ * Only one timer can be active; calling again is a no-op.
204
+ * @returns Cleanup function that stops the timer.
205
+ */
206
+ startTimer(opts) {
207
+ if (this.#timerInterval) {
208
+ this.#logger?.debug("plugin timer already running");
209
+ return () => this.stopTimer();
210
+ }
211
+ const intervalMs = opts?.intervalMs ?? this.#defaultTimerOptions.intervalMs;
212
+ this.#logger?.debug(`starting plugin timer (interval: ${intervalMs}ms)`);
213
+ this.#timerInterval = setInterval(async () => {
214
+ try {
215
+ const prevTimestamp = this.#apySnapshot?.timestamp;
216
+ await this.load(true, {
217
+ loadPools7DAgo: opts?.refreshPools7DAgoOnTick ?? this.#defaultTimerOptions.refreshPools7DAgoOnTick
218
+ });
219
+ if (this.#apySnapshot?.timestamp !== prevTimestamp) {
220
+ opts?.onChange?.() ?? this.#defaultTimerOptions.onChange?.();
221
+ await this.sdk.triggerPluginUpdate(PLUGIN_KEY);
222
+ }
223
+ } catch (e) {
224
+ this.#logger?.error(e, "periodic refresh failed");
225
+ }
226
+ }, intervalMs);
227
+ return () => this.stopTimer();
228
+ }
229
+ stopTimer() {
230
+ if (this.#timerInterval) {
231
+ clearInterval(this.#timerInterval);
232
+ this.#timerInterval = void 0;
233
+ this.#logger?.debug("plugin timer stopped");
234
+ }
235
+ }
236
+ // ---------------------------------------------------------------------------
237
+ // Plugin lifecycle
238
+ // ---------------------------------------------------------------------------
239
+ async syncState() {
240
+ await this.load(true);
241
+ }
242
+ stateHuman(_) {
243
+ return this.pools7DAgo.values().flatMap((p) => ({
244
+ address: p.pool,
245
+ version: this.version,
246
+ dieselRate: p.dieselRate
247
+ }));
248
+ }
249
+ get state() {
250
+ return {
251
+ pools7DAgo: this.pools7DAgo.asRecord(),
252
+ apySnapshot: this.apySnapshot
253
+ };
254
+ }
255
+ hydrate(state) {
256
+ this.#pools7DAgo = new AddressMap(
257
+ Object.entries(state.pools7DAgo),
258
+ MAP_LABEL
259
+ );
260
+ this.#apySnapshot = state.apySnapshot;
261
+ }
262
+ // ---------------------------------------------------------------------------
263
+ // Internal
264
+ // ---------------------------------------------------------------------------
265
+ async #fetchApy() {
266
+ try {
267
+ const cache = ApyOutputCache.get(
268
+ this.#apyUrl,
269
+ this.#cacheTtlMs,
270
+ this.#logger
271
+ );
272
+ const output = await cache.fetch();
273
+ if (!output) return void 0;
274
+ const chainData = output.chains[this.sdk.chainId];
275
+ if (!chainData) {
276
+ this.#logger?.debug(
277
+ `apy state-cache: no data for chainId ${this.sdk.chainId}`
278
+ );
279
+ return void 0;
280
+ }
281
+ const apy = parseNetworkApy(chainData.tokens, chainData.pools);
282
+ if (!apy) return void 0;
283
+ return {
284
+ apy,
285
+ gearStats: parseGearStats(output),
286
+ timestamp: output.timestamp
287
+ };
288
+ } catch (e) {
289
+ this.#logger?.error(e, "failed to fetch apy state-cache");
290
+ return void 0;
291
+ }
292
+ }
293
+ /**
294
+ * Collects addresses to look up in poolExtraAPYList for a given pool.
295
+ * Includes pool address (= diesel token) + any staked diesel token
296
+ * outputs discovered from zappers.
297
+ */
298
+ #getExtraAPYLookupAddresses(poolAddr) {
299
+ const addresses = [poolAddr];
300
+ try {
301
+ const zappers = this.sdk.marketRegister.poolZappers(poolAddr);
302
+ for (const z of zappers) {
303
+ if (!hexEq(z.tokenOut.addr, poolAddr)) {
304
+ addresses.push(z.tokenOut.addr);
305
+ }
306
+ }
307
+ } catch {
308
+ }
309
+ return addresses;
310
+ }
311
+ get #logger() {
312
+ return this.logger;
313
+ }
314
+ }
315
+ export {
316
+ ApyPlugin
317
+ };
@@ -0,0 +1,86 @@
1
+ import axios from "axios";
2
+ class ApyOutputCache {
3
+ static #instances = /* @__PURE__ */ new Map();
4
+ #url;
5
+ #ttlMs;
6
+ #cache;
7
+ #pending;
8
+ #logger;
9
+ constructor(url, ttlMs, logger) {
10
+ this.#url = url;
11
+ this.#ttlMs = ttlMs;
12
+ this.#logger = logger;
13
+ }
14
+ /**
15
+ * Returns a shared cache instance for the given URL.
16
+ * The same instance is reused across all callers with identical URL.
17
+ */
18
+ static get(url, ttlMs, logger) {
19
+ let instance = ApyOutputCache.#instances.get(url);
20
+ if (!instance) {
21
+ instance = new ApyOutputCache(url, ttlMs, logger);
22
+ ApyOutputCache.#instances.set(url, instance);
23
+ }
24
+ if (logger) {
25
+ instance.#logger = logger;
26
+ }
27
+ return instance;
28
+ }
29
+ /**
30
+ * Returns cached Output if fresh, otherwise fetches from the network.
31
+ * Concurrent calls are de-duplicated.
32
+ */
33
+ async fetch() {
34
+ if (this.#cache && Date.now() - this.#cache.fetchedAt < this.#ttlMs) {
35
+ this.#logger?.debug("apy cache: TTL still valid, returning cached data");
36
+ return this.#cache.data;
37
+ }
38
+ if (this.#pending) {
39
+ this.#logger?.debug("apy cache: request in flight, waiting");
40
+ return this.#pending;
41
+ }
42
+ this.#pending = this.#doFetch();
43
+ try {
44
+ return await this.#pending;
45
+ } finally {
46
+ this.#pending = void 0;
47
+ }
48
+ }
49
+ async #doFetch() {
50
+ try {
51
+ const headers = {};
52
+ if (this.#cache?.etag) {
53
+ headers["If-None-Match"] = this.#cache.etag;
54
+ }
55
+ const response = await axios.get(this.#url, {
56
+ headers,
57
+ validateStatus: (status) => status === 200 || status === 304
58
+ });
59
+ if (response.status === 304 && this.#cache) {
60
+ this.#cache.fetchedAt = Date.now();
61
+ this.#logger?.debug("apy cache: 304 Not Modified, extended TTL");
62
+ return this.#cache.data;
63
+ }
64
+ const etag = response.headers["etag"];
65
+ this.#cache = {
66
+ data: response.data,
67
+ etag,
68
+ fetchedAt: Date.now()
69
+ };
70
+ this.#logger?.debug(
71
+ `apy cache: fetched fresh data (timestamp: ${response.data.timestamp})`
72
+ );
73
+ return response.data;
74
+ } catch (e) {
75
+ this.#logger?.error(e, "apy cache: fetch failed");
76
+ return this.#cache?.data;
77
+ }
78
+ }
79
+ /** Evicts all cached entries. Mainly useful for tests. */
80
+ static clearAll() {
81
+ ApyOutputCache.#instances.clear();
82
+ }
83
+ }
84
+ export {
85
+ ApyOutputCache
86
+ };