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