@metamask-previews/earn-controller 12.2.6-preview-4f4c98e → 12.2.6-preview-5b293ee50

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 (53) hide show
  1. package/CHANGELOG.md +0 -4
  2. package/dist/EarnController-method-action-types.cjs +7 -0
  3. package/dist/EarnController-method-action-types.cjs.map +1 -0
  4. package/dist/{EarnController-method-action-types.d.ts → EarnController-method-action-types.d.cts} +2 -2
  5. package/dist/EarnController-method-action-types.d.cts.map +1 -0
  6. package/dist/EarnController-method-action-types.d.mts +263 -0
  7. package/dist/EarnController-method-action-types.d.mts.map +1 -0
  8. package/dist/{EarnController-method-action-types.js → EarnController-method-action-types.mjs} +1 -1
  9. package/dist/EarnController-method-action-types.mjs.map +1 -0
  10. package/dist/EarnController.cjs +778 -0
  11. package/dist/EarnController.cjs.map +1 -0
  12. package/dist/{EarnController.d.ts → EarnController.d.cts} +12 -12
  13. package/dist/EarnController.d.cts.map +1 -0
  14. package/dist/EarnController.d.mts +365 -0
  15. package/dist/EarnController.d.mts.map +1 -0
  16. package/dist/{EarnController.js → EarnController.mjs} +7 -7
  17. package/dist/EarnController.mjs.map +1 -0
  18. package/dist/index.cjs +33 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/{index.d.ts → index.d.cts} +6 -6
  21. package/dist/index.d.cts.map +1 -0
  22. package/dist/index.d.mts +6 -0
  23. package/dist/index.d.mts.map +1 -0
  24. package/dist/{index.js → index.mjs} +4 -4
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/selectors.cjs +121 -0
  27. package/dist/selectors.cjs.map +1 -0
  28. package/dist/{selectors.d.ts → selectors.d.cts} +117 -117
  29. package/dist/selectors.d.cts.map +1 -0
  30. package/dist/selectors.d.mts +1518 -0
  31. package/dist/selectors.d.mts.map +1 -0
  32. package/dist/{selectors.js → selectors.mjs} +2 -2
  33. package/dist/selectors.mjs.map +1 -0
  34. package/dist/types.cjs +3 -0
  35. package/dist/types.cjs.map +1 -0
  36. package/dist/{types.d.ts → types.d.cts} +1 -1
  37. package/dist/types.d.cts.map +1 -0
  38. package/dist/types.d.mts +21 -0
  39. package/dist/types.d.mts.map +1 -0
  40. package/dist/types.mjs +2 -0
  41. package/dist/types.mjs.map +1 -0
  42. package/package.json +16 -12
  43. package/dist/EarnController-method-action-types.d.ts.map +0 -1
  44. package/dist/EarnController-method-action-types.js.map +0 -1
  45. package/dist/EarnController.d.ts.map +0 -1
  46. package/dist/EarnController.js.map +0 -1
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index.js.map +0 -1
  49. package/dist/selectors.d.ts.map +0 -1
  50. package/dist/selectors.js.map +0 -1
  51. package/dist/types.d.ts.map +0 -1
  52. package/dist/types.js +0 -2
  53. package/dist/types.js.map +0 -1
@@ -0,0 +1,778 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _EarnController_instances, _EarnController_earnSDK, _EarnController_initPromise, _EarnController_lastRefreshedAddress, _EarnController_earnApiService, _EarnController_addTransactionFn, _EarnController_supportedPooledStakingChains, _EarnController_env, _EarnController_refreshEarnPortfolio, _EarnController_initializeSDK, _EarnController_getSelectedNetworkClientId, _EarnController_getSelectedEvmAccount, _EarnController_getSelectedEvmAccountAddress, _EarnController_refreshEarnPortfolioOnAccountReady;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.EarnController = exports.getDefaultEarnControllerState = exports.DEFAULT_TRON_STAKING_STATE = exports.DEFAULT_POOLED_STAKING_CHAIN_STATE = exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = exports.DEFAULT_LENDING_POSITION = exports.DEFAULT_LENDING_MARKET = exports.controllerName = void 0;
16
+ const providers_1 = require("@ethersproject/providers");
17
+ const base_controller_1 = require("@metamask/base-controller");
18
+ const controller_utils_1 = require("@metamask/controller-utils");
19
+ const keyring_api_1 = require("@metamask/keyring-api");
20
+ const stake_sdk_1 = require("@metamask/stake-sdk");
21
+ const transaction_controller_1 = require("@metamask/transaction-controller");
22
+ exports.controllerName = 'EarnController';
23
+ const stakingTransactionTypes = new Set([
24
+ transaction_controller_1.TransactionType.stakingDeposit,
25
+ transaction_controller_1.TransactionType.stakingUnstake,
26
+ transaction_controller_1.TransactionType.stakingClaim,
27
+ ]);
28
+ const lendingTransactionTypes = new Set([
29
+ transaction_controller_1.TransactionType.lendingDeposit,
30
+ transaction_controller_1.TransactionType.lendingWithdraw,
31
+ ]);
32
+ /**
33
+ * Metadata for the EarnController.
34
+ */
35
+ const earnControllerMetadata = {
36
+ pooled_staking: {
37
+ includeInStateLogs: true,
38
+ persist: true,
39
+ includeInDebugSnapshot: false,
40
+ usedInUi: true,
41
+ },
42
+ lending: {
43
+ includeInStateLogs: true,
44
+ persist: true,
45
+ includeInDebugSnapshot: false,
46
+ usedInUi: true,
47
+ },
48
+ tron_staking: {
49
+ includeInStateLogs: true,
50
+ persist: true,
51
+ includeInDebugSnapshot: false,
52
+ usedInUi: true,
53
+ },
54
+ lastUpdated: {
55
+ includeInStateLogs: true,
56
+ persist: false,
57
+ includeInDebugSnapshot: true,
58
+ usedInUi: false,
59
+ },
60
+ };
61
+ // === Default State ===
62
+ exports.DEFAULT_LENDING_MARKET = {
63
+ id: '',
64
+ chainId: 0,
65
+ protocol: '',
66
+ name: '',
67
+ address: '',
68
+ tvlUnderlying: '0',
69
+ netSupplyRate: 0,
70
+ totalSupplyRate: 0,
71
+ underlying: {
72
+ address: '',
73
+ chainId: 0,
74
+ },
75
+ outputToken: {
76
+ address: '',
77
+ chainId: 0,
78
+ },
79
+ rewards: [
80
+ {
81
+ token: {
82
+ address: '',
83
+ chainId: 0,
84
+ },
85
+ rate: 0,
86
+ },
87
+ ],
88
+ };
89
+ exports.DEFAULT_LENDING_POSITION = {
90
+ id: '',
91
+ chainId: 0,
92
+ assets: '0',
93
+ marketId: '',
94
+ marketAddress: '',
95
+ protocol: '',
96
+ };
97
+ exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
98
+ oneDay: '0',
99
+ oneWeek: '0',
100
+ oneMonth: '0',
101
+ threeMonths: '0',
102
+ sixMonths: '0',
103
+ oneYear: '0',
104
+ };
105
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE = {
106
+ pooledStakes: {
107
+ account: '',
108
+ lifetimeRewards: '0',
109
+ assets: '0',
110
+ exitRequests: [],
111
+ },
112
+ exchangeRate: '1',
113
+ vaultMetadata: {
114
+ apy: '0',
115
+ capacity: '0',
116
+ feePercent: 0,
117
+ totalAssets: '0',
118
+ vaultAddress: '0x0000000000000000000000000000000000000000',
119
+ },
120
+ vaultDailyApys: [],
121
+ vaultApyAverages: exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES,
122
+ };
123
+ exports.DEFAULT_TRON_STAKING_STATE = null;
124
+ /**
125
+ * Gets the default state for the EarnController.
126
+ *
127
+ * @returns The default EarnController state.
128
+ */
129
+ function getDefaultEarnControllerState() {
130
+ return {
131
+ pooled_staking: {
132
+ isEligible: false,
133
+ },
134
+ lending: {
135
+ markets: [exports.DEFAULT_LENDING_MARKET],
136
+ positions: [exports.DEFAULT_LENDING_POSITION],
137
+ isEligible: false,
138
+ },
139
+ tron_staking: exports.DEFAULT_TRON_STAKING_STATE,
140
+ lastUpdated: 0,
141
+ };
142
+ }
143
+ exports.getDefaultEarnControllerState = getDefaultEarnControllerState;
144
+ // === MESSENGER ===
145
+ const MESSENGER_EXPOSED_METHODS = [
146
+ 'refreshPooledStakes',
147
+ 'refreshEarnEligibility',
148
+ 'refreshPooledStakingVaultMetadata',
149
+ 'refreshPooledStakingVaultDailyApys',
150
+ 'refreshPooledStakingVaultApyAverages',
151
+ 'refreshPooledStakingData',
152
+ 'refreshLendingMarkets',
153
+ 'refreshLendingPositions',
154
+ 'refreshLendingData',
155
+ 'refreshTronStakingApy',
156
+ 'getTronStakingApy',
157
+ 'getLendingPositionHistory',
158
+ 'getLendingMarketDailyApysAndAverages',
159
+ 'executeLendingDeposit',
160
+ 'executeLendingWithdraw',
161
+ 'executeLendingTokenApprove',
162
+ 'getLendingTokenAllowance',
163
+ 'getLendingTokenMaxWithdraw',
164
+ 'getLendingTokenMaxDeposit',
165
+ ];
166
+ // === CONTROLLER DEFINITION ===
167
+ /**
168
+ * EarnController manages DeFi earning opportunities across different protocols and chains.
169
+ */
170
+ class EarnController extends base_controller_1.BaseController {
171
+ constructor({ messenger, state = {}, addTransactionFn, env = stake_sdk_1.EarnEnvironments.PROD, }) {
172
+ super({
173
+ name: exports.controllerName,
174
+ metadata: earnControllerMetadata,
175
+ messenger,
176
+ state: {
177
+ ...getDefaultEarnControllerState(),
178
+ ...state,
179
+ },
180
+ });
181
+ _EarnController_instances.add(this);
182
+ _EarnController_earnSDK.set(this, null);
183
+ _EarnController_initPromise.set(this, null);
184
+ _EarnController_lastRefreshedAddress.set(this, void 0);
185
+ _EarnController_earnApiService.set(this, void 0);
186
+ _EarnController_addTransactionFn.set(this, void 0);
187
+ _EarnController_supportedPooledStakingChains.set(this, void 0);
188
+ _EarnController_env.set(this, void 0);
189
+ __classPrivateFieldSet(this, _EarnController_env, env, "f");
190
+ __classPrivateFieldSet(this, _EarnController_earnApiService, new stake_sdk_1.EarnApiService(__classPrivateFieldGet(this, _EarnController_env, "f")), "f");
191
+ // temporary array of supported chains
192
+ // TODO: remove this once we export a supported chains list from the sdk
193
+ // from sdk or api to get lending and pooled staking chains
194
+ //
195
+ // Only eagerly prefetch Ethereum on startup/network-change; Hoodi
196
+ // (testnet) is still fully supported on-demand via explicit chainId
197
+ // calls (e.g. refreshPooledStakes({ chainId: ChainId.HOODI })), we just
198
+ // don't unconditionally fetch it for every user on every unlock.
199
+ __classPrivateFieldSet(this, _EarnController_supportedPooledStakingChains, [stake_sdk_1.ChainId.ETHEREUM], "f");
200
+ __classPrivateFieldSet(this, _EarnController_addTransactionFn, addTransactionFn, "f");
201
+ // Listen for network changes
202
+ this.messenger.subscribe('NetworkController:networkDidChange', (networkControllerState) => {
203
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this, networkControllerState.selectedNetworkClientId).catch(console.error);
204
+ // refresh pooled staking data
205
+ this.refreshPooledStakingVaultMetadata().catch(console.error);
206
+ this.refreshPooledStakingVaultDailyApys().catch(console.error);
207
+ this.refreshPooledStakingVaultApyAverages().catch(console.error);
208
+ this.refreshPooledStakes().catch(console.error);
209
+ // refresh lending data for all chains
210
+ this.refreshLendingMarkets().catch(console.error);
211
+ this.refreshLendingPositions().catch(console.error);
212
+ });
213
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
214
+ // Listen for account group changes
215
+ this.messenger.subscribe('AccountTreeController:selectedAccountGroupChange', () => {
216
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
217
+ // Skip if this account group change didn't actually change the
218
+ // resolved address (e.g. it can fire again right after init()
219
+ // during startup hydration) - nothing new to fetch.
220
+ if (!address || address === __classPrivateFieldGet(this, _EarnController_lastRefreshedAddress, "f")) {
221
+ return;
222
+ }
223
+ __classPrivateFieldSet(this, _EarnController_lastRefreshedAddress, address, "f");
224
+ // TODO: temp solution, this will refresh lending eligibility also
225
+ // we could have a more general check, as what is happening is a compliance address check
226
+ this.refreshEarnEligibility({ address }).catch(console.error);
227
+ this.refreshPooledStakes({ address }).catch(console.error);
228
+ this.refreshLendingPositions({ address }).catch(console.error);
229
+ });
230
+ // Listen for confirmed staking transactions
231
+ this.messenger.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
232
+ /**
233
+ * When we speed up a transaction, we set the type as Retry and we lose
234
+ * information about type of transaction that is being set up, so we use
235
+ * original type to track that information.
236
+ */
237
+ const { type, originalType } = transactionMeta;
238
+ const isStakingTransaction = stakingTransactionTypes.has(type) ||
239
+ stakingTransactionTypes.has(originalType);
240
+ const isLendingTransaction = lendingTransactionTypes.has(type) ||
241
+ lendingTransactionTypes.has(originalType);
242
+ const sender = transactionMeta.txParams.from;
243
+ if (isStakingTransaction) {
244
+ this.refreshPooledStakes({ resetCache: true, address: sender }).catch(console.error);
245
+ }
246
+ if (isLendingTransaction) {
247
+ this.refreshLendingPositions({ address: sender }).catch(console.error);
248
+ }
249
+ });
250
+ }
251
+ async init() {
252
+ if (__classPrivateFieldGet(this, _EarnController_initPromise, "f")) {
253
+ return __classPrivateFieldGet(this, _EarnController_initPromise, "f");
254
+ }
255
+ __classPrivateFieldSet(this, _EarnController_initPromise, (async () => {
256
+ await __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this, __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedNetworkClientId).call(this));
257
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
258
+ if (address) {
259
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_refreshEarnPortfolio).call(this, address);
260
+ }
261
+ else {
262
+ // Account tree state is not yet available, so we defer the refresh to when it is.
263
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_refreshEarnPortfolioOnAccountReady).call(this);
264
+ }
265
+ })().catch((error) => {
266
+ __classPrivateFieldSet(this, _EarnController_initPromise, null, "f");
267
+ throw error;
268
+ }), "f");
269
+ return __classPrivateFieldGet(this, _EarnController_initPromise, "f");
270
+ }
271
+ /**
272
+ * Refreshes the pooled stakes data for the current account.
273
+ * Fetches updated stake information including lifetime rewards, assets, and exit requests
274
+ * from the staking API service and updates the state.
275
+ *
276
+ * @param options - Optional arguments
277
+ * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
278
+ * @param [options.address] - The address to refresh pooled stakes for (optional).
279
+ * @param [options.chainId] - The chain id to refresh pooled stakes for (optional).
280
+ * @returns A promise that resolves when the stakes data has been updated
281
+ */
282
+ async refreshPooledStakes({ resetCache = false, address, chainId = stake_sdk_1.ChainId.ETHEREUM, } = {}) {
283
+ const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
284
+ if (!addressToUse) {
285
+ return;
286
+ }
287
+ const chainIdToUse = (0, stake_sdk_1.isSupportedPooledStakingChain)(chainId)
288
+ ? chainId
289
+ : stake_sdk_1.ChainId.ETHEREUM;
290
+ const { accounts, exchangeRate } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakes([addressToUse], chainIdToUse, resetCache);
291
+ this.update((state) => {
292
+ const chainState = state.pooled_staking[chainIdToUse] ??
293
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
294
+ state.pooled_staking[chainIdToUse] = {
295
+ ...chainState,
296
+ pooledStakes: accounts[0],
297
+ exchangeRate,
298
+ };
299
+ });
300
+ }
301
+ /**
302
+ * Refreshes the earn eligibility status for the current account.
303
+ * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.
304
+ *
305
+ * Note: Pooled-staking and Lending used the same result since there isn't a need to split these up right now.
306
+ *
307
+ * @param options - Optional arguments
308
+ * @param [options.address] - Address to refresh earn eligibility for (optional).
309
+ * @returns A promise that resolves when the eligibility status has been updated
310
+ */
311
+ async refreshEarnEligibility({ address, } = {}) {
312
+ const addressToCheck = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
313
+ if (!addressToCheck) {
314
+ return;
315
+ }
316
+ const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakingEligibility([
317
+ addressToCheck,
318
+ ]);
319
+ this.update((state) => {
320
+ state.pooled_staking.isEligible = isEligible;
321
+ state.lending.isEligible = isEligible;
322
+ });
323
+ }
324
+ /**
325
+ * Refreshes pooled staking vault metadata for the current chain.
326
+ * Updates the vault metadata in the controller state including APY, capacity,
327
+ * fee percentage, total assets, and vault address.
328
+ *
329
+ * @param [chainId] - The chain id to refresh pooled staking vault metadata for (optional).
330
+ * @returns A promise that resolves when the vault metadata has been updated
331
+ */
332
+ async refreshPooledStakingVaultMetadata(chainId = stake_sdk_1.ChainId.ETHEREUM) {
333
+ const chainIdToUse = (0, stake_sdk_1.isSupportedPooledStakingChain)(chainId)
334
+ ? chainId
335
+ : stake_sdk_1.ChainId.ETHEREUM;
336
+ const vaultMetadata = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultData(chainIdToUse);
337
+ this.update((state) => {
338
+ const chainState = state.pooled_staking[chainIdToUse] ??
339
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
340
+ state.pooled_staking[chainIdToUse] = {
341
+ ...chainState,
342
+ vaultMetadata,
343
+ };
344
+ });
345
+ }
346
+ /**
347
+ * Refreshes pooled staking vault daily apys for the current chain.
348
+ * Updates the pooled staking vault daily apys controller state.
349
+ *
350
+ * @param [options] - The options for refreshing pooled staking vault daily apys.
351
+ * @param [options.chainId] - The chain id to refresh pooled staking vault daily apys for (defaults to Ethereum).
352
+ * @param [options.days] - The number of days to fetch pooled staking vault daily apys for (defaults to 365).
353
+ * @param [options.order] - The order in which to fetch pooled staking vault daily apys. Descending order fetches the latest N days (latest working backwards). Ascending order fetches the oldest N days (oldest working forwards) (defaults to 'desc').
354
+ * @returns A promise that resolves when the pooled staking vault daily apys have been updated.
355
+ */
356
+ async refreshPooledStakingVaultDailyApys({ chainId = stake_sdk_1.ChainId.ETHEREUM, days = 365, order = 'desc', } = {}) {
357
+ const chainIdToUse = (0, stake_sdk_1.isSupportedPooledStakingChain)(chainId)
358
+ ? chainId
359
+ : stake_sdk_1.ChainId.ETHEREUM;
360
+ const vaultDailyApys = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultDailyApys(chainIdToUse, days, order);
361
+ this.update((state) => {
362
+ const chainState = state.pooled_staking[chainIdToUse] ??
363
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
364
+ state.pooled_staking[chainIdToUse] = {
365
+ ...chainState,
366
+ vaultDailyApys,
367
+ };
368
+ });
369
+ }
370
+ /**
371
+ * Refreshes pooled staking vault apy averages for the current chain.
372
+ * Updates the pooled staking vault apy averages controller state.
373
+ *
374
+ * @param [chainId] - The chain id to refresh pooled staking vault apy averages for (optional).
375
+ * @returns A promise that resolves when the pooled staking vault apy averages have been updated.
376
+ */
377
+ async refreshPooledStakingVaultApyAverages(chainId = stake_sdk_1.ChainId.ETHEREUM) {
378
+ const chainIdToUse = (0, stake_sdk_1.isSupportedPooledStakingChain)(chainId)
379
+ ? chainId
380
+ : stake_sdk_1.ChainId.ETHEREUM;
381
+ const vaultApyAverages = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultApyAverages(chainIdToUse);
382
+ this.update((state) => {
383
+ const chainState = state.pooled_staking[chainIdToUse] ??
384
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
385
+ state.pooled_staking[chainIdToUse] = {
386
+ ...chainState,
387
+ vaultApyAverages,
388
+ };
389
+ });
390
+ }
391
+ /**
392
+ * Refreshes all pooled staking related data including stakes, eligibility, and vault data.
393
+ * This method allows partial success, meaning some data may update while other requests fail.
394
+ * All errors are collected and thrown as a single error message.
395
+ *
396
+ * @param options - Optional arguments
397
+ * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
398
+ * @param [options.address] - The address to refresh pooled stakes for (optional).
399
+ * @returns A promise that resolves when all possible data has been updated
400
+ * @throws {Error} If any of the refresh operations fail, with concatenated error messages
401
+ */
402
+ async refreshPooledStakingData({ resetCache, address, } = {}) {
403
+ const errors = [];
404
+ for (const chainId of __classPrivateFieldGet(this, _EarnController_supportedPooledStakingChains, "f")) {
405
+ await Promise.all([
406
+ this.refreshPooledStakes({ resetCache, address, chainId }).catch((error) => {
407
+ errors.push(error);
408
+ }),
409
+ this.refreshPooledStakingVaultMetadata(chainId).catch((error) => {
410
+ errors.push(error);
411
+ }),
412
+ this.refreshPooledStakingVaultDailyApys({ chainId }).catch((error) => {
413
+ errors.push(error);
414
+ }),
415
+ this.refreshPooledStakingVaultApyAverages(chainId).catch((error) => {
416
+ errors.push(error);
417
+ }),
418
+ ]);
419
+ }
420
+ if (errors.length > 0) {
421
+ throw new Error(`Failed to refresh some staking data: ${errors
422
+ .map((error) => error.message)
423
+ .join(', ')}`);
424
+ }
425
+ }
426
+ /**
427
+ * Refreshes the lending markets data for all chains.
428
+ * Updates the lending markets in the controller state.
429
+ *
430
+ * @returns A promise that resolves when the lending markets have been updated
431
+ */
432
+ async refreshLendingMarkets() {
433
+ const markets = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getMarkets();
434
+ this.update((state) => {
435
+ state.lending.markets = markets;
436
+ });
437
+ }
438
+ /**
439
+ * Refreshes the lending positions for the current account.
440
+ * Updates the lending positions in the controller state.
441
+ *
442
+ * @param options - Optional arguments
443
+ * @param [options.address] - The address to refresh lending positions for (optional).
444
+ * @returns A promise that resolves when the lending positions have been updated
445
+ */
446
+ async refreshLendingPositions({ address, } = {}) {
447
+ const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
448
+ if (!addressToUse) {
449
+ return;
450
+ }
451
+ // linter complaining about this not being a promise, but it is
452
+ // TODO: figure out why this is not seen as a promise
453
+ const positions = await Promise.resolve(__classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getPositions(addressToUse));
454
+ this.update((state) => {
455
+ state.lending.positions = positions.map((position) => ({
456
+ ...position,
457
+ marketId: position.market.id,
458
+ marketAddress: position.market.address,
459
+ protocol: position.market.protocol,
460
+ }));
461
+ });
462
+ }
463
+ /**
464
+ * Refreshes all lending related data including markets, positions, and eligibility.
465
+ * This method allows partial success, meaning some data may update while other requests fail.
466
+ * All errors are collected and thrown as a single error message.
467
+ *
468
+ * @returns A promise that resolves when all possible data has been updated
469
+ * @throws {Error} If any of the refresh operations fail, with concatenated error messages
470
+ */
471
+ async refreshLendingData() {
472
+ const errors = [];
473
+ await Promise.all([
474
+ this.refreshLendingMarkets().catch((error) => {
475
+ errors.push(error);
476
+ }),
477
+ this.refreshLendingPositions().catch((error) => {
478
+ errors.push(error);
479
+ }),
480
+ ]);
481
+ if (errors.length > 0) {
482
+ throw new Error(`Failed to refresh some lending data: ${errors
483
+ .map((error) => error.message)
484
+ .join(', ')}`);
485
+ }
486
+ }
487
+ /**
488
+ * Refreshes the APY for TRON staking.
489
+ * The consumer provides a fetcher function that returns the APY for TRON.
490
+ *
491
+ * @param apyFetcher - An async function that fetches and returns the APY as a decimal string.
492
+ * @returns A promise that resolves when the APY has been updated.
493
+ */
494
+ async refreshTronStakingApy(apyFetcher) {
495
+ const apy = await apyFetcher();
496
+ this.update((state) => {
497
+ state.tron_staking = {
498
+ apy,
499
+ lastUpdated: Date.now(),
500
+ };
501
+ });
502
+ }
503
+ /**
504
+ * Gets the TRON staking APY.
505
+ *
506
+ * @returns The APY for TRON staking, or undefined if not available.
507
+ */
508
+ getTronStakingApy() {
509
+ return this.state.tron_staking?.apy;
510
+ }
511
+ /**
512
+ * Gets the lending position history for the current account.
513
+ *
514
+ * @param options - Optional arguments
515
+ * @param [options.address] - The address to get lending position history for (optional).
516
+ * @param options.chainId - The chain id to get lending position history for.
517
+ * @param [options.positionId] - The position id to get lending position history for.
518
+ * @param [options.marketId] - The market id to get lending position history for.
519
+ * @param [options.marketAddress] - The market address to get lending position history for.
520
+ * @param [options.protocol] - The protocol to get lending position history for.
521
+ * @param [options.days] - The number of days to get lending position history for (optional).
522
+ * @returns A promise that resolves when the lending position history has been updated
523
+ */
524
+ getLendingPositionHistory({ address, chainId, positionId, marketId, marketAddress, protocol, days = 730, }) {
525
+ const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
526
+ if (!addressToUse || !(0, stake_sdk_1.isSupportedLendingChain)(chainId)) {
527
+ return [];
528
+ }
529
+ return __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getPositionHistory(addressToUse, chainId, protocol, marketId, marketAddress, positionId, days);
530
+ }
531
+ /**
532
+ * Gets the lending market daily apys and averages for the current chain.
533
+ *
534
+ * @param options - Optional arguments
535
+ * @param options.chainId - The chain id to get lending market daily apys and averages for.
536
+ * @param [options.protocol] - The protocol to get lending market daily apys and averages for.
537
+ * @param [options.marketId] - The market id to get lending market daily apys and averages for.
538
+ * @param [options.days] - The number of days to get lending market daily apys and averages for (optional).
539
+ * @returns A promise that resolves when the lending market daily apys and averages have been updated
540
+ */
541
+ getLendingMarketDailyApysAndAverages({ chainId, protocol, marketId, days = 365, }) {
542
+ if (!(0, stake_sdk_1.isSupportedLendingChain)(chainId)) {
543
+ return undefined;
544
+ }
545
+ return __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getHistoricMarketApys(chainId, protocol, marketId, days);
546
+ }
547
+ /**
548
+ * Executes a lending deposit transaction.
549
+ *
550
+ * @param options - The options for the lending deposit transaction.
551
+ * @param options.amount - The amount to deposit.
552
+ * @param options.chainId - The chain ID for the lending deposit transaction.
553
+ * @param options.protocol - The protocol of the lending market.
554
+ * @param options.underlyingTokenAddress - The address of the underlying token.
555
+ * @param options.gasOptions - The gas options for the transaction.
556
+ * @param options.gasOptions.gasLimit - The gas limit for the transaction.
557
+ * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
558
+ * @param options.txOptions - The transaction options for the transaction.
559
+ * @returns A promise that resolves to the transaction hash.
560
+ */
561
+ async executeLendingDeposit({ amount, chainId, protocol, underlyingTokenAddress, gasOptions, txOptions, }) {
562
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
563
+ if (!address) {
564
+ throw new Error('No EVM-compatible account address found');
565
+ }
566
+ const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeDepositTransactionData(amount, address, gasOptions);
567
+ if (!transactionData) {
568
+ throw new Error('Transaction data not found');
569
+ }
570
+ const selectedNetworkClientId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedNetworkClientId).call(this);
571
+ if (!selectedNetworkClientId) {
572
+ throw new Error('Selected network client id not found');
573
+ }
574
+ const gasLimit = !transactionData.gasLimit
575
+ ? undefined
576
+ : (0, controller_utils_1.toHex)(transactionData.gasLimit);
577
+ const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
578
+ ...transactionData,
579
+ value: transactionData.value.toString(),
580
+ chainId: (0, controller_utils_1.toHex)(chainId),
581
+ gasLimit,
582
+ }, {
583
+ ...txOptions,
584
+ networkClientId: selectedNetworkClientId,
585
+ isInternal: true,
586
+ });
587
+ return txHash;
588
+ }
589
+ /**
590
+ * Executes a lending withdraw transaction.
591
+ *
592
+ * @param options - The options for the lending withdraw transaction.
593
+ * @param options.amount - The amount to withdraw.
594
+ * @param options.chainId - The chain ID for the lending withdraw transaction.
595
+ * @param options.protocol - The protocol of the lending market.
596
+ * @param options.underlyingTokenAddress - The address of the underlying token.
597
+ * @param options.gasOptions - The gas options for the transaction.
598
+ * @param options.gasOptions.gasLimit - The gas limit for the transaction.
599
+ * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
600
+ * @param options.txOptions - The transaction options for the transaction.
601
+ * @returns A promise that resolves to the transaction hash.
602
+ */
603
+ async executeLendingWithdraw({ amount, chainId, protocol, underlyingTokenAddress, gasOptions, txOptions, }) {
604
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
605
+ if (!address) {
606
+ throw new Error('No EVM-compatible account address found');
607
+ }
608
+ const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeWithdrawTransactionData(amount, address, gasOptions);
609
+ if (!transactionData) {
610
+ throw new Error('Transaction data not found');
611
+ }
612
+ const selectedNetworkClientId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedNetworkClientId).call(this);
613
+ if (!selectedNetworkClientId) {
614
+ throw new Error('Selected network client id not found');
615
+ }
616
+ const gasLimit = !transactionData.gasLimit
617
+ ? undefined
618
+ : (0, controller_utils_1.toHex)(transactionData.gasLimit);
619
+ const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
620
+ ...transactionData,
621
+ value: transactionData.value.toString(),
622
+ chainId: (0, controller_utils_1.toHex)(chainId),
623
+ gasLimit,
624
+ }, {
625
+ ...txOptions,
626
+ networkClientId: selectedNetworkClientId,
627
+ isInternal: true,
628
+ });
629
+ return txHash;
630
+ }
631
+ /**
632
+ * Executes a lending token approve transaction.
633
+ *
634
+ * @param options - The options for the lending token approve transaction.
635
+ * @param options.amount - The amount to approve.
636
+ * @param options.chainId - The chain ID for the lending token approve transaction.
637
+ * @param options.protocol - The protocol of the lending market.
638
+ * @param options.underlyingTokenAddress - The address of the underlying token.
639
+ * @param options.gasOptions - The gas options for the transaction.
640
+ * @param options.gasOptions.gasLimit - The gas limit for the transaction.
641
+ * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
642
+ * @param options.txOptions - The transaction options for the transaction.
643
+ * @returns A promise that resolves to the transaction hash.
644
+ */
645
+ async executeLendingTokenApprove({ protocol, amount, chainId, underlyingTokenAddress, gasOptions, txOptions, }) {
646
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
647
+ if (!address) {
648
+ throw new Error('No EVM-compatible account address found');
649
+ }
650
+ const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeUnderlyingTokenApproveTransactionData(amount, address, gasOptions);
651
+ if (!transactionData) {
652
+ throw new Error('Transaction data not found');
653
+ }
654
+ const selectedNetworkClientId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedNetworkClientId).call(this);
655
+ if (!selectedNetworkClientId) {
656
+ throw new Error('Selected network client id not found');
657
+ }
658
+ const gasLimit = !transactionData.gasLimit
659
+ ? undefined
660
+ : (0, controller_utils_1.toHex)(transactionData.gasLimit);
661
+ const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
662
+ ...transactionData,
663
+ value: transactionData.value.toString(),
664
+ chainId: (0, controller_utils_1.toHex)(chainId),
665
+ gasLimit,
666
+ }, {
667
+ ...txOptions,
668
+ networkClientId: selectedNetworkClientId,
669
+ isInternal: true,
670
+ });
671
+ return txHash;
672
+ }
673
+ /**
674
+ * Gets the allowance for a lending token.
675
+ *
676
+ * @param protocol - The protocol of the lending market.
677
+ * @param underlyingTokenAddress - The address of the underlying token.
678
+ * @returns A promise that resolves to the allowance.
679
+ */
680
+ async getLendingTokenAllowance(protocol, underlyingTokenAddress) {
681
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
682
+ if (!address) {
683
+ return undefined;
684
+ }
685
+ const allowance = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.underlyingTokenAllowance(address);
686
+ return allowance;
687
+ }
688
+ /**
689
+ * Gets the maximum withdraw amount for a lending token's output token or shares if no output token.
690
+ *
691
+ * @param protocol - The protocol of the lending market.
692
+ * @param underlyingTokenAddress - The address of the underlying token.
693
+ * @returns A promise that resolves to the maximum withdraw amount.
694
+ */
695
+ async getLendingTokenMaxWithdraw(protocol, underlyingTokenAddress) {
696
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
697
+ if (!address) {
698
+ return undefined;
699
+ }
700
+ const maxWithdraw = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.maxWithdraw(address);
701
+ return maxWithdraw;
702
+ }
703
+ /**
704
+ * Gets the maximum deposit amount for a lending token.
705
+ *
706
+ * @param protocol - The protocol of the lending market.
707
+ * @param underlyingTokenAddress - The address of the underlying token.
708
+ * @returns A promise that resolves to the maximum deposit amount.
709
+ */
710
+ async getLendingTokenMaxDeposit(protocol, underlyingTokenAddress) {
711
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
712
+ if (!address) {
713
+ return undefined;
714
+ }
715
+ const maxDeposit = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.maxDeposit(address);
716
+ return maxDeposit;
717
+ }
718
+ }
719
+ exports.EarnController = EarnController;
720
+ _EarnController_earnSDK = new WeakMap(), _EarnController_initPromise = new WeakMap(), _EarnController_lastRefreshedAddress = new WeakMap(), _EarnController_earnApiService = new WeakMap(), _EarnController_addTransactionFn = new WeakMap(), _EarnController_supportedPooledStakingChains = new WeakMap(), _EarnController_env = new WeakMap(), _EarnController_instances = new WeakSet(), _EarnController_refreshEarnPortfolio = function _EarnController_refreshEarnPortfolio(address) {
721
+ __classPrivateFieldSet(this, _EarnController_lastRefreshedAddress, address, "f");
722
+ this.refreshEarnEligibility({ address }).catch(console.error);
723
+ this.refreshPooledStakingData({ address }).catch(console.error);
724
+ this.refreshLendingData().catch(console.error);
725
+ }, _EarnController_initializeSDK =
726
+ /**
727
+ * Initializes the Earn SDK.
728
+ *
729
+ * @param networkClientId - The network client id to initialize the Earn SDK for.
730
+ */
731
+ async function _EarnController_initializeSDK(networkClientId) {
732
+ const networkClient = this.messenger.call('NetworkController:getNetworkClientById', networkClientId);
733
+ if (!networkClient?.provider) {
734
+ __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
735
+ return;
736
+ }
737
+ const provider = new providers_1.Web3Provider(networkClient.provider);
738
+ const { chainId } = networkClient.configuration;
739
+ // Initialize appropriate contracts based on chainId
740
+ const config = {
741
+ chainId: (0, controller_utils_1.convertHexToDecimal)(chainId),
742
+ env: __classPrivateFieldGet(this, _EarnController_env, "f"),
743
+ };
744
+ try {
745
+ __classPrivateFieldSet(this, _EarnController_earnSDK, await stake_sdk_1.EarnSdk.create(provider, config), "f");
746
+ }
747
+ catch (error) {
748
+ __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
749
+ // Only log unexpected errors, not unsupported chain errors
750
+ if (!(error instanceof Error &&
751
+ error.message.includes('Unsupported chainId'))) {
752
+ console.error('Earn SDK initialization failed:', error);
753
+ }
754
+ }
755
+ }, _EarnController_getSelectedNetworkClientId = function _EarnController_getSelectedNetworkClientId() {
756
+ return this.messenger.call('NetworkController:getState')
757
+ .selectedNetworkClientId;
758
+ }, _EarnController_getSelectedEvmAccount = function _EarnController_getSelectedEvmAccount() {
759
+ return this.messenger
760
+ .call('AccountTreeController:getAccountsFromSelectedAccountGroup')
761
+ .find((account) => (0, keyring_api_1.isEvmAccountType)(account.type));
762
+ }, _EarnController_getSelectedEvmAccountAddress = function _EarnController_getSelectedEvmAccountAddress() {
763
+ return __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccount).call(this)?.address;
764
+ }, _EarnController_refreshEarnPortfolioOnAccountReady = function _EarnController_refreshEarnPortfolioOnAccountReady() {
765
+ const handler = ({ selectedAccountGroup, }) => {
766
+ if (!selectedAccountGroup) {
767
+ return;
768
+ }
769
+ const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getSelectedEvmAccountAddress).call(this);
770
+ if (!address) {
771
+ return;
772
+ }
773
+ this.messenger.unsubscribe('AccountTreeController:stateChange', handler);
774
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_refreshEarnPortfolio).call(this, address);
775
+ };
776
+ this.messenger.subscribe('AccountTreeController:stateChange', handler);
777
+ };
778
+ //# sourceMappingURL=EarnController.cjs.map