@gearbox-protocol/sdk 13.6.0-kyc.7 → 13.6.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 (155) hide show
  1. package/dist/cjs/dev/AccountOpener.js +5 -45
  2. package/dist/cjs/dev/logSplitterTransport.js +10 -1
  3. package/dist/cjs/plugins/adapters/abi/actionAbi.js +1 -1
  4. package/dist/cjs/plugins/adapters/abi/conctructorAbi.js +1 -1
  5. package/dist/cjs/plugins/adapters/createAdapter.js +1 -1
  6. package/dist/cjs/plugins/adapters/types.js +1 -1
  7. package/dist/cjs/plugins/apy/ApyPlugin.js +266 -0
  8. package/dist/cjs/plugins/apy/apy-cache.js +120 -0
  9. package/dist/cjs/plugins/apy/apy-parser.js +169 -0
  10. package/dist/cjs/{sdk/market/kyc/securitize → plugins/apy}/constants.js +6 -3
  11. package/dist/cjs/{sdk/market/kyc/securitize → plugins/apy}/index.js +14 -6
  12. package/dist/cjs/{sdk/market/kyc/securitize/types.js → plugins/apy/pool-apy-types.js} +2 -2
  13. package/dist/cjs/plugins/apy/pool-apy-utils.js +141 -0
  14. package/dist/cjs/rewards/rewards/extra-apy.js +10 -8
  15. package/dist/cjs/sdk/GearboxSDK.js +5 -52
  16. package/dist/cjs/sdk/accounts/AbstractCreditAccountsService.js +16 -324
  17. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +1 -7
  18. package/dist/cjs/sdk/base/TokensMeta.js +43 -32
  19. package/dist/cjs/sdk/base/token-types.js +0 -9
  20. package/dist/cjs/sdk/chain/chains.js +32 -17
  21. package/dist/cjs/sdk/constants/address-provider.js +0 -3
  22. package/dist/cjs/sdk/market/MarketRegister.js +116 -70
  23. package/dist/cjs/sdk/market/MarketSuite.js +0 -3
  24. package/dist/cjs/sdk/market/index.js +0 -2
  25. package/dist/cjs/sdk/market/pool/PoolSuite.js +0 -3
  26. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +2 -11
  27. package/dist/cjs/sdk/market/pool/index.js +0 -2
  28. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +3 -3
  29. package/dist/cjs/sdk/options.js +1 -7
  30. package/dist/cjs/sdk/pools/PoolService.js +12 -104
  31. package/dist/cjs/sdk/utils/viem/index.js +0 -2
  32. package/dist/cjs/sdk/utils/viem/simulateWithPriceUpdates.js +39 -2
  33. package/dist/esm/dev/AccountOpener.js +6 -47
  34. package/dist/esm/dev/logSplitterTransport.js +10 -1
  35. package/dist/esm/plugins/adapters/abi/actionAbi.js +1 -1
  36. package/dist/esm/plugins/adapters/abi/conctructorAbi.js +1 -1
  37. package/dist/esm/plugins/adapters/createAdapter.js +1 -1
  38. package/dist/esm/plugins/adapters/types.js +1 -1
  39. package/dist/esm/plugins/apy/ApyPlugin.js +255 -0
  40. package/dist/esm/plugins/apy/apy-cache.js +86 -0
  41. package/dist/esm/plugins/apy/apy-parser.js +143 -0
  42. package/dist/esm/plugins/apy/constants.js +6 -0
  43. package/dist/esm/plugins/apy/index.js +7 -0
  44. package/dist/esm/plugins/apy/pool-apy-utils.js +113 -0
  45. package/dist/esm/rewards/rewards/extra-apy.js +10 -8
  46. package/dist/esm/sdk/GearboxSDK.js +6 -56
  47. package/dist/esm/sdk/accounts/AbstractCreditAccountsService.js +17 -328
  48. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +1 -7
  49. package/dist/esm/sdk/base/TokensMeta.js +45 -32
  50. package/dist/esm/sdk/base/token-types.js +0 -6
  51. package/dist/esm/sdk/chain/chains.js +32 -17
  52. package/dist/esm/sdk/constants/address-provider.js +0 -2
  53. package/dist/esm/sdk/market/MarketRegister.js +118 -74
  54. package/dist/esm/sdk/market/MarketSuite.js +0 -3
  55. package/dist/esm/sdk/market/index.js +0 -1
  56. package/dist/esm/sdk/market/pool/PoolSuite.js +0 -3
  57. package/dist/esm/sdk/market/pool/PoolV310Contract.js +2 -11
  58. package/dist/esm/sdk/market/pool/index.js +0 -1
  59. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +3 -3
  60. package/dist/esm/sdk/options.js +1 -7
  61. package/dist/esm/sdk/pools/PoolService.js +13 -109
  62. package/dist/esm/sdk/utils/viem/index.js +0 -1
  63. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +41 -2
  64. package/dist/types/dev/logSplitterTransport.d.ts +3 -1
  65. package/dist/types/plugins/adapters/types.d.ts +2 -2
  66. package/dist/types/plugins/apy/ApyPlugin.d.ts +46 -0
  67. package/dist/types/plugins/apy/apy-cache.d.ts +28 -0
  68. package/dist/types/plugins/apy/apy-parser.d.ts +5 -0
  69. package/dist/types/plugins/apy/constants.d.ts +2 -0
  70. package/dist/types/plugins/apy/index.d.ts +7 -0
  71. package/dist/types/plugins/apy/pool-apy-types.d.ts +41 -0
  72. package/dist/types/plugins/apy/pool-apy-utils.d.ts +73 -0
  73. package/dist/types/plugins/apy/types.d.ts +37 -0
  74. package/dist/types/rewards/rewards/api.d.ts +10 -1
  75. package/dist/types/rewards/rewards/common.d.ts +0 -10
  76. package/dist/types/rewards/rewards/extra-apy.d.ts +4 -6
  77. package/dist/types/sdk/GearboxSDK.d.ts +0 -7
  78. package/dist/types/sdk/accounts/AbstractCreditAccountsService.d.ts +2 -52
  79. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -1
  80. package/dist/types/sdk/accounts/types.d.ts +13 -93
  81. package/dist/types/sdk/base/TokensMeta.d.ts +3 -14
  82. package/dist/types/sdk/base/token-types.d.ts +4 -44
  83. package/dist/types/sdk/base/types.d.ts +11 -116
  84. package/dist/types/sdk/chain/chains.d.ts +5 -5
  85. package/dist/types/sdk/constants/address-provider.d.ts +0 -1
  86. package/dist/types/sdk/market/MarketRegister.d.ts +9 -6
  87. package/dist/types/sdk/market/MarketSuite.d.ts +0 -2
  88. package/dist/types/sdk/market/index.d.ts +0 -1
  89. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +2 -3
  90. package/dist/types/sdk/market/oracle/types.d.ts +10 -3
  91. package/dist/types/sdk/market/pool/PoolSuite.d.ts +0 -2
  92. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +2 -6
  93. package/dist/types/sdk/market/pool/index.d.ts +0 -1
  94. package/dist/types/sdk/market/pricefeeds/PriceFeedsRegister.d.ts +1 -1
  95. package/dist/types/sdk/market/types.d.ts +1 -1
  96. package/dist/types/sdk/options.d.ts +0 -1
  97. package/dist/types/sdk/pools/PoolService.d.ts +8 -8
  98. package/dist/types/sdk/pools/types.d.ts +1 -1
  99. package/dist/types/sdk/types/state-human.d.ts +0 -2
  100. package/dist/types/sdk/types/state.d.ts +0 -5
  101. package/dist/types/sdk/utils/viem/index.d.ts +0 -1
  102. package/package.json +2 -3
  103. package/dist/cjs/abi/kyc/iDSRegistryService.js +0 -70
  104. package/dist/cjs/abi/kyc/iDSToken.js +0 -71
  105. package/dist/cjs/abi/kyc/iKYCCompressor.js +0 -196
  106. package/dist/cjs/abi/kyc/iKYCFactory.js +0 -122
  107. package/dist/cjs/abi/kyc/iKYCUnderlying.js +0 -401
  108. package/dist/cjs/abi/kyc/iSecuritizeDegenNFT.js +0 -326
  109. package/dist/cjs/abi/kyc/iSecuritizeKYCFactory.js +0 -319
  110. package/dist/cjs/plugins/pools-history/Pools7DAgoPlugin.js +0 -108
  111. package/dist/cjs/plugins/pools-history/index.js +0 -24
  112. package/dist/cjs/sdk/market/kyc/KYCRegistry.js +0 -269
  113. package/dist/cjs/sdk/market/kyc/index.js +0 -26
  114. package/dist/cjs/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +0 -244
  115. package/dist/cjs/sdk/market/kyc/types.js +0 -34
  116. package/dist/cjs/sdk/utils/viem/executeDelegatedMulticalls.js +0 -38
  117. package/dist/esm/abi/kyc/iDSRegistryService.js +0 -46
  118. package/dist/esm/abi/kyc/iDSToken.js +0 -47
  119. package/dist/esm/abi/kyc/iKYCCompressor.js +0 -172
  120. package/dist/esm/abi/kyc/iKYCFactory.js +0 -98
  121. package/dist/esm/abi/kyc/iKYCUnderlying.js +0 -377
  122. package/dist/esm/abi/kyc/iSecuritizeDegenNFT.js +0 -302
  123. package/dist/esm/abi/kyc/iSecuritizeKYCFactory.js +0 -295
  124. package/dist/esm/plugins/pools-history/Pools7DAgoPlugin.js +0 -90
  125. package/dist/esm/plugins/pools-history/index.js +0 -2
  126. package/dist/esm/sdk/market/kyc/KYCRegistry.js +0 -253
  127. package/dist/esm/sdk/market/kyc/index.js +0 -3
  128. package/dist/esm/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +0 -220
  129. package/dist/esm/sdk/market/kyc/securitize/constants.js +0 -4
  130. package/dist/esm/sdk/market/kyc/securitize/index.js +0 -3
  131. package/dist/esm/sdk/market/kyc/types.js +0 -9
  132. package/dist/esm/sdk/utils/viem/executeDelegatedMulticalls.js +0 -14
  133. package/dist/types/abi/kyc/iDSRegistryService.d.ts +0 -71
  134. package/dist/types/abi/kyc/iDSToken.d.ts +0 -67
  135. package/dist/types/abi/kyc/iKYCCompressor.d.ts +0 -228
  136. package/dist/types/abi/kyc/iKYCFactory.d.ts +0 -139
  137. package/dist/types/abi/kyc/iKYCUnderlying.d.ts +0 -548
  138. package/dist/types/abi/kyc/iSecuritizeDegenNFT.d.ts +0 -404
  139. package/dist/types/abi/kyc/iSecuritizeKYCFactory.d.ts +0 -376
  140. package/dist/types/plugins/pools-history/Pools7DAgoPlugin.d.ts +0 -20
  141. package/dist/types/plugins/pools-history/index.d.ts +0 -2
  142. package/dist/types/plugins/pools-history/types.d.ts +0 -9
  143. package/dist/types/sdk/market/kyc/KYCRegistry.d.ts +0 -52
  144. package/dist/types/sdk/market/kyc/index.d.ts +0 -3
  145. package/dist/types/sdk/market/kyc/securitize/SecuritizeKYCFactory.d.ts +0 -428
  146. package/dist/types/sdk/market/kyc/securitize/constants.d.ts +0 -1
  147. package/dist/types/sdk/market/kyc/securitize/index.d.ts +0 -3
  148. package/dist/types/sdk/market/kyc/securitize/types.d.ts +0 -127
  149. package/dist/types/sdk/market/kyc/types.d.ts +0 -170
  150. package/dist/types/sdk/utils/viem/executeDelegatedMulticalls.d.ts +0 -28
  151. /package/dist/cjs/plugins/{pools-history → apy}/package.json +0 -0
  152. /package/dist/cjs/plugins/{pools-history → apy}/types.js +0 -0
  153. /package/dist/esm/plugins/{pools-history → apy}/package.json +0 -0
  154. /package/dist/esm/plugins/{pools-history/types.js → apy/pool-apy-types.js} +0 -0
  155. /package/dist/esm/{sdk/market/kyc/securitize → plugins/apy}/types.js +0 -0
@@ -52,7 +52,6 @@ class AccountOpener extends import_sdk.SDKConstruct {
52
52
  #minDebtMultiplier;
53
53
  #allowMint;
54
54
  #leverageDelta;
55
- #poolService;
56
55
  constructor(service, options_ = {}) {
57
56
  super(service.sdk);
58
57
  const {
@@ -78,7 +77,6 @@ class AccountOpener extends import_sdk.SDKConstruct {
78
77
  this.#poolDepositMultiplier = BigInt(poolDepositMultiplier);
79
78
  this.#minDebtMultiplier = BigInt(minDebtMultiplier);
80
79
  this.#leverageDelta = BigInt(leverageDelta);
81
- this.#poolService = new import_sdk.PoolService(service.sdk);
82
80
  this.#logger?.info(
83
81
  {
84
82
  borrower: (0, import_accounts.privateKeyToAccount)(this.borrowerKey).address,
@@ -116,10 +114,6 @@ class AccountOpener extends import_sdk.SDKConstruct {
116
114
  },
117
115
  "opening credit accounts"
118
116
  );
119
- await Promise.all([
120
- this.sdk.tokensMeta.loadTokenData(),
121
- this.sdk.marketRegister.loadZappers()
122
- ]);
123
117
  let deposits = [];
124
118
  if (depositIntoPools) {
125
119
  try {
@@ -471,34 +465,9 @@ class AccountOpener extends import_sdk.SDKConstruct {
471
465
  this.#logger?.debug(
472
466
  `depositor balance in underlying: ${this.sdk.tokensMeta.formatBN(pool.underlying, allowance, { symbol: true })}`
473
467
  );
474
- const tokensOut = this.#poolService.getDepositTokensOut(
475
- address,
476
- underlying
477
- );
478
- this.#logger?.debug(
479
- { tokensOut: tokensOut.map((t) => this.labelAddress(t)) },
480
- "deposit tokens out"
481
- );
482
- if (tokensOut.length === 0) {
483
- throw new Error(`no tokens out found for pool ${poolName}`);
484
- }
485
- const tokenOut = tokensOut[0];
486
- const metadata = this.#poolService.getDepositMetadata(
487
- address,
488
- underlying,
489
- tokenOut
490
- );
491
- this.logger?.debug(
492
- {
493
- underlying: this.labelAddress(underlying),
494
- tokenOut: this.labelAddress(tokenOut),
495
- ...metadata
496
- },
497
- "pool deposit metadata"
498
- );
499
468
  txHash = await this.#anvil.writeContract({
500
469
  account: depositor,
501
- address: metadata.approveTarget,
470
+ address: underlying,
502
471
  abi: import_iERC20.ierc20Abi,
503
472
  functionName: "approve",
504
473
  args: [address, allowance],
@@ -515,21 +484,12 @@ class AccountOpener extends import_sdk.SDKConstruct {
515
484
  this.#logger?.debug(
516
485
  `depositor approved underlying for pool ${poolName}: ${txHash}`
517
486
  );
518
- const depositCall = this.#poolService.addLiquidity({
519
- collateral: { token: underlying, balance: amount },
520
- pool: address,
521
- wallet: depositor.address,
522
- meta: metadata
523
- });
524
- if (!depositCall) {
525
- throw new Error(`no deposit call could be created for ${poolName}`);
526
- }
527
487
  txHash = await this.#anvil.writeContract({
528
488
  account: depositor,
529
- address: depositCall.target,
530
- abi: depositCall.abi,
531
- functionName: depositCall.functionName,
532
- args: depositCall.args,
489
+ address,
490
+ abi: import_generated.iPoolV310Abi,
491
+ functionName: "deposit",
492
+ args: [amount, depositor.address],
533
493
  chain: this.#anvil.chain
534
494
  });
535
495
  receipt = await this.#anvil.waitForTransactionReceipt({ hash: txHash });
@@ -43,7 +43,9 @@ const RANGE_ERROR_PATTERNS = [
43
43
  /eth_getLogs is limited to/i,
44
44
  /eth_getLogs requests with up to/i,
45
45
  /range is too large/i,
46
- /exceeded max allowed range/i
46
+ /exceeded max allowed range/i,
47
+ // Encountered on DRPC: "query exceeds max results 20000, retry with the range …"
48
+ /exceeds max results/i
47
49
  ];
48
50
  function isRangeError(error) {
49
51
  const msg = errorMessage(error);
@@ -51,10 +53,17 @@ function isRangeError(error) {
51
53
  }
52
54
  const GENERIC_BLOCKS_RE = /(\d+)\s*block/i;
53
55
  const ALCHEMY_RANGE_RE = /this block range should work: \[(0x[0-9a-fA-F]+),\s*(0x[0-9a-fA-F]+)\]/;
56
+ const DRPC_RANGE_RE = /retry with the range (\d+)-(\d+)/;
54
57
  function parsePageSizeHint(error) {
55
58
  const alchemy = tryAlchemyHint(error);
56
59
  if (alchemy != null) return alchemy;
57
60
  const msg = errorMessage(error);
61
+ const drpc = msg.match(DRPC_RANGE_RE);
62
+ if (drpc) {
63
+ const from = Number(drpc[1]);
64
+ const to = Number(drpc[2]);
65
+ return to - from + 1;
66
+ }
58
67
  const m = msg.match(GENERIC_BLOCKS_RE);
59
68
  return m ? Number(m[1]) : null;
60
69
  }
@@ -73,7 +73,7 @@ const adapterActionSignatures = {
73
73
  310: "function setPairStatusBatch((address,address,address,uint8)[])",
74
74
  311: "function setPairStatusBatch((address,address,address,uint8,uint8)[])"
75
75
  },
76
- [import_types.AdapterType.TRADERJOE_ROUTER]: {
76
+ [import_types.AdapterType.TRADER_JOE_ROUTER]: {
77
77
  310: "function setPoolStatusBatch((address,address,uint256,uint8,bool)[])"
78
78
  },
79
79
  [import_types.AdapterType.UNISWAP_V2_ROUTER]: {
@@ -72,7 +72,7 @@ const adapterConstructorAbi = {
72
72
  [import_types.AdapterType.DAI_USDS_EXCHANGE]: {
73
73
  310: import_conctructorAbiPatterns.BASIC_ADAPTER_ABI
74
74
  },
75
- [import_types.AdapterType.TRADERJOE_ROUTER]: {
75
+ [import_types.AdapterType.TRADER_JOE_ROUTER]: {
76
76
  310: import_conctructorAbiPatterns.BASIC_ADAPTER_ABI
77
77
  },
78
78
  [import_types.AdapterType.UNISWAP_V2_ROUTER]: {
@@ -93,7 +93,7 @@ function createAdapter(options, data, strict) {
93
93
  return new import_contracts.PendleRouterAdapterContract(options, data);
94
94
  case "ADAPTER::STAKING_REWARDS":
95
95
  return new import_contracts.StakingRewardsAdapterContract(options, data);
96
- case "ADAPTER::TRADERJOE_ROUTER":
96
+ case "ADAPTER::TRADER_JOE_ROUTER":
97
97
  return new import_contracts.TraderJoeRouterAdapterContract(options, data);
98
98
  case "ADAPTER::UNISWAP_V2_ROUTER":
99
99
  return new import_contracts.UniswapV2AdapterContract(options, data);
@@ -59,7 +59,7 @@ var AdapterType = /* @__PURE__ */ ((AdapterType2) => {
59
59
  AdapterType2["MIDAS_REDEMPTION_VAULT"] = "MIDAS_REDEMPTION_VAULT";
60
60
  AdapterType2["PENDLE_ROUTER"] = "PENDLE_ROUTER";
61
61
  AdapterType2["STAKING_REWARDS"] = "STAKING_REWARDS";
62
- AdapterType2["TRADERJOE_ROUTER"] = "TRADERJOE_ROUTER";
62
+ AdapterType2["TRADER_JOE_ROUTER"] = "TRADER_JOE_ROUTER";
63
63
  AdapterType2["UNISWAP_V2_ROUTER"] = "UNISWAP_V2_ROUTER";
64
64
  AdapterType2["UNISWAP_V3_ROUTER"] = "UNISWAP_V3_ROUTER";
65
65
  AdapterType2["UNISWAP_V4_GATEWAY"] = "UNISWAP_V4_GATEWAY";
@@ -0,0 +1,266 @@
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 ApyPlugin_exports = {};
20
+ __export(ApyPlugin_exports, {
21
+ ApyPlugin: () => ApyPlugin
22
+ });
23
+ module.exports = __toCommonJS(ApyPlugin_exports);
24
+ var import_marketCompressor = require("../../abi/compressors/marketCompressor.js");
25
+ var import_extra_apy = require("../../rewards/rewards/extra-apy.js");
26
+ var import_sdk = require("../../sdk/index.js");
27
+ var import_formatter = require("../../sdk/utils/formatter.js");
28
+ var import_hex = require("../../sdk/utils/hex.js");
29
+ var import_apy_cache = require("./apy-cache.js");
30
+ var import_apy_parser = require("./apy-parser.js");
31
+ var import_constants = require("./constants.js");
32
+ var import_pool_apy_utils = require("./pool-apy-utils.js");
33
+ const MAP_LABEL = "pools7DAgo";
34
+ class ApyPlugin extends import_sdk.BasePlugin {
35
+ #apyUrl;
36
+ #cacheTtlMs;
37
+ #pools7DAgo;
38
+ #apySnapshot;
39
+ constructor(loadOnAttach = false, options) {
40
+ super(loadOnAttach);
41
+ this.#apyUrl = options?.apyUrl ?? import_constants.APY_STATE_CACHE_URL;
42
+ this.#cacheTtlMs = options?.cacheTtlMs ?? import_constants.DEFAULT_APY_INTERVAL_MS;
43
+ }
44
+ // ---------------------------------------------------------------------------
45
+ // Load — single entry point for all data (on-chain + state-cache)
46
+ // ---------------------------------------------------------------------------
47
+ async load(force, loadOptions) {
48
+ if (!force && this.loaded) {
49
+ return this.state;
50
+ }
51
+ const targetBlock = this.sdk.currentBlock - import_sdk.BLOCKS_PER_WEEK_BY_NETWORK[this.sdk.networkType];
52
+ const [marketCompressorAddress] = this.sdk.addressProvider.mustGetLatest(
53
+ import_sdk.AP_MARKET_COMPRESSOR,
54
+ import_sdk.VERSION_RANGE_310
55
+ );
56
+ this.#logger?.debug(
57
+ `loading pools 7d ago with market compressor ${marketCompressorAddress}`
58
+ );
59
+ const markets = this.sdk.marketRegister.markets;
60
+ const shouldLoadPools7DAgo = !this.#pools7DAgo || !!loadOptions?.loadPools7DAgo;
61
+ const [multicallResp, apySnapshot] = await Promise.all([
62
+ shouldLoadPools7DAgo ? this.client.multicall({
63
+ allowFailure: true,
64
+ contracts: markets.map(
65
+ (m) => ({
66
+ address: marketCompressorAddress,
67
+ abi: import_marketCompressor.marketCompressorAbi,
68
+ functionName: "getPoolState",
69
+ args: [m.pool.pool.address]
70
+ })
71
+ ),
72
+ blockNumber: targetBlock > 0n ? targetBlock : void 0,
73
+ batchSize: 0
74
+ }) : null,
75
+ this.#fetchApy()
76
+ ]);
77
+ if (multicallResp !== null) {
78
+ this.#pools7DAgo = new import_sdk.AddressMap(void 0, MAP_LABEL);
79
+ multicallResp.forEach((r, index) => {
80
+ const m = markets[index];
81
+ const cfg = m.configurator.address;
82
+ const pool = m.pool.pool.address;
83
+ if (r.status === "success") {
84
+ this.#pools7DAgo?.upsert(m.pool.pool.address, {
85
+ dieselRate: r.result.dieselRate,
86
+ pool
87
+ });
88
+ } else {
89
+ this.#logger?.error(
90
+ `failed to load pools 7d ago for market configurator ${this.labelAddress(cfg)} and pool ${this.labelAddress(pool)}: ${r.error}`
91
+ );
92
+ }
93
+ });
94
+ }
95
+ if (apySnapshot) {
96
+ this.#apySnapshot = apySnapshot;
97
+ }
98
+ return this.state;
99
+ }
100
+ get loaded() {
101
+ return !!this.#pools7DAgo && !!this.#apySnapshot;
102
+ }
103
+ // ---------------------------------------------------------------------------
104
+ // Accessors
105
+ // ---------------------------------------------------------------------------
106
+ /**
107
+ * @throws if plugin is not loaded
108
+ */
109
+ get pools7DAgo() {
110
+ if (!this.#pools7DAgo) {
111
+ throw new Error("apy plugin not loaded");
112
+ }
113
+ return this.#pools7DAgo;
114
+ }
115
+ /**
116
+ * @throws if plugin is not loaded
117
+ */
118
+ get apySnapshot() {
119
+ if (!this.#apySnapshot) {
120
+ throw new Error("apy plugin not loaded");
121
+ }
122
+ return this.#apySnapshot;
123
+ }
124
+ // ---------------------------------------------------------------------------
125
+ // Aggregated APY / points
126
+ // ---------------------------------------------------------------------------
127
+ /**
128
+ * Computes per-pool APY (current + 7d-ago) and points for all markets.
129
+ *
130
+ * @throws if plugin is not loaded
131
+ */
132
+ getPoolsAPY() {
133
+ if (!this.loaded) {
134
+ throw new Error("apy plugin not loaded");
135
+ }
136
+ const markets = this.sdk.marketRegister.markets;
137
+ const { apy } = this.apySnapshot;
138
+ const totalTokenBalances = {};
139
+ const poolPointsBase = apy.poolRewardsList && Object.keys(apy.poolRewardsList).length > 0 ? import_extra_apy.PoolPointsAPI.getPointsByPool({
140
+ poolRewards: apy.poolRewardsList,
141
+ totalTokenBalances,
142
+ pools: markets,
143
+ tokensList: this.sdk.tokensMeta
144
+ }) : {};
145
+ const data = {};
146
+ const data7DAgo = {};
147
+ const points = {};
148
+ for (const market of markets) {
149
+ const pool = market.pool.pool;
150
+ const poolAddr = pool.address.toLowerCase();
151
+ const underlyingLc = pool.underlying.toLowerCase();
152
+ const depositAPY = (0, import_formatter.rayToNumber)(pool.supplyRate) * Number(import_sdk.PERCENTAGE_DECIMALS);
153
+ const underlyingAPY = apy.apyList?.[underlyingLc] ?? apy.apyList?.[pool.underlying] ?? 0;
154
+ const lookupAddresses = this.#getExtraAPYLookupAddresses(poolAddr);
155
+ const extraAPY = (0, import_pool_apy_utils.getPoolExtraAPY)(lookupAddresses, apy.poolExtraAPYList);
156
+ const currentExternalList = apy.poolExternalAPYList?.[poolAddr];
157
+ const poolAPY = (0, import_pool_apy_utils.calculatePoolFullAPY)({
158
+ depositAPY,
159
+ underlyingAPY,
160
+ extraAPY,
161
+ currentExternalList
162
+ });
163
+ data[poolAddr] = poolAPY;
164
+ const pool7DAgo = this.#pools7DAgo?.get(poolAddr);
165
+ const supplyAPY7DAgo = pool7DAgo ? (0, import_pool_apy_utils.calculateSupplyApy7d)(
166
+ pool.dieselRate,
167
+ pool.supplyRate,
168
+ pool7DAgo.dieselRate
169
+ ) : void 0;
170
+ data7DAgo[poolAddr] = (0, import_pool_apy_utils.calculatePoolFullAPY7DAgo)({
171
+ supplyAPY7DAgo,
172
+ depositAPY,
173
+ poolAPY
174
+ });
175
+ const poolTokenMeta = this.sdk.tokensMeta.get(pool.underlying);
176
+ points[poolAddr] = (0, import_pool_apy_utils.calculatePoolPoints)({
177
+ poolTokenSymbol: poolTokenMeta?.symbol,
178
+ points: poolPointsBase[poolAddr],
179
+ tokensList: this.sdk.tokensMeta
180
+ });
181
+ }
182
+ return { data, data7DAgo, pointsBase: poolPointsBase, points };
183
+ }
184
+ // ---------------------------------------------------------------------------
185
+ // Plugin lifecycle
186
+ // ---------------------------------------------------------------------------
187
+ async syncState() {
188
+ await this.load();
189
+ }
190
+ stateHuman(_) {
191
+ return this.pools7DAgo.values().flatMap((p) => ({
192
+ address: p.pool,
193
+ version: this.version,
194
+ dieselRate: p.dieselRate
195
+ }));
196
+ }
197
+ get state() {
198
+ return {
199
+ pools7DAgo: this.pools7DAgo.asRecord(),
200
+ apySnapshot: this.apySnapshot
201
+ };
202
+ }
203
+ hydrate(state) {
204
+ this.#pools7DAgo = new import_sdk.AddressMap(
205
+ Object.entries(state.pools7DAgo),
206
+ MAP_LABEL
207
+ );
208
+ this.#apySnapshot = state.apySnapshot;
209
+ }
210
+ // ---------------------------------------------------------------------------
211
+ // Internal
212
+ // ---------------------------------------------------------------------------
213
+ async #fetchApy() {
214
+ try {
215
+ const cache = import_apy_cache.ApyOutputCache.get(
216
+ this.#apyUrl,
217
+ this.#cacheTtlMs,
218
+ this.#logger
219
+ );
220
+ const output = await cache.fetch();
221
+ if (!output) return void 0;
222
+ const chainData = output.chains[this.sdk.chainId];
223
+ if (!chainData) {
224
+ this.#logger?.debug(
225
+ `apy state-cache: no data for chainId ${this.sdk.chainId}`
226
+ );
227
+ return void 0;
228
+ }
229
+ const apy = (0, import_apy_parser.parseNetworkApy)(chainData.tokens, chainData.pools);
230
+ if (!apy) return void 0;
231
+ return {
232
+ apy,
233
+ gearStats: (0, import_apy_parser.parseGearStats)(output),
234
+ timestamp: output.timestamp
235
+ };
236
+ } catch (e) {
237
+ this.#logger?.error(e, "failed to fetch apy state-cache");
238
+ return void 0;
239
+ }
240
+ }
241
+ /**
242
+ * Collects addresses to look up in poolExtraAPYList for a given pool.
243
+ * Includes pool address (= diesel token) + any staked diesel token
244
+ * outputs discovered from zappers.
245
+ */
246
+ #getExtraAPYLookupAddresses(poolAddr) {
247
+ const addresses = [poolAddr];
248
+ try {
249
+ const zappers = this.sdk.marketRegister.poolZappers(poolAddr);
250
+ for (const z of zappers) {
251
+ if (!(0, import_hex.hexEq)(z.tokenOut.addr, poolAddr)) {
252
+ addresses.push(z.tokenOut.addr);
253
+ }
254
+ }
255
+ } catch {
256
+ }
257
+ return addresses;
258
+ }
259
+ get #logger() {
260
+ return this.logger;
261
+ }
262
+ }
263
+ // Annotate the CommonJS export names for ESM import in node:
264
+ 0 && (module.exports = {
265
+ ApyPlugin
266
+ });
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var apy_cache_exports = {};
30
+ __export(apy_cache_exports, {
31
+ ApyOutputCache: () => ApyOutputCache
32
+ });
33
+ module.exports = __toCommonJS(apy_cache_exports);
34
+ var import_axios = __toESM(require("axios"));
35
+ class ApyOutputCache {
36
+ static #instances = /* @__PURE__ */ new Map();
37
+ #url;
38
+ #ttlMs;
39
+ #cache;
40
+ #pending;
41
+ #logger;
42
+ constructor(url, ttlMs, logger) {
43
+ this.#url = url;
44
+ this.#ttlMs = ttlMs;
45
+ this.#logger = logger;
46
+ }
47
+ /**
48
+ * Returns a shared cache instance for the given URL.
49
+ * The same instance is reused across all callers with identical URL.
50
+ */
51
+ static get(url, ttlMs, logger) {
52
+ let instance = ApyOutputCache.#instances.get(url);
53
+ if (!instance) {
54
+ instance = new ApyOutputCache(url, ttlMs, logger);
55
+ ApyOutputCache.#instances.set(url, instance);
56
+ }
57
+ if (logger) {
58
+ instance.#logger = logger;
59
+ }
60
+ return instance;
61
+ }
62
+ /**
63
+ * Returns cached Output if fresh, otherwise fetches from the network.
64
+ * Concurrent calls are de-duplicated.
65
+ */
66
+ async fetch() {
67
+ if (this.#cache && Date.now() - this.#cache.fetchedAt < this.#ttlMs) {
68
+ this.#logger?.debug("apy cache: TTL still valid, returning cached data");
69
+ return this.#cache.data;
70
+ }
71
+ if (this.#pending) {
72
+ this.#logger?.debug("apy cache: request in flight, waiting");
73
+ return this.#pending;
74
+ }
75
+ this.#pending = this.#doFetch();
76
+ try {
77
+ return await this.#pending;
78
+ } finally {
79
+ this.#pending = void 0;
80
+ }
81
+ }
82
+ async #doFetch() {
83
+ try {
84
+ const headers = {};
85
+ if (this.#cache?.etag) {
86
+ headers["If-None-Match"] = this.#cache.etag;
87
+ }
88
+ const response = await import_axios.default.get(this.#url, {
89
+ headers,
90
+ validateStatus: (status) => status === 200 || status === 304
91
+ });
92
+ if (response.status === 304 && this.#cache) {
93
+ this.#cache.fetchedAt = Date.now();
94
+ this.#logger?.debug("apy cache: 304 Not Modified, extended TTL");
95
+ return this.#cache.data;
96
+ }
97
+ const etag = response.headers["etag"];
98
+ this.#cache = {
99
+ data: response.data,
100
+ etag,
101
+ fetchedAt: Date.now()
102
+ };
103
+ this.#logger?.debug(
104
+ `apy cache: fetched fresh data (timestamp: ${response.data.timestamp})`
105
+ );
106
+ return response.data;
107
+ } catch (e) {
108
+ this.#logger?.error(e, "apy cache: fetch failed");
109
+ return this.#cache?.data;
110
+ }
111
+ }
112
+ /** Evicts all cached entries. Mainly useful for tests. */
113
+ static clearAll() {
114
+ ApyOutputCache.#instances.clear();
115
+ }
116
+ }
117
+ // Annotate the CommonJS export names for ESM import in node:
118
+ 0 && (module.exports = {
119
+ ApyOutputCache
120
+ });