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

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
- };
7
2
  var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
8
3
  if (kind === "m") throw new TypeError("Private method is not writable");
9
4
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
10
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");
11
6
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
12
7
  };
13
- var _EarnController_instances, _EarnController_stakeSDK, _EarnController_selectedNetworkClientId, _EarnController_stakingApiService, _EarnController_initializeSDK, _EarnController_getCurrentAccount, _EarnController_getCurrentChainId;
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;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.EarnController = exports.getDefaultEarnControllerState = exports.controllerName = void 0;
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;
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,6 +24,10 @@ 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
+ ]);
27
31
  /**
28
32
  * Metadata for the EarnController.
29
33
  */
@@ -32,7 +36,7 @@ const earnControllerMetadata = {
32
36
  persist: true,
33
37
  anonymous: false,
34
38
  },
35
- stablecoin_lending: {
39
+ lending: {
36
40
  persist: true,
37
41
  anonymous: false,
38
42
  },
@@ -42,17 +46,42 @@ const earnControllerMetadata = {
42
46
  },
43
47
  };
44
48
  // === Default State ===
45
- const DEFAULT_STABLECOIN_VAULT = {
46
- symbol: '',
49
+ exports.DEFAULT_LENDING_MARKET = {
50
+ id: '',
51
+ chainId: 0,
52
+ protocol: '',
47
53
  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: '',
48
78
  chainId: 0,
49
- tokenAddress: '',
50
- vaultAddress: '',
51
- currentAPY: '0',
52
- supply: '0',
53
- liquidity: '0',
79
+ assets: '0',
80
+ marketId: '',
81
+ marketAddress: '',
82
+ protocol: '',
54
83
  };
55
- const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
84
+ exports.DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
56
85
  oneDay: '0',
57
86
  oneWeek: '0',
58
87
  oneMonth: '0',
@@ -60,6 +89,24 @@ const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
60
89
  sixMonths: '0',
61
90
  oneYear: '0',
62
91
  };
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
+ };
63
110
  /**
64
111
  * Gets the default state for the EarnController.
65
112
  *
@@ -68,26 +115,13 @@ const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES = {
68
115
  function getDefaultEarnControllerState() {
69
116
  return {
70
117
  pooled_staking: {
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,
118
+ '0': exports.DEFAULT_POOLED_STAKING_CHAIN_STATE,
87
119
  isEligible: false,
88
120
  },
89
- stablecoin_lending: {
90
- vaults: [DEFAULT_STABLECOIN_VAULT],
121
+ lending: {
122
+ markets: [exports.DEFAULT_LENDING_MARKET],
123
+ positions: [exports.DEFAULT_LENDING_POSITION],
124
+ isEligible: false,
91
125
  },
92
126
  lastUpdated: 0,
93
127
  };
@@ -98,7 +132,7 @@ exports.getDefaultEarnControllerState = getDefaultEarnControllerState;
98
132
  * EarnController manages DeFi earning opportunities across different protocols and chains.
99
133
  */
100
134
  class EarnController extends base_controller_1.BaseController {
101
- constructor({ messenger, state = {}, }) {
135
+ constructor({ messenger, state = {}, addTransactionFn, }) {
102
136
  super({
103
137
  name: exports.controllerName,
104
138
  metadata: earnControllerMetadata,
@@ -109,22 +143,37 @@ class EarnController extends base_controller_1.BaseController {
109
143
  },
110
144
  });
111
145
  _EarnController_instances.add(this);
112
- _EarnController_stakeSDK.set(this, null);
146
+ _EarnController_earnSDK.set(this, null);
113
147
  _EarnController_selectedNetworkClientId.set(this, void 0);
114
- _EarnController_stakingApiService.set(this, new stake_sdk_1.StakingApiService());
115
- __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this);
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);
116
157
  this.refreshPooledStakingData().catch(console.error);
158
+ this.refreshLendingData().catch(console.error);
117
159
  const { selectedNetworkClientId } = this.messagingSystem.call('NetworkController:getState');
118
160
  __classPrivateFieldSet(this, _EarnController_selectedNetworkClientId, selectedNetworkClientId, "f");
119
161
  // Listen for network changes
120
162
  this.messagingSystem.subscribe('NetworkController:stateChange', (networkControllerState) => {
121
163
  if (networkControllerState.selectedNetworkClientId !==
122
164
  __classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
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);
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);
128
177
  }
129
178
  __classPrivateFieldSet(this, _EarnController_selectedNetworkClientId, networkControllerState.selectedNetworkClientId, "f");
130
179
  });
@@ -136,8 +185,11 @@ class EarnController extends base_controller_1.BaseController {
136
185
  * Until this has been fixed, we rely on the event payload for the latest account instead of #getCurrentAccount().
137
186
  * Issue: https://github.com/MetaMask/accounts-planning/issues/887
138
187
  */
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
139
190
  this.refreshStakingEligibility({ address }).catch(console.error);
140
191
  this.refreshPooledStakes({ address }).catch(console.error);
192
+ this.refreshLendingPositions({ address }).catch(console.error);
141
193
  });
142
194
  // Listen for confirmed staking transactions
143
195
  this.messagingSystem.subscribe('TransactionController:transactionConfirmed', (transactionMeta) => {
@@ -149,10 +201,15 @@ class EarnController extends base_controller_1.BaseController {
149
201
  const { type, originalType } = transactionMeta;
150
202
  const isStakingTransaction = stakingTransactionTypes.has(type) ||
151
203
  stakingTransactionTypes.has(originalType);
204
+ const isLendingTransaction = lendingTransactionTypes.has(type) ||
205
+ lendingTransactionTypes.has(originalType);
206
+ const sender = transactionMeta.txParams.from;
152
207
  if (isStakingTransaction) {
153
- const sender = transactionMeta.txParams.from;
154
208
  this.refreshPooledStakes({ resetCache: true, address: sender }).catch(console.error);
155
209
  }
210
+ if (isLendingTransaction) {
211
+ this.refreshLendingPositions({ address: sender }).catch(console.error);
212
+ }
156
213
  });
157
214
  }
158
215
  /**
@@ -163,18 +220,24 @@ class EarnController extends base_controller_1.BaseController {
163
220
  * @param options - Optional arguments
164
221
  * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
165
222
  * @param [options.address] - The address to refresh pooled stakes for (optional).
223
+ * @param [options.chainId] - The chain id to refresh pooled stakes for (optional).
166
224
  * @returns A promise that resolves when the stakes data has been updated
167
225
  */
168
- async refreshPooledStakes({ resetCache = false, address, } = {}) {
226
+ async refreshPooledStakes({ resetCache = false, address, chainId, } = {}) {
169
227
  const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
170
228
  if (!addressToUse) {
171
229
  return;
172
230
  }
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);
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);
175
233
  this.update((state) => {
176
- state.pooled_staking.pooledStakes = accounts[0];
177
- state.pooled_staking.exchangeRate = exchangeRate;
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
+ };
178
241
  });
179
242
  }
180
243
  /**
@@ -190,11 +253,12 @@ class EarnController extends base_controller_1.BaseController {
190
253
  if (!addressToCheck) {
191
254
  return;
192
255
  }
193
- const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_stakingApiService, "f").getPooledStakingEligibility([
256
+ const { eligible: isEligible } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakingEligibility([
194
257
  addressToCheck,
195
258
  ]);
196
259
  this.update((state) => {
197
260
  state.pooled_staking.isEligible = isEligible;
261
+ state.lending.isEligible = isEligible;
198
262
  });
199
263
  }
200
264
  /**
@@ -202,41 +266,59 @@ class EarnController extends base_controller_1.BaseController {
202
266
  * Updates the vault metadata in the controller state including APY, capacity,
203
267
  * fee percentage, total assets, and vault address.
204
268
  *
269
+ * @param chainId - The chain id to refresh pooled staking vault metadata for (optional).
205
270
  * @returns A promise that resolves when the vault metadata has been updated
206
271
  */
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);
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);
210
275
  this.update((state) => {
211
- state.pooled_staking.vaultMetadata = vaultMetadata;
276
+ const chainState = state.pooled_staking[chainIdToUse] ??
277
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
278
+ state.pooled_staking[chainIdToUse] = {
279
+ ...chainState,
280
+ vaultMetadata,
281
+ };
212
282
  });
213
283
  }
214
284
  /**
215
285
  * Refreshes pooled staking vault daily apys for the current chain.
216
286
  * Updates the pooled staking vault daily apys controller state.
217
287
  *
288
+ * @param chainId - The chain id to refresh pooled staking vault daily apys for (optional).
218
289
  * @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).
219
290
  * @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').
220
291
  * @returns A promise that resolves when the pooled staking vault daily apys have been updated.
221
292
  */
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);
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);
225
296
  this.update((state) => {
226
- state.pooled_staking.vaultDailyApys = vaultDailyApys;
297
+ const chainState = state.pooled_staking[chainIdToUse] ??
298
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
299
+ state.pooled_staking[chainIdToUse] = {
300
+ ...chainState,
301
+ vaultDailyApys,
302
+ };
227
303
  });
228
304
  }
229
305
  /**
230
306
  * Refreshes pooled staking vault apy averages for the current chain.
231
307
  * Updates the pooled staking vault apy averages controller state.
232
308
  *
309
+ * @param chainId - The chain id to refresh pooled staking vault apy averages for (optional).
233
310
  * @returns A promise that resolves when the pooled staking vault apy averages have been updated.
234
311
  */
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);
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);
238
315
  this.update((state) => {
239
- state.pooled_staking.vaultApyAverages = vaultApyAverages;
316
+ const chainState = state.pooled_staking[chainIdToUse] ??
317
+ exports.DEFAULT_POOLED_STAKING_CHAIN_STATE;
318
+ state.pooled_staking[chainIdToUse] = {
319
+ ...chainState,
320
+ vaultApyAverages,
321
+ };
240
322
  });
241
323
  }
242
324
  /**
@@ -251,39 +333,300 @@ class EarnController extends base_controller_1.BaseController {
251
333
  * @throws {Error} If any of the refresh operations fail, with concatenated error messages
252
334
  */
253
335
  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() {
254
430
  const errors = [];
255
431
  await Promise.all([
256
- this.refreshPooledStakes({ resetCache, address }).catch((error) => {
432
+ this.refreshLendingMarkets().catch((error) => {
257
433
  errors.push(error);
258
434
  }),
259
- this.refreshStakingEligibility({ address }).catch((error) => {
435
+ this.refreshLendingPositions().catch((error) => {
260
436
  errors.push(error);
261
437
  }),
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) => {
438
+ this.refreshLendingEligibility().catch((error) => {
269
439
  errors.push(error);
270
440
  }),
271
441
  ]);
272
442
  if (errors.length > 0) {
273
- throw new Error(`Failed to refresh some staking data: ${errors
443
+ throw new Error(`Failed to refresh some lending data: ${errors
274
444
  .map((e) => e.message)
275
445
  .join(', ')}`);
276
446
  }
277
447
  }
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
+ }
278
615
  }
279
616
  exports.EarnController = EarnController;
280
- _EarnController_stakeSDK = new WeakMap(), _EarnController_selectedNetworkClientId = new WeakMap(), _EarnController_stakingApiService = new WeakMap(), _EarnController_instances = new WeakSet(), _EarnController_initializeSDK = function _EarnController_initializeSDK(networkClientId) {
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) {
281
624
  const { selectedNetworkClientId } = networkClientId
282
625
  ? { selectedNetworkClientId: networkClientId }
283
626
  : this.messagingSystem.call('NetworkController:getState');
284
627
  const networkClient = this.messagingSystem.call('NetworkController:getNetworkClientById', selectedNetworkClientId);
285
628
  if (!networkClient?.provider) {
286
- __classPrivateFieldSet(this, _EarnController_stakeSDK, null, "f");
629
+ __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
287
630
  return;
288
631
  }
289
632
  const provider = new providers_1.Web3Provider(networkClient.provider);
@@ -293,31 +636,23 @@ _EarnController_stakeSDK = new WeakMap(), _EarnController_selectedNetworkClientI
293
636
  chainId: (0, controller_utils_1.convertHexToDecimal)(chainId),
294
637
  };
295
638
  try {
296
- __classPrivateFieldSet(this, _EarnController_stakeSDK, stake_sdk_1.StakeSdk.create(config), "f");
297
- __classPrivateFieldGet(this, _EarnController_stakeSDK, "f").pooledStakingContract.connectSignerOrProvider(provider);
639
+ __classPrivateFieldSet(this, _EarnController_earnSDK, await stake_sdk_1.EarnSdk.create(provider, config), "f");
298
640
  }
299
641
  catch (error) {
300
- __classPrivateFieldSet(this, _EarnController_stakeSDK, null, "f");
642
+ __classPrivateFieldSet(this, _EarnController_earnSDK, null, "f");
301
643
  // Only log unexpected errors, not unsupported chain errors
302
644
  if (!(error instanceof Error &&
303
645
  error.message.includes('Unsupported chainId'))) {
304
- console.error('Stake SDK initialization failed:', error);
646
+ console.error('Earn SDK initialization failed:', error);
305
647
  }
306
648
  }
307
649
  }, _EarnController_getCurrentAccount = function _EarnController_getCurrentAccount() {
308
650
  return this.messagingSystem.call('AccountsController:getSelectedAccount');
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;
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);
322
657
  };
323
658
  //# sourceMappingURL=EarnController.cjs.map