@metamask-previews/earn-controller 0.14.0-preview-37f78da → 0.14.0-preview-d20538b

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.
@@ -1,18 +1,18 @@
1
1
  "use strict";
2
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
4
+ 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");
5
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
+ };
2
7
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
8
  if (kind === "m") throw new TypeError("Private method is not writable");
4
9
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
10
  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
11
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
12
  };
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_selectedNetworkClientId, _EarnController_earnApiService, _EarnController_addTransactionFn, _EarnController_supportedPooledStakingChains, _EarnController_initializeSDK, _EarnController_getCurrentAccount, _EarnController_getCurrentChainId;
13
+ var _EarnController_instances, _EarnController_stakeSDK, _EarnController_selectedNetworkClientId, _EarnController_stakingApiService, _EarnController_initializeSDK, _EarnController_getCurrentAccount, _EarnController_getCurrentChainId;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.EarnController = exports.getDefaultEarnControllerState = 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;
15
+ exports.EarnController = exports.getDefaultEarnControllerState = exports.controllerName = void 0;
16
16
  const providers_1 = require("@ethersproject/providers");
17
17
  const base_controller_1 = require("@metamask/base-controller");
18
18
  const controller_utils_1 = require("@metamask/controller-utils");
@@ -24,10 +24,6 @@ const stakingTransactionTypes = new Set([
24
24
  transaction_controller_1.TransactionType.stakingUnstake,
25
25
  transaction_controller_1.TransactionType.stakingClaim,
26
26
  ]);
27
- const lendingTransactionTypes = new Set([
28
- transaction_controller_1.TransactionType.lendingDeposit,
29
- 'lendingWithdraw',
30
- ]);
31
27
  /**
32
28
  * Metadata for the EarnController.
33
29
  */
@@ -36,7 +32,7 @@ const earnControllerMetadata = {
36
32
  persist: true,
37
33
  anonymous: false,
38
34
  },
39
- lending: {
35
+ stablecoin_lending: {
40
36
  persist: true,
41
37
  anonymous: false,
42
38
  },
@@ -46,42 +42,17 @@ const earnControllerMetadata = {
46
42
  },
47
43
  };
48
44
  // === Default State ===
49
- exports.DEFAULT_LENDING_MARKET = {
50
- id: '',
51
- chainId: 0,
52
- protocol: '',
45
+ const DEFAULT_STABLECOIN_VAULT = {
46
+ symbol: '',
53
47
  name: '',
54
- address: '',
55
- tvlUnderlying: '0',
56
- netSupplyRate: 0,
57
- totalSupplyRate: 0,
58
- underlying: {
59
- address: '',
60
- chainId: 0,
61
- },
62
- outputToken: {
63
- address: '',
64
- chainId: 0,
65
- },
66
- rewards: [
67
- {
68
- token: {
69
- address: '',
70
- chainId: 0,
71
- },
72
- rate: 0,
73
- },
74
- ],
75
- };
76
- exports.DEFAULT_LENDING_POSITION = {
77
- id: '',
78
48
  chainId: 0,
79
- assets: '0',
80
- marketId: '',
81
- marketAddress: '',
82
- protocol: '',
49
+ tokenAddress: '',
50
+ vaultAddress: '',
51
+ currentAPY: '0',
52
+ supply: '0',
53
+ liquidity: '0',
83
54
  };
84
- exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
55
+ const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
85
56
  oneDay: '0',
86
57
  oneWeek: '0',
87
58
  oneMonth: '0',
@@ -89,24 +60,6 @@ exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
89
60
  sixMonths: '0',
90
61
  oneYear: '0',
91
62
  };
92
- exports.DEFAULT_POOLED_STAKING_CHAIN_STATE = {
93
- pooledStakes: {
94
- account: '',
95
- lifetimeRewards: '0',
96
- assets: '0',
97
- exitRequests: [],
98
- },
99
- exchangeRate: '1',
100
- vaultMetadata: {
101
- apy: '0',
102
- capacity: '0',
103
- feePercent: 0,
104
- totalAssets: '0',
105
- vaultAddress: '0x0000000000000000000000000000000000000000',
106
- },
107
- vaultDailyApys: [],
108
- vaultApyAverages: exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES,
109
- };
110
63
  /**
111
64
  * Gets the default state for the EarnController.
112
65
  *
@@ -115,13 +68,26 @@ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE = {
115
68
  function getDefaultEarnControllerState() {
116
69
  return {
117
70
  pooled_staking: {
118
- '0': exports.DEFAULT_POOLED_STAKING_CHAIN_STATE,
71
+ pooledStakes: {
72
+ account: '',
73
+ lifetimeRewards: '0',
74
+ assets: '0',
75
+ exitRequests: [],
76
+ },
77
+ exchangeRate: '1',
78
+ vaultMetadata: {
79
+ apy: '0',
80
+ capacity: '0',
81
+ feePercent: 0,
82
+ totalAssets: '0',
83
+ vaultAddress: '0x0000000000000000000000000000000000000000',
84
+ },
85
+ vaultDailyApys: [],
86
+ vaultApyAverages: DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES,
119
87
  isEligible: false,
120
88
  },
121
- lending: {
122
- markets: [exports.DEFAULT_LENDING_MARKET],
123
- positions: [exports.DEFAULT_LENDING_POSITION],
124
- isEligible: false,
89
+ stablecoin_lending: {
90
+ vaults: [DEFAULT_STABLECOIN_VAULT],
125
91
  },
126
92
  lastUpdated: 0,
127
93
  };
@@ -132,7 +98,7 @@ exports.getDefaultEarnControllerState = getDefaultEarnControllerState;
132
98
  * EarnController manages DeFi earning opportunities across different protocols and chains.
133
99
  */
134
100
  class EarnController extends base_controller_1.BaseController {
135
- constructor({ messenger, state = {}, addTransactionFn, }) {
101
+ constructor({ messenger, state = {}, }) {
136
102
  super({
137
103
  name: exports.controllerName,
138
104
  metadata: earnControllerMetadata,
@@ -143,37 +109,22 @@ class EarnController extends base_controller_1.BaseController {
143
109
  },
144
110
  });
145
111
  _EarnController_instances.add(this);
146
- _EarnController_earnSDK.set(this, null);
112
+ _EarnController_stakeSDK.set(this, null);
147
113
  _EarnController_selectedNetworkClientId.set(this, void 0);
148
- _EarnController_earnApiService.set(this, new stake_sdk_1.EarnApiService());
149
- _EarnController_addTransactionFn.set(this, void 0);
150
- _EarnController_supportedPooledStakingChains.set(this, void 0);
151
- // temporary array of supported chains
152
- // TODO: remove this once we have a more permanent solution
153
- // from sdk or api to get lending and pooled staking chains
154
- __classPrivateFieldSet(this, _EarnController_supportedPooledStakingChains, [1, 560048], "f");
155
- __classPrivateFieldSet(this, _EarnController_addTransactionFn, addTransactionFn, "f");
156
- __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this).catch(console.error);
114
+ _EarnController_stakingApiService.set(this, new stake_sdk_1.StakingApiService());
115
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this);
157
116
  this.refreshPooledStakingData().catch(console.error);
158
- this.refreshLendingData().catch(console.error);
159
117
  const { selectedNetworkClientId } = this.messagingSystem.call('NetworkController:getState');
160
118
  __classPrivateFieldSet(this, _EarnController_selectedNetworkClientId, selectedNetworkClientId, "f");
161
119
  // Listen for network changes
162
120
  this.messagingSystem.subscribe('NetworkController:stateChange', (networkControllerState) => {
163
121
  if (networkControllerState.selectedNetworkClientId !==
164
122
  __classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
165
- const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this, networkControllerState.selectedNetworkClientId);
166
- __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this, networkControllerState.selectedNetworkClientId).catch(console.error);
167
- if (__classPrivateFieldGet(this, _EarnController_supportedPooledStakingChains, "f").includes(chainId)) {
168
- // only refresh pool staking data for the chain we are switching to
169
- this.refreshPooledStakingVaultMetadata(chainId).catch(console.error);
170
- this.refreshPooledStakingVaultDailyApys(chainId).catch(console.error);
171
- this.refreshPooledStakingVaultApyAverages(chainId).catch(console.error);
172
- this.refreshPooledStakes({ chainId }).catch(console.error);
173
- }
174
- // refresh lending data for all chains
175
- this.refreshLendingMarkets().catch(console.error);
176
- this.refreshLendingPositions().catch(console.error);
123
+ __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this, networkControllerState.selectedNetworkClientId);
124
+ this.refreshPooledStakingVaultMetadata().catch(console.error);
125
+ this.refreshPooledStakingVaultDailyApys().catch(console.error);
126
+ this.refreshPooledStakingVaultApyAverages().catch(console.error);
127
+ this.refreshPooledStakes().catch(console.error);
177
128
  }
178
129
  __classPrivateFieldSet(this, _EarnController_selectedNetworkClientId, networkControllerState.selectedNetworkClientId, "f");
179
130
  });
@@ -185,11 +136,8 @@ class EarnController extends base_controller_1.BaseController {
185
136
  * Until this has been fixed, we rely on the event payload for the latest account instead of #getCurrentAccount().
186
137
  * Issue: https://github.com/MetaMask/accounts-planning/issues/887
187
138
  */
188
- // TODO: temp solution, this will refresh lending eligibility also
189
- // we could have a more general check, as what is happening is a compliance address check
190
139
  this.refreshStakingEligibility({ address }).catch(console.error);
191
140
  this.refreshPooledStakes({ address }).catch(console.error);
192
- this.refreshLendingPositions({ address }).catch(console.error);
193
141
  });
194
142
  // Listen for confirmed staking transactions
195
143
  this.messagingSystem.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
@@ -201,15 +149,10 @@ class EarnController extends base_controller_1.BaseController {
201
149
  const { type, originalType } = transactionMeta;
202
150
  const isStakingTransaction = stakingTransactionTypes.has(type) ||
203
151
  stakingTransactionTypes.has(originalType);
204
- const isLendingTransaction = lendingTransactionTypes.has(type) ||
205
- lendingTransactionTypes.has(originalType);
206
- const sender = transactionMeta.txParams.from;
207
152
  if (isStakingTransaction) {
153
+ const sender = transactionMeta.txParams.from;
208
154
  this.refreshPooledStakes({ resetCache: true, address: sender }).catch(console.error);
209
155
  }
210
- if (isLendingTransaction) {
211
- this.refreshLendingPositions({ address: sender }).catch(console.error);
212
- }
213
156
  });
214
157
  }
215
158
  /**
@@ -220,24 +163,18 @@ class EarnController extends base_controller_1.BaseController {
220
163
  * @param options - Optional arguments
221
164
  * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
222
165
  * @param [options.address] - The address to refresh pooled stakes for (optional).
223
- * @param [options.chainId] - The chain id to refresh pooled stakes for (optional).
224
166
  * @returns A promise that resolves when the stakes data has been updated
225
167
  */
226
- async refreshPooledStakes({ resetCache = false, address, chainId, } = {}) {
168
+ async refreshPooledStakes({ resetCache = false, address, } = {}) {
227
169
  const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
228
170
  if (!addressToUse) {
229
171
  return;
230
172
  }
231
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
232
- const { accounts, exchangeRate } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakes([addressToUse], chainIdToUse, resetCache);
173
+ const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
174
+ const { accounts, exchangeRate } = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getPooledStakes([addressToUse], chainId, resetCache);
233
175
  this.update((state) => {
234
- const chainState = state.pooled_staking[chainIdToUse] ??
235
- exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
236
- state.pooled_staking[chainIdToUse] = {
237
- ...chainState,
238
- pooledStakes: accounts[0],
239
- exchangeRate,
240
- };
176
+ state.pooled_staking.pooledStakes = accounts[0];
177
+ state.pooled_staking.exchangeRate = exchangeRate;
241
178
  });
242
179
  }
243
180
  /**
@@ -253,12 +190,11 @@ class EarnController extends base_controller_1.BaseController {
253
190
  if (!addressToCheck) {
254
191
  return;
255
192
  }
256
- const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakingEligibility([
193
+ const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getPooledStakingEligibility([
257
194
  addressToCheck,
258
195
  ]);
259
196
  this.update((state) => {
260
197
  state.pooled_staking.isEligible = isEligible;
261
- state.lending.isEligible = isEligible;
262
198
  });
263
199
  }
264
200
  /**
@@ -266,59 +202,41 @@ class EarnController extends base_controller_1.BaseController {
266
202
  * Updates the vault metadata in the controller state including APY, capacity,
267
203
  * fee percentage, total assets, and vault address.
268
204
  *
269
- * @param chainId - The chain id to refresh pooled staking vault metadata for (optional).
270
205
  * @returns A promise that resolves when the vault metadata has been updated
271
206
  */
272
- async refreshPooledStakingVaultMetadata(chainId) {
273
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
274
- const vaultMetadata = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultData(chainIdToUse);
207
+ async refreshPooledStakingVaultMetadata() {
208
+ const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
209
+ const vaultMetadata = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getVaultData(chainId);
275
210
  this.update((state) => {
276
- const chainState = state.pooled_staking[chainIdToUse] ??
277
- exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
278
- state.pooled_staking[chainIdToUse] = {
279
- ...chainState,
280
- vaultMetadata,
281
- };
211
+ state.pooled_staking.vaultMetadata = vaultMetadata;
282
212
  });
283
213
  }
284
214
  /**
285
215
  * Refreshes pooled staking vault daily apys for the current chain.
286
216
  * Updates the pooled staking vault daily apys controller state.
287
217
  *
288
- * @param chainId - The chain id to refresh pooled staking vault daily apys for (optional).
289
218
  * @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).
290
219
  * @param 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').
291
220
  * @returns A promise that resolves when the pooled staking vault daily apys have been updated.
292
221
  */
293
- async refreshPooledStakingVaultDailyApys(chainId, days = 365, order = 'desc') {
294
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
295
- const vaultDailyApys = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultDailyApys(chainIdToUse, days, order);
222
+ async refreshPooledStakingVaultDailyApys(days = 365, order = 'desc') {
223
+ const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
224
+ const vaultDailyApys = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getVaultDailyApys(chainId, days, order);
296
225
  this.update((state) => {
297
- const chainState = state.pooled_staking[chainIdToUse] ??
298
- exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
299
- state.pooled_staking[chainIdToUse] = {
300
- ...chainState,
301
- vaultDailyApys,
302
- };
226
+ state.pooled_staking.vaultDailyApys = vaultDailyApys;
303
227
  });
304
228
  }
305
229
  /**
306
230
  * Refreshes pooled staking vault apy averages for the current chain.
307
231
  * Updates the pooled staking vault apy averages controller state.
308
232
  *
309
- * @param chainId - The chain id to refresh pooled staking vault apy averages for (optional).
310
233
  * @returns A promise that resolves when the pooled staking vault apy averages have been updated.
311
234
  */
312
- async refreshPooledStakingVaultApyAverages(chainId) {
313
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
314
- const vaultApyAverages = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultApyAverages(chainIdToUse);
235
+ async refreshPooledStakingVaultApyAverages() {
236
+ const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
237
+ const vaultApyAverages = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getVaultApyAverages(chainId);
315
238
  this.update((state) => {
316
- const chainState = state.pooled_staking[chainIdToUse] ??
317
- exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
318
- state.pooled_staking[chainIdToUse] = {
319
- ...chainState,
320
- vaultApyAverages,
321
- };
239
+ state.pooled_staking.vaultApyAverages = vaultApyAverages;
322
240
  });
323
241
  }
324
242
  /**
@@ -333,300 +251,39 @@ class EarnController extends base_controller_1.BaseController {
333
251
  * @throws {Error} If any of the refresh operations fail, with concatenated error messages
334
252
  */
335
253
  async refreshPooledStakingData({ resetCache, address, } = {}) {
336
- const errors = [];
337
- for (const chainId of __classPrivateFieldGet(this, _EarnController_supportedPooledStakingChains, "f")) {
338
- await Promise.all([
339
- this.refreshPooledStakes({ resetCache, address, chainId }).catch((error) => {
340
- errors.push(error);
341
- }),
342
- this.refreshStakingEligibility({ address }).catch((error) => {
343
- errors.push(error);
344
- }),
345
- this.refreshPooledStakingVaultMetadata(chainId).catch((error) => {
346
- errors.push(error);
347
- }),
348
- this.refreshPooledStakingVaultDailyApys(chainId).catch((error) => {
349
- errors.push(error);
350
- }),
351
- this.refreshPooledStakingVaultApyAverages(chainId).catch((error) => {
352
- errors.push(error);
353
- }),
354
- ]);
355
- }
356
- if (errors.length > 0) {
357
- throw new Error(`Failed to refresh some staking data: ${errors
358
- .map((e) => e.message)
359
- .join(', ')}`);
360
- }
361
- }
362
- /**
363
- * Refreshes the lending markets data for all chains.
364
- * Updates the lending markets in the controller state.
365
- *
366
- * @returns A promise that resolves when the lending markets have been updated
367
- */
368
- async refreshLendingMarkets() {
369
- const markets = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getMarkets();
370
- this.update((state) => {
371
- state.lending.markets = markets;
372
- });
373
- }
374
- /**
375
- * Refreshes the lending positions for the current account.
376
- * Updates the lending positions in the controller state.
377
- *
378
- * @param options - Optional arguments
379
- * @param [options.address] - The address to refresh lending positions for (optional).
380
- * @returns A promise that resolves when the lending positions have been updated
381
- */
382
- async refreshLendingPositions({ address, } = {}) {
383
- const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
384
- // linter complaining about this not being a promise, but it is
385
- // TODO: figure out why this is not seen as a promise
386
- const positions = await Promise.resolve(__classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getPositions(addressToUse));
387
- this.update((state) => {
388
- state.lending.positions = positions.map((position) => ({
389
- ...position,
390
- marketId: position.market.id,
391
- marketAddress: position.market.address,
392
- protocol: position.market.protocol,
393
- }));
394
- });
395
- }
396
- /**
397
- * Refreshes the lending eligibility status for the current account.
398
- * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.
399
- *
400
- * @param options - Optional arguments
401
- * @param [options.address] - The address to refresh lending eligibility for (optional).
402
- * @returns A promise that resolves when the eligibility status has been updated
403
- */
404
- async refreshLendingEligibility({ address, } = {}) {
405
- const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
406
- // TODO: this is a temporary solution to refresh lending eligibility as
407
- // the eligibility check is not yet implemented for lending
408
- // this check will check the address against the same blocklist as the
409
- // staking eligibility check
410
- if (!addressToUse) {
411
- return;
412
- }
413
- const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakingEligibility([
414
- addressToUse,
415
- ]);
416
- this.update((state) => {
417
- state.lending.isEligible = isEligible;
418
- state.pooled_staking.isEligible = isEligible;
419
- });
420
- }
421
- /**
422
- * Refreshes all lending related data including markets, positions, and eligibility.
423
- * This method allows partial success, meaning some data may update while other requests fail.
424
- * All errors are collected and thrown as a single error message.
425
- *
426
- * @returns A promise that resolves when all possible data has been updated
427
- * @throws {Error} If any of the refresh operations fail, with concatenated error messages
428
- */
429
- async refreshLendingData() {
430
254
  const errors = [];
431
255
  await Promise.all([
432
- this.refreshLendingMarkets().catch((error) => {
256
+ this.refreshPooledStakes({ resetCache, address }).catch((error) => {
433
257
  errors.push(error);
434
258
  }),
435
- this.refreshLendingPositions().catch((error) => {
259
+ this.refreshStakingEligibility({ address }).catch((error) => {
436
260
  errors.push(error);
437
261
  }),
438
- this.refreshLendingEligibility().catch((error) => {
262
+ this.refreshPooledStakingVaultMetadata().catch((error) => {
263
+ errors.push(error);
264
+ }),
265
+ this.refreshPooledStakingVaultDailyApys().catch((error) => {
266
+ errors.push(error);
267
+ }),
268
+ this.refreshPooledStakingVaultApyAverages().catch((error) => {
439
269
  errors.push(error);
440
270
  }),
441
271
  ]);
442
272
  if (errors.length > 0) {
443
- throw new Error(`Failed to refresh some lending data: ${errors
273
+ throw new Error(`Failed to refresh some staking data: ${errors
444
274
  .map((e) => e.message)
445
275
  .join(', ')}`);
446
276
  }
447
277
  }
448
- /**
449
- * Gets the lending position history for the current account.
450
- *
451
- * @param options - Optional arguments
452
- * @param [options.address] - The address to get lending position history for (optional).
453
- * @param [options.chainId] - The chain id to get lending position history for (optional).
454
- * @param [options.positionId] - The position id to get lending position history for.
455
- * @param [options.marketId] - The market id to get lending position history for.
456
- * @param [options.marketAddress] - The market address to get lending position history for.
457
- * @param [options.protocol] - The protocol to get lending position history for.
458
- * @param [options.days] - The number of days to get lending position history for (optional).
459
- * @returns A promise that resolves when the lending position history has been updated
460
- */
461
- getLendingPositionHistory({ address, chainId, positionId, marketId, marketAddress, protocol, days = 730, }) {
462
- const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
463
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
464
- return __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getPositionHistory(addressToUse, chainIdToUse, protocol, marketId, marketAddress, positionId, days);
465
- }
466
- /**
467
- * Gets the lending market daily apys and averages for the current chain.
468
- *
469
- * @param options - Optional arguments
470
- * @param [options.chainId] - The chain id to get lending market daily apys and averages for (optional).
471
- * @param [options.protocol] - The protocol to get lending market daily apys and averages for.
472
- * @param [options.marketId] - The market id to get lending market daily apys and averages for.
473
- * @param [options.days] - The number of days to get lending market daily apys and averages for (optional).
474
- * @returns A promise that resolves when the lending market daily apys and averages have been updated
475
- */
476
- getLendingMarketDailyApysAndAverages({ chainId, protocol, marketId, days = 365, }) {
477
- const chainIdToUse = chainId ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
478
- return __classPrivateFieldGet(this, _EarnController_earnApiService, "f").lending.getHistoricMarketApys(chainIdToUse, protocol, marketId, days);
479
- }
480
- /**
481
- * Executes a lending deposit transaction.
482
- *
483
- * @param options - The options for the lending deposit transaction.
484
- * @param options.amount - The amount to deposit.
485
- * @param options.protocol - The protocol of the lending market.
486
- * @param options.underlyingTokenAddress - The address of the underlying token.
487
- * @param options.gasOptions - The gas options for the transaction.
488
- * @param options.gasOptions.gasLimit - The gas limit for the transaction.
489
- * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
490
- * @param options.txOptions - The transaction options for the transaction.
491
- * @returns A promise that resolves to the transaction hash.
492
- */
493
- async executeLendingDeposit({ amount, protocol, underlyingTokenAddress, gasOptions, txOptions, }) {
494
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
495
- const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeDepositTransactionData(amount, address, gasOptions);
496
- if (!transactionData) {
497
- throw new Error('Transaction data not found');
498
- }
499
- if (!__classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
500
- throw new Error('Selected network client id not found');
501
- }
502
- const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
503
- ...transactionData,
504
- value: transactionData.value.toString(),
505
- chainId: (0, controller_utils_1.toHex)(__classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this)),
506
- gasLimit: String(transactionData.gasLimit),
507
- }, {
508
- ...txOptions,
509
- networkClientId: __classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f"),
510
- });
511
- return txHash;
512
- }
513
- /**
514
- * Executes a lending withdraw transaction.
515
- *
516
- * @param options - The options for the lending withdraw transaction.
517
- * @param options.amount - The amount to withdraw.
518
- * @param options.protocol - The protocol of the lending market.
519
- * @param options.underlyingTokenAddress - The address of the underlying token.
520
- * @param options.gasOptions - The gas options for the transaction.
521
- * @param options.gasOptions.gasLimit - The gas limit for the transaction.
522
- * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
523
- * @param options.txOptions - The transaction options for the transaction.
524
- * @returns A promise that resolves to the transaction hash.
525
- */
526
- async executeLendingWithdraw({ amount, protocol, underlyingTokenAddress, gasOptions, txOptions, }) {
527
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
528
- const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeWithdrawTransactionData(amount, address, gasOptions);
529
- if (!transactionData) {
530
- throw new Error('Transaction data not found');
531
- }
532
- if (!__classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
533
- throw new Error('Selected network client id not found');
534
- }
535
- const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
536
- ...transactionData,
537
- value: transactionData.value.toString(),
538
- chainId: (0, controller_utils_1.toHex)(__classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this)),
539
- gasLimit: String(transactionData.gasLimit),
540
- }, {
541
- ...txOptions,
542
- networkClientId: __classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f"),
543
- });
544
- return txHash;
545
- }
546
- /**
547
- * Executes a lending token approve transaction.
548
- *
549
- * @param options - The options for the lending token approve transaction.
550
- * @param options.amount - The amount to approve.
551
- * @param options.protocol - The protocol of the lending market.
552
- * @param options.underlyingTokenAddress - The address of the underlying token.
553
- * @param options.gasOptions - The gas options for the transaction.
554
- * @param options.gasOptions.gasLimit - The gas limit for the transaction.
555
- * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.
556
- * @param options.txOptions - The transaction options for the transaction.
557
- * @returns A promise that resolves to the transaction hash.
558
- */
559
- async executeLendingTokenApprove({ protocol, amount, underlyingTokenAddress, gasOptions, txOptions, }) {
560
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
561
- const transactionData = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.encodeUnderlyingTokenApproveTransactionData(amount, address, gasOptions);
562
- if (!transactionData) {
563
- throw new Error('Transaction data not found');
564
- }
565
- if (!__classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
566
- throw new Error('Selected network client id not found');
567
- }
568
- const txHash = await __classPrivateFieldGet(this, _EarnController_addTransactionFn, "f").call(this, {
569
- ...transactionData,
570
- value: transactionData.value.toString(),
571
- chainId: (0, controller_utils_1.toHex)(__classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this)),
572
- gasLimit: String(transactionData.gasLimit),
573
- }, {
574
- ...txOptions,
575
- networkClientId: __classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f"),
576
- });
577
- return txHash;
578
- }
579
- /**
580
- * Gets the allowance for a lending token.
581
- *
582
- * @param protocol - The protocol of the lending market.
583
- * @param underlyingTokenAddress - The address of the underlying token.
584
- * @returns A promise that resolves to the allowance.
585
- */
586
- async getLendingTokenAllowance(protocol, underlyingTokenAddress) {
587
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
588
- const allowance = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.underlyingTokenAllowance(address);
589
- return allowance;
590
- }
591
- /**
592
- * Gets the maximum withdraw amount for a lending token's output token or shares if no output token.
593
- *
594
- * @param protocol - The protocol of the lending market.
595
- * @param underlyingTokenAddress - The address of the underlying token.
596
- * @returns A promise that resolves to the maximum withdraw amount.
597
- */
598
- async getLendingTokenMaxWithdraw(protocol, underlyingTokenAddress) {
599
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
600
- const maxWithdraw = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.maxWithdraw(address);
601
- return maxWithdraw;
602
- }
603
- /**
604
- * Gets the maximum deposit amount for a lending token.
605
- *
606
- * @param protocol - The protocol of the lending market.
607
- * @param underlyingTokenAddress - The address of the underlying token.
608
- * @returns A promise that resolves to the maximum deposit amount.
609
- */
610
- async getLendingTokenMaxDeposit(protocol, underlyingTokenAddress) {
611
- const address = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
612
- const maxDeposit = await __classPrivateFieldGet(this, _EarnController_earnSDK, "f")?.contracts?.lending?.[protocol]?.[underlyingTokenAddress]?.maxDeposit(address);
613
- return maxDeposit;
614
- }
615
278
  }
616
279
  exports.EarnController = EarnController;
617
- _EarnController_earnSDK = new WeakMap(), _EarnController_selectedNetworkClientId = new WeakMap(), _EarnController_earnApiService = new WeakMap(), _EarnController_addTransactionFn = new WeakMap(), _EarnController_supportedPooledStakingChains = new WeakMap(), _EarnController_instances = new WeakSet(), _EarnController_initializeSDK =
618
- /**
619
- * Initializes the Earn SDK.
620
- *
621
- * @param networkClientId - The network client id to initialize the Earn SDK for (optional).
622
- */
623
- async function _EarnController_initializeSDK(networkClientId) {
280
+ _EarnController_stakeSDK = new WeakMap(), _EarnController_selectedNetworkClientId = new WeakMap(), _EarnController_stakingApiService = new WeakMap(), _EarnController_instances = new WeakSet(), _EarnController_initializeSDK = function _EarnController_initializeSDK(networkClientId) {
624
281
  const { selectedNetworkClientId } = networkClientId
625
282
  ? { selectedNetworkClientId: networkClientId }
626
283
  : this.messagingSystem.call('NetworkController:getState');
627
284
  const networkClient = this.messagingSystem.call('NetworkController:getNetworkClientById', selectedNetworkClientId);
628
285
  if (!networkClient?.provider) {
629
- __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
286
+ __classPrivateFieldSet(this, _EarnController_stakeSDK, null, "f");
630
287
  return;
631
288
  }
632
289
  const provider = new providers_1.Web3Provider(networkClient.provider);
@@ -636,23 +293,31 @@ async function _EarnController_initializeSDK(networkClientId) {
636
293
  chainId: (0, controller_utils_1.convertHexToDecimal)(chainId),
637
294
  };
638
295
  try {
639
- __classPrivateFieldSet(this, _EarnController_earnSDK, await stake_sdk_1.EarnSdk.create(provider, config), "f");
296
+ __classPrivateFieldSet(this, _EarnController_stakeSDK, stake_sdk_1.StakeSdk.create(config), "f");
297
+ __classPrivateFieldGet(this, _EarnController_stakeSDK, "f").pooledStakingContract.connectSignerOrProvider(provider);
640
298
  }
641
299
  catch (error) {
642
- __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
300
+ __classPrivateFieldSet(this, _EarnController_stakeSDK, null, "f");
643
301
  // Only log unexpected errors, not unsupported chain errors
644
302
  if (!(error instanceof Error &&
645
303
  error.message.includes('Unsupported chainId'))) {
646
- console.error('Earn SDK initialization failed:', error);
304
+ console.error('Stake SDK initialization failed:', error);
647
305
  }
648
306
  }
649
307
  }, _EarnController_getCurrentAccount = function _EarnController_getCurrentAccount() {
650
308
  return this.messagingSystem.call('AccountsController:getSelectedAccount');
651
- }, _EarnController_getCurrentChainId = function _EarnController_getCurrentChainId(networkClientId) {
652
- const networkClientIdToUse = networkClientId ??
653
- this.messagingSystem.call('NetworkController:getState')
654
- .selectedNetworkClientId;
655
- const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientIdToUse);
656
- return (0, controller_utils_1.convertHexToDecimal)(chainId);
309
+ }, _EarnController_getCurrentChainId = function _EarnController_getCurrentChainId() {
310
+ // const { selectedNetworkClientId } = this.messagingSystem.call(
311
+ // 'NetworkController:getState',
312
+ // );
313
+ // const {
314
+ // configuration: { chainId },
315
+ // } = this.messagingSystem.call(
316
+ // 'NetworkController:getNetworkClientById',
317
+ // selectedNetworkClientId,
318
+ // );
319
+ // return convertHexToDecimal(chainId);
320
+ // TEMP: Until we update our data-fetching and storage solution to not depend on single selected network.
321
+ return stake_sdk_1.ChainId.ETHEREUM;
657
322
  };
658
323
  //# sourceMappingURL=EarnController.cjs.map