@metamask-previews/earn-controller 2.0.1-preview-2bb8758e → 3.0.0-preview-32f9004a
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.
- package/CHANGELOG.md +5 -1
- package/dist/EarnController.cjs +61 -61
- package/dist/EarnController.cjs.map +1 -1
- package/dist/EarnController.d.cts +10 -12
- package/dist/EarnController.d.cts.map +1 -1
- package/dist/EarnController.d.mts +10 -12
- package/dist/EarnController.d.mts.map +1 -1
- package/dist/EarnController.mjs +63 -63
- package/dist/EarnController.mjs.map +1 -1
- package/dist/constants.cjs +6 -0
- package/dist/constants.cjs.map +1 -0
- package/dist/constants.d.cts +3 -0
- package/dist/constants.d.cts.map +1 -0
- package/dist/constants.d.mts +3 -0
- package/dist/constants.d.mts.map +1 -0
- package/dist/constants.mjs +3 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +1 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +1 -2
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/package.json +1 -1
@@ -4,7 +4,7 @@ import { BaseController } from "@metamask/base-controller";
|
|
4
4
|
import type { NetworkControllerGetNetworkClientByIdAction, NetworkControllerGetStateAction, NetworkControllerStateChangeEvent } from "@metamask/network-controller";
|
5
5
|
import { type LendingMarket, type PooledStake, type VaultData, type VaultDailyApy, type VaultApyAverages, type LendingPosition, type GasLimitParams, type HistoricLendingMarketApys, EarnEnvironments } from "@metamask/stake-sdk";
|
6
6
|
import { type TransactionController, type TransactionControllerTransactionConfirmedEvent } from "@metamask/transaction-controller";
|
7
|
-
import type { RefreshLendingEligibilityOptions, RefreshLendingPositionsOptions, RefreshPooledStakesOptions, RefreshPooledStakingDataOptions
|
7
|
+
import type { RefreshEarnEligibilityOptions, RefreshLendingEligibilityOptions, RefreshLendingPositionsOptions, RefreshPooledStakesOptions, RefreshPooledStakingDataOptions } from "./types.mjs";
|
8
8
|
export declare const controllerName = "EarnController";
|
9
9
|
export type PooledStakingState = {
|
10
10
|
[chainId: number]: {
|
@@ -114,46 +114,44 @@ export declare class EarnController extends BaseController<typeof controllerName
|
|
114
114
|
* @param options - Optional arguments
|
115
115
|
* @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
|
116
116
|
* @param [options.address] - The address to refresh pooled stakes for (optional).
|
117
|
-
* @param [options.chainId] - The chain id to refresh pooled stakes for (optional).
|
118
117
|
* @returns A promise that resolves when the stakes data has been updated
|
119
118
|
*/
|
120
|
-
refreshPooledStakes({ resetCache, address,
|
119
|
+
refreshPooledStakes({ resetCache, address, }?: RefreshPooledStakesOptions): Promise<void>;
|
121
120
|
/**
|
122
|
-
* Refreshes the
|
121
|
+
* Refreshes the earn eligibility status for the current account.
|
123
122
|
* Updates the eligibility status in the controller state based on the location and address blocklist for compliance.
|
124
123
|
*
|
124
|
+
* Note: Pooled-staking and Lending used the same result since there isn't a need to split these up right now.
|
125
|
+
*
|
125
126
|
* @param options - Optional arguments
|
126
|
-
* @param [options.address] - Address to refresh
|
127
|
+
* @param [options.address] - Address to refresh earn eligibility for (optional).
|
127
128
|
* @returns A promise that resolves when the eligibility status has been updated
|
128
129
|
*/
|
129
|
-
|
130
|
+
refreshEarnEligibility({ address, }?: RefreshEarnEligibilityOptions): Promise<void>;
|
130
131
|
/**
|
131
132
|
* Refreshes pooled staking vault metadata for the current chain.
|
132
133
|
* Updates the vault metadata in the controller state including APY, capacity,
|
133
134
|
* fee percentage, total assets, and vault address.
|
134
135
|
*
|
135
|
-
* @param chainId - The chain id to refresh pooled staking vault metadata for (optional).
|
136
136
|
* @returns A promise that resolves when the vault metadata has been updated
|
137
137
|
*/
|
138
|
-
refreshPooledStakingVaultMetadata(
|
138
|
+
refreshPooledStakingVaultMetadata(): Promise<void>;
|
139
139
|
/**
|
140
140
|
* Refreshes pooled staking vault daily apys for the current chain.
|
141
141
|
* Updates the pooled staking vault daily apys controller state.
|
142
142
|
*
|
143
|
-
* @param chainId - The chain id to refresh pooled staking vault daily apys for (optional).
|
144
143
|
* @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).
|
145
144
|
* @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').
|
146
145
|
* @returns A promise that resolves when the pooled staking vault daily apys have been updated.
|
147
146
|
*/
|
148
|
-
refreshPooledStakingVaultDailyApys(
|
147
|
+
refreshPooledStakingVaultDailyApys(days?: number, order?: 'asc' | 'desc'): Promise<void>;
|
149
148
|
/**
|
150
149
|
* Refreshes pooled staking vault apy averages for the current chain.
|
151
150
|
* Updates the pooled staking vault apy averages controller state.
|
152
151
|
*
|
153
|
-
* @param chainId - The chain id to refresh pooled staking vault apy averages for (optional).
|
154
152
|
* @returns A promise that resolves when the pooled staking vault apy averages have been updated.
|
155
153
|
*/
|
156
|
-
refreshPooledStakingVaultApyAverages(
|
154
|
+
refreshPooledStakingVaultApyAverages(): Promise<void>;
|
157
155
|
/**
|
158
156
|
* Refreshes all pooled staking related data including stakes, eligibility, and vault data.
|
159
157
|
* This method allows partial success, meaning some data may update while other requests fail.
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"EarnController.d.mts","sourceRoot":"","sources":["../src/EarnController.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,0CAA0C,EAC1C,4CAA4C,EAC7C,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAE3D,OAAO,KAAK,EACV,2CAA2C,EAC3C,+BAA+B,EAC/B,iCAAiC,EAClC,qCAAqC;AACtC,OAAO,
|
1
|
+
{"version":3,"file":"EarnController.d.mts","sourceRoot":"","sources":["../src/EarnController.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,0CAA0C,EAC1C,4CAA4C,E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) || function (
|
|
9
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
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
11
11
|
};
|
12
|
-
var _EarnController_instances, _EarnController_earnSDK, _EarnController_selectedNetworkClientId, _EarnController_earnApiService, _EarnController_addTransactionFn, _EarnController_supportedPooledStakingChains, _EarnController_env, _EarnController_initializeSDK, _EarnController_getCurrentAccount, _EarnController_getCurrentChainId;
|
12
|
+
var _EarnController_instances, _EarnController_earnSDK, _EarnController_selectedNetworkClientId, _EarnController_earnApiService, _EarnController_addTransactionFn, _EarnController_supportedPooledStakingChains, _EarnController_env, _EarnController_initializeSDK, _EarnController_getCurrentAccount, _EarnController_getCurrentChainId, _EarnController_getActivePooledStakingChainId;
|
13
13
|
import { Web3Provider } from "@ethersproject/providers";
|
14
14
|
import { BaseController } from "@metamask/base-controller";
|
15
15
|
import { convertHexToDecimal, toHex } from "@metamask/controller-utils";
|
16
|
-
import { EarnSdk, EarnApiService,
|
17
|
-
import { TransactionType } from "@metamask/transaction-controller";
|
16
|
+
import { EarnSdk, EarnApiService, isSupportedLendingChain, EarnEnvironments } from "@metamask/stake-sdk";
|
17
|
+
import { TransactionType, CHAIN_IDS } from "@metamask/transaction-controller";
|
18
|
+
import { HOODI_TESTNET_CHAIN_ID_HEX } from "./constants.mjs";
|
18
19
|
export const controllerName = 'EarnController';
|
19
20
|
const stakingTransactionTypes = new Set([
|
20
21
|
TransactionType.stakingDeposit,
|
@@ -149,7 +150,10 @@ export class EarnController extends BaseController {
|
|
149
150
|
// temporary array of supported chains
|
150
151
|
// TODO: remove this once we export a supported chains list from the sdk
|
151
152
|
// from sdk or api to get lending and pooled staking chains
|
152
|
-
__classPrivateFieldSet(this, _EarnController_supportedPooledStakingChains, [
|
153
|
+
__classPrivateFieldSet(this, _EarnController_supportedPooledStakingChains, [
|
154
|
+
CHAIN_IDS.MAINNET,
|
155
|
+
HOODI_TESTNET_CHAIN_ID_HEX,
|
156
|
+
], "f");
|
153
157
|
__classPrivateFieldSet(this, _EarnController_addTransactionFn, addTransactionFn, "f");
|
154
158
|
__classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this).catch(console.error);
|
155
159
|
this.refreshPooledStakingData().catch(console.error);
|
@@ -160,15 +164,11 @@ export class EarnController extends BaseController {
|
|
160
164
|
this.messagingSystem.subscribe('NetworkController:stateChange', (networkControllerState) => {
|
161
165
|
if (networkControllerState.selectedNetworkClientId !==
|
162
166
|
__classPrivateFieldGet(this, _EarnController_selectedNetworkClientId, "f")) {
|
163
|
-
const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this, networkControllerState.selectedNetworkClientId);
|
164
167
|
__classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_initializeSDK).call(this, networkControllerState.selectedNetworkClientId).catch(console.error);
|
165
|
-
|
166
|
-
|
167
|
-
|
168
|
-
|
169
|
-
this.refreshPooledStakingVaultApyAverages(chainId).catch(console.error);
|
170
|
-
this.refreshPooledStakes({ chainId }).catch(console.error);
|
171
|
-
}
|
168
|
+
this.refreshPooledStakingVaultMetadata().catch(console.error);
|
169
|
+
this.refreshPooledStakingVaultDailyApys().catch(console.error);
|
170
|
+
this.refreshPooledStakingVaultApyAverages().catch(console.error);
|
171
|
+
this.refreshPooledStakes().catch(console.error);
|
172
172
|
// refresh lending data for all chains
|
173
173
|
this.refreshLendingMarkets().catch(console.error);
|
174
174
|
this.refreshLendingPositions().catch(console.error);
|
@@ -185,7 +185,7 @@ export class EarnController extends BaseController {
|
|
185
185
|
*/
|
186
186
|
// TODO: temp solution, this will refresh lending eligibility also
|
187
187
|
// we could have a more general check, as what is happening is a compliance address check
|
188
|
-
this.
|
188
|
+
this.refreshEarnEligibility({ address }).catch(console.error);
|
189
189
|
this.refreshPooledStakes({ address }).catch(console.error);
|
190
190
|
this.refreshLendingPositions({ address }).catch(console.error);
|
191
191
|
});
|
@@ -218,20 +218,18 @@ export class EarnController extends BaseController {
|
|
218
218
|
* @param options - Optional arguments
|
219
219
|
* @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).
|
220
220
|
* @param [options.address] - The address to refresh pooled stakes for (optional).
|
221
|
-
* @param [options.chainId] - The chain id to refresh pooled stakes for (optional).
|
222
221
|
* @returns A promise that resolves when the stakes data has been updated
|
223
222
|
*/
|
224
|
-
async refreshPooledStakes({ resetCache = false, address,
|
223
|
+
async refreshPooledStakes({ resetCache = false, address, } = {}) {
|
225
224
|
const addressToUse = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
|
226
225
|
if (!addressToUse) {
|
227
226
|
return;
|
228
227
|
}
|
229
|
-
const
|
230
|
-
const { accounts, exchangeRate } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakes([addressToUse],
|
228
|
+
const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getActivePooledStakingChainId).call(this);
|
229
|
+
const { accounts, exchangeRate } = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getPooledStakes([addressToUse], chainId, resetCache);
|
231
230
|
this.update((state) => {
|
232
|
-
const chainState = state.pooled_staking[
|
233
|
-
|
234
|
-
state.pooled_staking[chainIdToUse] = {
|
231
|
+
const chainState = state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;
|
232
|
+
state.pooled_staking[chainId] = {
|
235
233
|
...chainState,
|
236
234
|
pooledStakes: accounts[0],
|
237
235
|
exchangeRate,
|
@@ -239,14 +237,16 @@ export class EarnController extends BaseController {
|
|
239
237
|
});
|
240
238
|
}
|
241
239
|
/**
|
242
|
-
* Refreshes the
|
240
|
+
* Refreshes the earn eligibility status for the current account.
|
243
241
|
* Updates the eligibility status in the controller state based on the location and address blocklist for compliance.
|
244
242
|
*
|
243
|
+
* Note: Pooled-staking and Lending used the same result since there isn't a need to split these up right now.
|
244
|
+
*
|
245
245
|
* @param options - Optional arguments
|
246
|
-
* @param [options.address] - Address to refresh
|
246
|
+
* @param [options.address] - Address to refresh earn eligibility for (optional).
|
247
247
|
* @returns A promise that resolves when the eligibility status has been updated
|
248
248
|
*/
|
249
|
-
async
|
249
|
+
async refreshEarnEligibility({ address, } = {}) {
|
250
250
|
const addressToCheck = address ?? __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentAccount).call(this)?.address;
|
251
251
|
if (!addressToCheck) {
|
252
252
|
return;
|
@@ -264,16 +264,14 @@ export class EarnController extends BaseController {
|
|
264
264
|
* Updates the vault metadata in the controller state including APY, capacity,
|
265
265
|
* fee percentage, total assets, and vault address.
|
266
266
|
*
|
267
|
-
* @param chainId - The chain id to refresh pooled staking vault metadata for (optional).
|
268
267
|
* @returns A promise that resolves when the vault metadata has been updated
|
269
268
|
*/
|
270
|
-
async refreshPooledStakingVaultMetadata(
|
271
|
-
const
|
272
|
-
const vaultMetadata = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultData(
|
269
|
+
async refreshPooledStakingVaultMetadata() {
|
270
|
+
const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getActivePooledStakingChainId).call(this);
|
271
|
+
const vaultMetadata = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultData(chainId);
|
273
272
|
this.update((state) => {
|
274
|
-
const chainState = state.pooled_staking[
|
275
|
-
|
276
|
-
state.pooled_staking[chainIdToUse] = {
|
273
|
+
const chainState = state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;
|
274
|
+
state.pooled_staking[chainId] = {
|
277
275
|
...chainState,
|
278
276
|
vaultMetadata,
|
279
277
|
};
|
@@ -283,18 +281,16 @@ export class EarnController extends BaseController {
|
|
283
281
|
* Refreshes pooled staking vault daily apys for the current chain.
|
284
282
|
* Updates the pooled staking vault daily apys controller state.
|
285
283
|
*
|
286
|
-
* @param chainId - The chain id to refresh pooled staking vault daily apys for (optional).
|
287
284
|
* @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).
|
288
285
|
* @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').
|
289
286
|
* @returns A promise that resolves when the pooled staking vault daily apys have been updated.
|
290
287
|
*/
|
291
|
-
async refreshPooledStakingVaultDailyApys(
|
292
|
-
const
|
293
|
-
const vaultDailyApys = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultDailyApys(
|
288
|
+
async refreshPooledStakingVaultDailyApys(days = 365, order = 'desc') {
|
289
|
+
const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getActivePooledStakingChainId).call(this);
|
290
|
+
const vaultDailyApys = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultDailyApys(chainId, days, order);
|
294
291
|
this.update((state) => {
|
295
|
-
const chainState = state.pooled_staking[
|
296
|
-
|
297
|
-
state.pooled_staking[chainIdToUse] = {
|
292
|
+
const chainState = state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;
|
293
|
+
state.pooled_staking[chainId] = {
|
298
294
|
...chainState,
|
299
295
|
vaultDailyApys,
|
300
296
|
};
|
@@ -304,16 +300,14 @@ export class EarnController extends BaseController {
|
|
304
300
|
* Refreshes pooled staking vault apy averages for the current chain.
|
305
301
|
* Updates the pooled staking vault apy averages controller state.
|
306
302
|
*
|
307
|
-
* @param chainId - The chain id to refresh pooled staking vault apy averages for (optional).
|
308
303
|
* @returns A promise that resolves when the pooled staking vault apy averages have been updated.
|
309
304
|
*/
|
310
|
-
async refreshPooledStakingVaultApyAverages(
|
311
|
-
const
|
312
|
-
const vaultApyAverages = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultApyAverages(
|
305
|
+
async refreshPooledStakingVaultApyAverages() {
|
306
|
+
const chainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getActivePooledStakingChainId).call(this);
|
307
|
+
const vaultApyAverages = await __classPrivateFieldGet(this, _EarnController_earnApiService, "f").pooledStaking.getVaultApyAverages(chainId);
|
313
308
|
this.update((state) => {
|
314
|
-
const chainState = state.pooled_staking[
|
315
|
-
|
316
|
-
state.pooled_staking[chainIdToUse] = {
|
309
|
+
const chainState = state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;
|
310
|
+
state.pooled_staking[chainId] = {
|
317
311
|
...chainState,
|
318
312
|
vaultApyAverages,
|
319
313
|
};
|
@@ -332,25 +326,23 @@ export class EarnController extends BaseController {
|
|
332
326
|
*/
|
333
327
|
async refreshPooledStakingData({ resetCache, address, } = {}) {
|
334
328
|
const errors = [];
|
335
|
-
|
336
|
-
|
337
|
-
|
338
|
-
|
339
|
-
|
340
|
-
|
341
|
-
|
342
|
-
|
343
|
-
|
344
|
-
|
345
|
-
|
346
|
-
|
347
|
-
|
348
|
-
|
349
|
-
|
350
|
-
|
351
|
-
|
352
|
-
]);
|
353
|
-
}
|
329
|
+
await Promise.all([
|
330
|
+
this.refreshPooledStakes({ resetCache, address }).catch((error) => {
|
331
|
+
errors.push(error);
|
332
|
+
}),
|
333
|
+
this.refreshEarnEligibility({ address }).catch((error) => {
|
334
|
+
errors.push(error);
|
335
|
+
}),
|
336
|
+
this.refreshPooledStakingVaultMetadata().catch((error) => {
|
337
|
+
errors.push(error);
|
338
|
+
}),
|
339
|
+
this.refreshPooledStakingVaultDailyApys().catch((error) => {
|
340
|
+
errors.push(error);
|
341
|
+
}),
|
342
|
+
this.refreshPooledStakingVaultApyAverages().catch((error) => {
|
343
|
+
errors.push(error);
|
344
|
+
}),
|
345
|
+
]);
|
354
346
|
if (errors.length > 0) {
|
355
347
|
throw new Error(`Failed to refresh some staking data: ${errors
|
356
348
|
.map((e) => e.message)
|
@@ -670,5 +662,13 @@ async function _EarnController_initializeSDK(networkClientId) {
|
|
670
662
|
.selectedNetworkClientId;
|
671
663
|
const { configuration: { chainId }, } = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientIdToUse);
|
672
664
|
return convertHexToDecimal(chainId);
|
665
|
+
}, _EarnController_getActivePooledStakingChainId = function _EarnController_getActivePooledStakingChainId() {
|
666
|
+
const activeChainId = __classPrivateFieldGet(this, _EarnController_instances, "m", _EarnController_getCurrentChainId).call(this);
|
667
|
+
if (!activeChainId ||
|
668
|
+
!__classPrivateFieldGet(this, _EarnController_supportedPooledStakingChains, "f").includes(toHex(activeChainId))) {
|
669
|
+
// Fallback to Ethereum Mainnet if chainId is not supported.
|
670
|
+
return convertHexToDecimal(CHAIN_IDS.MAINNET);
|
671
|
+
}
|
672
|
+
return activeChainId;
|
673
673
|
};
|
674
674
|
//# sourceMappingURL=EarnController.mjs.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"EarnController.mjs","sourceRoot":"","sources":["../src/EarnController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,YAAY,EAAE,iCAAiC;AAWxD,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,mCAAmC;AAMxE,OAAO,EACL,OAAO,EACP,cAAc,EACd,6BAA6B,EAC7B,uBAAuB,EAUvB,gBAAgB,EACjB,4BAA4B;AAC7B,OAAO,EAEL,eAAe,EAEhB,yCAAyC;AAU1C,MAAM,CAAC,MAAM,cAAc,GAAG,gBAAgB,CAAC;AA4C/C,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,eAAe,CAAC,cAAc;IAC9B,eAAe,CAAC,cAAc;IAC9B,eAAe,CAAC,YAAY;CAC7B,CAAC,CAAC;AAMH,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,eAAe,CAAC,cAAc;IAC9B,eAAe,CAAC,eAAe;CAChC,CAAC,CAAC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AAC;IAQC,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;AAC5E,CAAC,iFAQkB,eAAwB;IACzC,MAAM,oBAAoB,GACxB,eAAe;QACf,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,4BAA4B,CAAC;aACpD,uBAAuB,CAAC;IAE7B,MAAM,EACJ,aAAa,EAAE,EAAE,OAAO,EAAE,GAC3B,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3B,wCAAwC,EACxC,oBAAoB,CACrB,CAAC;IACF,OAAO,mBAAmB,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC","sourcesContent":["import { Web3Provider } from '@ethersproject/providers';\nimport type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { convertHexToDecimal, toHex } from '@metamask/controller-utils';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport {\n EarnSdk,\n EarnApiService,\n isSupportedPooledStakingChain,\n isSupportedLendingChain,\n type LendingMarket,\n type PooledStake,\n type EarnSdkConfig,\n type VaultData,\n type VaultDailyApy,\n type VaultApyAverages,\n type LendingPosition,\n type GasLimitParams,\n type HistoricLendingMarketApys,\n EarnEnvironments,\n} from '@metamask/stake-sdk';\nimport {\n type TransactionController,\n TransactionType,\n type TransactionControllerTransactionConfirmedEvent,\n} from '@metamask/transaction-controller';\n\nimport type {\n RefreshLendingEligibilityOptions,\n RefreshLendingPositionsOptions,\n RefreshPooledStakesOptions,\n RefreshPooledStakingDataOptions,\n RefreshStakingEligibilityOptions,\n} from './types';\n\nexport const controllerName = 'EarnController';\n\nexport type PooledStakingState = {\n [chainId: number]: {\n pooledStakes: PooledStake;\n exchangeRate: string;\n vaultMetadata: VaultData;\n vaultDailyApys: VaultDailyApy[];\n vaultApyAverages: VaultApyAverages;\n };\n isEligible: boolean;\n};\n\nexport type LendingPositionWithMarket = LendingPosition & {\n marketId: string;\n marketAddress: string;\n protocol: string;\n};\n\n// extends LendingPosition to include a marketId, marketAddress, and protocol reference\nexport type LendingPositionWithMarketReference = Omit<\n LendingPosition,\n 'market'\n> & {\n marketId: string;\n marketAddress: string;\n protocol: string;\n};\n\nexport type LendingMarketWithPosition = LendingMarket & {\n position: LendingPositionWithMarketReference;\n};\n\nexport type LendingState = {\n markets: LendingMarket[]; // list of markets\n positions: LendingPositionWithMarketReference[]; // list of positions\n isEligible: boolean;\n};\n\ntype StakingTransactionTypes =\n | TransactionType.stakingDeposit\n | TransactionType.stakingUnstake\n | TransactionType.stakingClaim;\n\nconst stakingTransactionTypes = new Set<StakingTransactionTypes>([\n TransactionType.stakingDeposit,\n TransactionType.stakingUnstake,\n TransactionType.stakingClaim,\n]);\n\ntype LendingTransactionTypes =\n | TransactionType.lendingDeposit\n | TransactionType.lendingWithdraw;\n\nconst lendingTransactionTypes = new Set<LendingTransactionTypes>([\n TransactionType.lendingDeposit,\n TransactionType.lendingWithdraw,\n]);\n\n/**\n * Metadata for the EarnController.\n */\nconst earnControllerMetadata: StateMetadata<EarnControllerState> = {\n pooled_staking: {\n persist: true,\n anonymous: false,\n },\n lending: {\n persist: true,\n anonymous: false,\n },\n lastUpdated: {\n persist: false,\n anonymous: true,\n },\n};\n\n// === State Types ===\nexport type EarnControllerState = {\n pooled_staking: PooledStakingState;\n lending: LendingState;\n lastUpdated: number;\n};\n\n// === Default State ===\nexport const DEFAULT_LENDING_MARKET: LendingMarket = {\n id: '',\n chainId: 0,\n protocol: '' as LendingMarket['protocol'],\n name: '',\n address: '',\n tvlUnderlying: '0',\n netSupplyRate: 0,\n totalSupplyRate: 0,\n underlying: {\n address: '',\n chainId: 0,\n },\n outputToken: {\n address: '',\n chainId: 0,\n },\n rewards: [\n {\n token: {\n address: '',\n chainId: 0,\n },\n rate: 0,\n },\n ],\n};\n\nexport const DEFAULT_LENDING_POSITION: LendingPositionWithMarketReference = {\n id: '',\n chainId: 0,\n assets: '0',\n marketId: '',\n marketAddress: '',\n protocol: '',\n};\n\nexport const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES: VaultApyAverages = {\n oneDay: '0',\n oneWeek: '0',\n oneMonth: '0',\n threeMonths: '0',\n sixMonths: '0',\n oneYear: '0',\n};\n\nexport const DEFAULT_POOLED_STAKING_CHAIN_STATE = {\n pooledStakes: {\n account: '',\n lifetimeRewards: '0',\n assets: '0',\n exitRequests: [],\n },\n exchangeRate: '1',\n vaultMetadata: {\n apy: '0',\n capacity: '0',\n feePercent: 0,\n totalAssets: '0',\n vaultAddress: '0x0000000000000000000000000000000000000000',\n },\n vaultDailyApys: [],\n vaultApyAverages: DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES,\n};\n\n/**\n * Gets the default state for the EarnController.\n *\n * @returns The default EarnController state.\n */\nexport function getDefaultEarnControllerState(): EarnControllerState {\n return {\n pooled_staking: {\n isEligible: false,\n },\n lending: {\n markets: [DEFAULT_LENDING_MARKET],\n positions: [DEFAULT_LENDING_POSITION],\n isEligible: false,\n },\n lastUpdated: 0,\n };\n}\n\n// === MESSENGER ===\n\n/**\n * The action which can be used to retrieve the state of the EarnController.\n */\nexport type EarnControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n EarnControllerState\n>;\n\n/**\n * All actions that EarnController registers, to be called externally.\n */\nexport type EarnControllerActions = EarnControllerGetStateAction;\n\n/**\n * All actions that EarnController calls internally.\n */\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\n/**\n * The event that EarnController publishes when updating state.\n */\nexport type EarnControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n EarnControllerState\n>;\n\n/**\n * All events that EarnController publishes, to be subscribed to externally.\n */\nexport type EarnControllerEvents = EarnControllerStateChangeEvent;\n\n/**\n * All events that EarnController subscribes to internally.\n */\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | NetworkControllerStateChangeEvent\n | TransactionControllerTransactionConfirmedEvent;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * EarnController.\n */\nexport type EarnControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n EarnControllerActions | AllowedActions,\n EarnControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * EarnController manages DeFi earning opportunities across different protocols and chains.\n */\nexport class EarnController extends BaseController<\n typeof controllerName,\n EarnControllerState,\n EarnControllerMessenger\n> {\n #earnSDK: EarnSdk | null = null;\n\n #selectedNetworkClientId?: string;\n\n readonly #earnApiService: EarnApiService;\n\n readonly #addTransactionFn: typeof TransactionController.prototype.addTransaction;\n\n readonly #supportedPooledStakingChains: number[];\n\n readonly #env: EarnEnvironments;\n\n constructor({\n messenger,\n state = {},\n addTransactionFn,\n env = EarnEnvironments.PROD,\n }: {\n messenger: EarnControllerMessenger;\n state?: Partial<EarnControllerState>;\n addTransactionFn: typeof TransactionController.prototype.addTransaction;\n env?: EarnEnvironments;\n }) {\n super({\n name: controllerName,\n metadata: earnControllerMetadata,\n messenger,\n state: {\n ...getDefaultEarnControllerState(),\n ...state,\n },\n });\n\n this.#env = env;\n\n this.#earnApiService = new EarnApiService(this.#env);\n\n // temporary array of supported chains\n // TODO: remove this once we export a supported chains list from the sdk\n // from sdk or api to get lending and pooled staking chains\n this.#supportedPooledStakingChains = [1, 560048];\n\n this.#addTransactionFn = addTransactionFn;\n\n this.#initializeSDK().catch(console.error);\n this.refreshPooledStakingData().catch(console.error);\n this.refreshLendingData().catch(console.error);\n\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n this.#selectedNetworkClientId = selectedNetworkClientId;\n\n // Listen for network changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n (networkControllerState) => {\n if (\n networkControllerState.selectedNetworkClientId !==\n this.#selectedNetworkClientId\n ) {\n const chainId = this.#getCurrentChainId(\n networkControllerState.selectedNetworkClientId,\n );\n this.#initializeSDK(\n networkControllerState.selectedNetworkClientId,\n ).catch(console.error);\n if (isSupportedPooledStakingChain(chainId)) {\n // only refresh pool staking data for the chain we are switching to\n this.refreshPooledStakingVaultMetadata(chainId).catch(\n console.error,\n );\n this.refreshPooledStakingVaultDailyApys(chainId).catch(\n console.error,\n );\n this.refreshPooledStakingVaultApyAverages(chainId).catch(\n console.error,\n );\n this.refreshPooledStakes({ chainId }).catch(console.error);\n }\n // refresh lending data for all chains\n this.refreshLendingMarkets().catch(console.error);\n this.refreshLendingPositions().catch(console.error);\n }\n this.#selectedNetworkClientId =\n networkControllerState.selectedNetworkClientId;\n },\n );\n\n // Listen for account changes\n this.messagingSystem.subscribe(\n 'AccountsController:selectedAccountChange',\n (account) => {\n const address = account?.address;\n /**\n * TEMP: There's a race condition where the account state isn't updated immediately.\n * Until this has been fixed, we rely on the event payload for the latest account instead of #getCurrentAccount().\n * Issue: https://github.com/MetaMask/accounts-planning/issues/887\n */\n\n // TODO: temp solution, this will refresh lending eligibility also\n // we could have a more general check, as what is happening is a compliance address check\n this.refreshStakingEligibility({ address }).catch(console.error);\n\n this.refreshPooledStakes({ address }).catch(console.error);\n this.refreshLendingPositions({ address }).catch(console.error);\n },\n );\n\n // Listen for confirmed staking transactions\n this.messagingSystem.subscribe(\n 'TransactionController:transactionConfirmed',\n (transactionMeta) => {\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n const { type, originalType } = transactionMeta;\n\n const isStakingTransaction =\n stakingTransactionTypes.has(type as StakingTransactionTypes) ||\n stakingTransactionTypes.has(originalType as StakingTransactionTypes);\n\n const isLendingTransaction =\n lendingTransactionTypes.has(type as LendingTransactionTypes) ||\n lendingTransactionTypes.has(originalType as LendingTransactionTypes);\n\n const sender = transactionMeta.txParams.from;\n\n if (isStakingTransaction) {\n this.refreshPooledStakes({ resetCache: true, address: sender }).catch(\n console.error,\n );\n }\n if (isLendingTransaction) {\n this.refreshLendingPositions({ address: sender }).catch(\n console.error,\n );\n }\n },\n );\n }\n\n /**\n * Initializes the Earn SDK.\n *\n * @param networkClientId - The network client id to initialize the Earn SDK for (optional).\n */\n async #initializeSDK(networkClientId?: string) {\n const { selectedNetworkClientId } = networkClientId\n ? { selectedNetworkClientId: networkClientId }\n : this.messagingSystem.call('NetworkController:getState');\n\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n\n if (!networkClient?.provider) {\n this.#earnSDK = null;\n return;\n }\n\n const provider = new Web3Provider(networkClient.provider);\n const { chainId } = networkClient.configuration;\n\n // Initialize appropriate contracts based on chainId\n const config: EarnSdkConfig = {\n chainId: convertHexToDecimal(chainId),\n env: this.#env,\n };\n\n try {\n this.#earnSDK = await EarnSdk.create(provider, config);\n } catch (error) {\n this.#earnSDK = null;\n // Only log unexpected errors, not unsupported chain errors\n if (\n !(\n error instanceof Error &&\n error.message.includes('Unsupported chainId')\n )\n ) {\n console.error('Earn SDK initialization failed:', error);\n }\n }\n }\n\n /**\n * Gets the current account.\n *\n * @returns The current account.\n */\n #getCurrentAccount() {\n return this.messagingSystem.call('AccountsController:getSelectedAccount');\n }\n\n /**\n * Gets the current chain id.\n *\n * @param networkClientId - The network client id to get the chain id for (optional).\n * @returns The current chain id in decimal.\n */\n #getCurrentChainId(networkClientId?: string): number {\n const networkClientIdToUse =\n networkClientId ??\n this.messagingSystem.call('NetworkController:getState')\n .selectedNetworkClientId;\n\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientIdToUse,\n );\n return convertHexToDecimal(chainId);\n }\n\n /**\n * Refreshes the pooled stakes data for the current account.\n * Fetches updated stake information including lifetime rewards, assets, and exit requests\n * from the staking API service and updates the state.\n *\n * @param options - Optional arguments\n * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).\n * @param [options.address] - The address to refresh pooled stakes for (optional).\n * @param [options.chainId] - The chain id to refresh pooled stakes for (optional).\n * @returns A promise that resolves when the stakes data has been updated\n */\n async refreshPooledStakes({\n resetCache = false,\n address,\n chainId,\n }: RefreshPooledStakesOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToUse) {\n return;\n }\n\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n\n const { accounts, exchangeRate } =\n await this.#earnApiService.pooledStaking.getPooledStakes(\n [addressToUse],\n chainIdToUse,\n resetCache,\n );\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainIdToUse] ??\n DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainIdToUse] = {\n ...chainState,\n pooledStakes: accounts[0],\n exchangeRate,\n };\n });\n }\n\n /**\n * Refreshes the staking eligibility status for the current account.\n * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.\n *\n * @param options - Optional arguments\n * @param [options.address] - Address to refresh staking eligibility for (optional).\n * @returns A promise that resolves when the eligibility status has been updated\n */\n async refreshStakingEligibility({\n address,\n }: RefreshStakingEligibilityOptions = {}): Promise<void> {\n const addressToCheck = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToCheck) {\n return;\n }\n\n const { eligible: isEligible } =\n await this.#earnApiService.pooledStaking.getPooledStakingEligibility([\n addressToCheck,\n ]);\n\n this.update((state) => {\n state.pooled_staking.isEligible = isEligible;\n state.lending.isEligible = isEligible;\n });\n }\n\n /**\n * Refreshes pooled staking vault metadata for the current chain.\n * Updates the vault metadata in the controller state including APY, capacity,\n * fee percentage, total assets, and vault address.\n *\n * @param chainId - The chain id to refresh pooled staking vault metadata for (optional).\n * @returns A promise that resolves when the vault metadata has been updated\n */\n async refreshPooledStakingVaultMetadata(chainId?: number): Promise<void> {\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n const vaultMetadata =\n await this.#earnApiService.pooledStaking.getVaultData(chainIdToUse);\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainIdToUse] ??\n DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainIdToUse] = {\n ...chainState,\n vaultMetadata,\n };\n });\n }\n\n /**\n * Refreshes pooled staking vault daily apys for the current chain.\n * Updates the pooled staking vault daily apys controller state.\n *\n * @param chainId - The chain id to refresh pooled staking vault daily apys for (optional).\n * @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).\n * @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').\n * @returns A promise that resolves when the pooled staking vault daily apys have been updated.\n */\n async refreshPooledStakingVaultDailyApys(\n chainId?: number,\n days = 365,\n order: 'asc' | 'desc' = 'desc',\n ): Promise<void> {\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n const vaultDailyApys =\n await this.#earnApiService.pooledStaking.getVaultDailyApys(\n chainIdToUse,\n days,\n order,\n );\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainIdToUse] ??\n DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainIdToUse] = {\n ...chainState,\n vaultDailyApys,\n };\n });\n }\n\n /**\n * Refreshes pooled staking vault apy averages for the current chain.\n * Updates the pooled staking vault apy averages controller state.\n *\n * @param chainId - The chain id to refresh pooled staking vault apy averages for (optional).\n * @returns A promise that resolves when the pooled staking vault apy averages have been updated.\n */\n async refreshPooledStakingVaultApyAverages(chainId?: number) {\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n const vaultApyAverages =\n await this.#earnApiService.pooledStaking.getVaultApyAverages(\n chainIdToUse,\n );\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainIdToUse] ??\n DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainIdToUse] = {\n ...chainState,\n vaultApyAverages,\n };\n });\n }\n\n /**\n * Refreshes all pooled staking related data including stakes, eligibility, and vault data.\n * This method allows partial success, meaning some data may update while other requests fail.\n * All errors are collected and thrown as a single error message.\n *\n * @param options - Optional arguments\n * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).\n * @param [options.address] - The address to refresh pooled stakes for (optional).\n * @returns A promise that resolves when all possible data has been updated\n * @throws {Error} If any of the refresh operations fail, with concatenated error messages\n */\n async refreshPooledStakingData({\n resetCache,\n address,\n }: RefreshPooledStakingDataOptions = {}): Promise<void> {\n const errors: Error[] = [];\n for (const chainId of this.#supportedPooledStakingChains) {\n await Promise.all([\n this.refreshPooledStakes({ resetCache, address, chainId }).catch(\n (error) => {\n errors.push(error);\n },\n ),\n this.refreshStakingEligibility({ address }).catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultMetadata(chainId).catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultDailyApys(chainId).catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultApyAverages(chainId).catch((error) => {\n errors.push(error);\n }),\n ]);\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Failed to refresh some staking data: ${errors\n .map((e) => e.message)\n .join(', ')}`,\n );\n }\n }\n\n /**\n * Refreshes the lending markets data for all chains.\n * Updates the lending markets in the controller state.\n *\n * @returns A promise that resolves when the lending markets have been updated\n */\n async refreshLendingMarkets(): Promise<void> {\n const markets = await this.#earnApiService.lending.getMarkets();\n\n this.update((state) => {\n state.lending.markets = markets;\n });\n }\n\n /**\n * Refreshes the lending positions for the current account.\n * Updates the lending positions in the controller state.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to refresh lending positions for (optional).\n * @returns A promise that resolves when the lending positions have been updated\n */\n async refreshLendingPositions({\n address,\n }: RefreshLendingPositionsOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToUse) {\n return;\n }\n\n // linter complaining about this not being a promise, but it is\n // TODO: figure out why this is not seen as a promise\n const positions = await Promise.resolve(\n this.#earnApiService.lending.getPositions(addressToUse),\n );\n\n this.update((state) => {\n state.lending.positions = positions.map((position) => ({\n ...position,\n marketId: position.market.id,\n marketAddress: position.market.address,\n protocol: position.market.protocol,\n }));\n });\n }\n\n /**\n * Refreshes the lending eligibility status for the current account.\n * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to refresh lending eligibility for (optional).\n * @returns A promise that resolves when the eligibility status has been updated\n */\n async refreshLendingEligibility({\n address,\n }: RefreshLendingEligibilityOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n // TODO: this is a temporary solution to refresh lending eligibility as\n // the eligibility check is not yet implemented for lending\n // this check will check the address against the same blocklist as the\n // staking eligibility check\n\n if (!addressToUse) {\n return;\n }\n\n const { eligible: isEligible } =\n await this.#earnApiService.pooledStaking.getPooledStakingEligibility([\n addressToUse,\n ]);\n\n this.update((state) => {\n state.lending.isEligible = isEligible;\n state.pooled_staking.isEligible = isEligible;\n });\n }\n\n /**\n * Refreshes all lending related data including markets, positions, and eligibility.\n * This method allows partial success, meaning some data may update while other requests fail.\n * All errors are collected and thrown as a single error message.\n *\n * @returns A promise that resolves when all possible data has been updated\n * @throws {Error} If any of the refresh operations fail, with concatenated error messages\n */\n async refreshLendingData(): Promise<void> {\n const errors: Error[] = [];\n\n await Promise.all([\n this.refreshLendingMarkets().catch((error) => {\n errors.push(error);\n }),\n this.refreshLendingPositions().catch((error) => {\n errors.push(error);\n }),\n this.refreshLendingEligibility().catch((error) => {\n errors.push(error);\n }),\n ]);\n\n if (errors.length > 0) {\n throw new Error(\n `Failed to refresh some lending data: ${errors\n .map((e) => e.message)\n .join(', ')}`,\n );\n }\n }\n\n /**\n * Gets the lending position history for the current account.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to get lending position history for (optional).\n * @param [options.chainId] - The chain id to get lending position history for (optional).\n * @param [options.positionId] - The position id to get lending position history for.\n * @param [options.marketId] - The market id to get lending position history for.\n * @param [options.marketAddress] - The market address to get lending position history for.\n * @param [options.protocol] - The protocol to get lending position history for.\n * @param [options.days] - The number of days to get lending position history for (optional).\n * @returns A promise that resolves when the lending position history has been updated\n */\n getLendingPositionHistory({\n address,\n chainId,\n positionId,\n marketId,\n marketAddress,\n protocol,\n days = 730,\n }: {\n address?: string;\n chainId?: number;\n positionId: string;\n marketId: string;\n marketAddress: string;\n protocol: string;\n days?: number;\n }) {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n\n if (!addressToUse || !isSupportedLendingChain(chainIdToUse)) {\n return [];\n }\n\n return this.#earnApiService.lending.getPositionHistory(\n addressToUse,\n chainIdToUse,\n protocol,\n marketId,\n marketAddress,\n positionId,\n days,\n );\n }\n\n /**\n * Gets the lending market daily apys and averages for the current chain.\n *\n * @param options - Optional arguments\n * @param [options.chainId] - The chain id to get lending market daily apys and averages for (optional).\n * @param [options.protocol] - The protocol to get lending market daily apys and averages for.\n * @param [options.marketId] - The market id to get lending market daily apys and averages for.\n * @param [options.days] - The number of days to get lending market daily apys and averages for (optional).\n * @returns A promise that resolves when the lending market daily apys and averages have been updated\n */\n getLendingMarketDailyApysAndAverages({\n chainId,\n protocol,\n marketId,\n days = 365,\n }: {\n chainId?: number;\n protocol: string;\n marketId: string;\n days?: number;\n }): Promise<HistoricLendingMarketApys> | undefined {\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n\n if (!isSupportedLendingChain(chainIdToUse)) {\n return undefined;\n }\n\n return this.#earnApiService.lending.getHistoricMarketApys(\n chainIdToUse,\n protocol,\n marketId,\n days,\n );\n }\n\n /**\n * Executes a lending deposit transaction.\n *\n * @param options - The options for the lending deposit transaction.\n * @param options.amount - The amount to deposit.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingDeposit({\n amount,\n protocol,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n amount: string;\n protocol: LendingMarket['protocol'];\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeDepositTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Executes a lending withdraw transaction.\n *\n * @param options - The options for the lending withdraw transaction.\n * @param options.amount - The amount to withdraw.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingWithdraw({\n amount,\n protocol,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n amount: string;\n protocol: LendingMarket['protocol'];\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeWithdrawTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Executes a lending token approve transaction.\n *\n * @param options - The options for the lending token approve transaction.\n * @param options.amount - The amount to approve.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingTokenApprove({\n protocol,\n amount,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n protocol: LendingMarket['protocol'];\n amount: string;\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeUnderlyingTokenApproveTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Gets the allowance for a lending token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the allowance.\n */\n async getLendingTokenAllowance(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const allowance =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.underlyingTokenAllowance(address);\n\n return allowance;\n }\n\n /**\n * Gets the maximum withdraw amount for a lending token's output token or shares if no output token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the maximum withdraw amount.\n */\n async getLendingTokenMaxWithdraw(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const maxWithdraw =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.maxWithdraw(address);\n\n return maxWithdraw;\n }\n\n /**\n * Gets the maximum deposit amount for a lending token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the maximum deposit amount.\n */\n async getLendingTokenMaxDeposit(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const maxDeposit =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.maxDeposit(address);\n\n return maxDeposit;\n }\n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;IAAC,OAAO,KAAK,EAAE;QACd,uBAAA,IAAI,2BAAY,IAAI,MAAA,CAAC;QACrB,2DAA2D;QAC3D,IACE,CAAC,CACC,KAAK,YAAY,KAAK;YACtB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAC9C,EACD;YACA,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;SACzD;KACF;AACH,CAAC;IAQC,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,CAAC,CAAC;AAC5E,CAAC,iFAQkB,eAAwB;IACzC,MAAM,oBAAoB,GACxB,eAAe;QACf,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,4BAA4B,CAAC;aACpD,uBAAuB,CAAC;IAE7B,MAAM,EACJ,aAAa,EAAE,EAAE,OAAO,EAAE,GAC3B,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC3B,wCAAwC,EACxC,oBAAoB,CACrB,CAAC;IACF,OAAO,mBAAmB,CAAC,OAAO,CAAC,CAAC;AACtC,CAAC;IAQC,MAAM,aAAa,GAAG,uBAAA,IAAI,oEAAmB,MAAvB,IAAI,CAAqB,CAAC;IAEhD,IACE,CAAC,aAAa;QACd,CAAC,uBAAA,IAAI,oDAA8B,CAAC,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC,EAClE;QACA,4DAA4D;QAC5D,OAAO,mBAAmB,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;KAC/C;IAED,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import { Web3Provider } from '@ethersproject/providers';\nimport type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { convertHexToDecimal, toHex } from '@metamask/controller-utils';\nimport type {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport {\n EarnSdk,\n EarnApiService,\n isSupportedLendingChain,\n type LendingMarket,\n type PooledStake,\n type EarnSdkConfig,\n type VaultData,\n type VaultDailyApy,\n type VaultApyAverages,\n type LendingPosition,\n type GasLimitParams,\n type HistoricLendingMarketApys,\n EarnEnvironments,\n} from '@metamask/stake-sdk';\nimport {\n type TransactionController,\n TransactionType,\n type TransactionControllerTransactionConfirmedEvent,\n CHAIN_IDS,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { HOODI_TESTNET_CHAIN_ID_HEX } from './constants';\nimport type {\n RefreshEarnEligibilityOptions,\n RefreshLendingEligibilityOptions,\n RefreshLendingPositionsOptions,\n RefreshPooledStakesOptions,\n RefreshPooledStakingDataOptions,\n} from './types';\n\nexport const controllerName = 'EarnController';\n\nexport type PooledStakingState = {\n [chainId: number]: {\n pooledStakes: PooledStake;\n exchangeRate: string;\n vaultMetadata: VaultData;\n vaultDailyApys: VaultDailyApy[];\n vaultApyAverages: VaultApyAverages;\n };\n isEligible: boolean;\n};\n\nexport type LendingPositionWithMarket = LendingPosition & {\n marketId: string;\n marketAddress: string;\n protocol: string;\n};\n\n// extends LendingPosition to include a marketId, marketAddress, and protocol reference\nexport type LendingPositionWithMarketReference = Omit<\n LendingPosition,\n 'market'\n> & {\n marketId: string;\n marketAddress: string;\n protocol: string;\n};\n\nexport type LendingMarketWithPosition = LendingMarket & {\n position: LendingPositionWithMarketReference;\n};\n\nexport type LendingState = {\n markets: LendingMarket[]; // list of markets\n positions: LendingPositionWithMarketReference[]; // list of positions\n isEligible: boolean;\n};\n\ntype StakingTransactionTypes =\n | TransactionType.stakingDeposit\n | TransactionType.stakingUnstake\n | TransactionType.stakingClaim;\n\nconst stakingTransactionTypes = new Set<StakingTransactionTypes>([\n TransactionType.stakingDeposit,\n TransactionType.stakingUnstake,\n TransactionType.stakingClaim,\n]);\n\ntype LendingTransactionTypes =\n | TransactionType.lendingDeposit\n | TransactionType.lendingWithdraw;\n\nconst lendingTransactionTypes = new Set<LendingTransactionTypes>([\n TransactionType.lendingDeposit,\n TransactionType.lendingWithdraw,\n]);\n\n/**\n * Metadata for the EarnController.\n */\nconst earnControllerMetadata: StateMetadata<EarnControllerState> = {\n pooled_staking: {\n persist: true,\n anonymous: false,\n },\n lending: {\n persist: true,\n anonymous: false,\n },\n lastUpdated: {\n persist: false,\n anonymous: true,\n },\n};\n\n// === State Types ===\nexport type EarnControllerState = {\n pooled_staking: PooledStakingState;\n lending: LendingState;\n lastUpdated: number;\n};\n\n// === Default State ===\nexport const DEFAULT_LENDING_MARKET: LendingMarket = {\n id: '',\n chainId: 0,\n protocol: '' as LendingMarket['protocol'],\n name: '',\n address: '',\n tvlUnderlying: '0',\n netSupplyRate: 0,\n totalSupplyRate: 0,\n underlying: {\n address: '',\n chainId: 0,\n },\n outputToken: {\n address: '',\n chainId: 0,\n },\n rewards: [\n {\n token: {\n address: '',\n chainId: 0,\n },\n rate: 0,\n },\n ],\n};\n\nexport const DEFAULT_LENDING_POSITION: LendingPositionWithMarketReference = {\n id: '',\n chainId: 0,\n assets: '0',\n marketId: '',\n marketAddress: '',\n protocol: '',\n};\n\nexport const DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES: VaultApyAverages = {\n oneDay: '0',\n oneWeek: '0',\n oneMonth: '0',\n threeMonths: '0',\n sixMonths: '0',\n oneYear: '0',\n};\n\nexport const DEFAULT_POOLED_STAKING_CHAIN_STATE = {\n pooledStakes: {\n account: '',\n lifetimeRewards: '0',\n assets: '0',\n exitRequests: [],\n },\n exchangeRate: '1',\n vaultMetadata: {\n apy: '0',\n capacity: '0',\n feePercent: 0,\n totalAssets: '0',\n vaultAddress: '0x0000000000000000000000000000000000000000',\n },\n vaultDailyApys: [],\n vaultApyAverages: DEFAULT_POOLED_STAKING_VAULT_APY_AVERAGES,\n};\n\n/**\n * Gets the default state for the EarnController.\n *\n * @returns The default EarnController state.\n */\nexport function getDefaultEarnControllerState(): EarnControllerState {\n return {\n pooled_staking: {\n isEligible: false,\n },\n lending: {\n markets: [DEFAULT_LENDING_MARKET],\n positions: [DEFAULT_LENDING_POSITION],\n isEligible: false,\n },\n lastUpdated: 0,\n };\n}\n\n// === MESSENGER ===\n\n/**\n * The action which can be used to retrieve the state of the EarnController.\n */\nexport type EarnControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n EarnControllerState\n>;\n\n/**\n * All actions that EarnController registers, to be called externally.\n */\nexport type EarnControllerActions = EarnControllerGetStateAction;\n\n/**\n * All actions that EarnController calls internally.\n */\nexport type AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\n/**\n * The event that EarnController publishes when updating state.\n */\nexport type EarnControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n EarnControllerState\n>;\n\n/**\n * All events that EarnController publishes, to be subscribed to externally.\n */\nexport type EarnControllerEvents = EarnControllerStateChangeEvent;\n\n/**\n * All events that EarnController subscribes to internally.\n */\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | NetworkControllerStateChangeEvent\n | TransactionControllerTransactionConfirmedEvent;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * EarnController.\n */\nexport type EarnControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n EarnControllerActions | AllowedActions,\n EarnControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * EarnController manages DeFi earning opportunities across different protocols and chains.\n */\nexport class EarnController extends BaseController<\n typeof controllerName,\n EarnControllerState,\n EarnControllerMessenger\n> {\n #earnSDK: EarnSdk | null = null;\n\n #selectedNetworkClientId?: string;\n\n readonly #earnApiService: EarnApiService;\n\n readonly #addTransactionFn: typeof TransactionController.prototype.addTransaction;\n\n readonly #supportedPooledStakingChains: Hex[];\n\n readonly #env: EarnEnvironments;\n\n constructor({\n messenger,\n state = {},\n addTransactionFn,\n env = EarnEnvironments.PROD,\n }: {\n messenger: EarnControllerMessenger;\n state?: Partial<EarnControllerState>;\n addTransactionFn: typeof TransactionController.prototype.addTransaction;\n env?: EarnEnvironments;\n }) {\n super({\n name: controllerName,\n metadata: earnControllerMetadata,\n messenger,\n state: {\n ...getDefaultEarnControllerState(),\n ...state,\n },\n });\n\n this.#env = env;\n\n this.#earnApiService = new EarnApiService(this.#env);\n\n // temporary array of supported chains\n // TODO: remove this once we export a supported chains list from the sdk\n // from sdk or api to get lending and pooled staking chains\n this.#supportedPooledStakingChains = [\n CHAIN_IDS.MAINNET,\n HOODI_TESTNET_CHAIN_ID_HEX,\n ];\n\n this.#addTransactionFn = addTransactionFn;\n\n this.#initializeSDK().catch(console.error);\n this.refreshPooledStakingData().catch(console.error);\n this.refreshLendingData().catch(console.error);\n\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n this.#selectedNetworkClientId = selectedNetworkClientId;\n\n // Listen for network changes\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n (networkControllerState) => {\n if (\n networkControllerState.selectedNetworkClientId !==\n this.#selectedNetworkClientId\n ) {\n this.#initializeSDK(\n networkControllerState.selectedNetworkClientId,\n ).catch(console.error);\n\n this.refreshPooledStakingVaultMetadata().catch(console.error);\n this.refreshPooledStakingVaultDailyApys().catch(console.error);\n this.refreshPooledStakingVaultApyAverages().catch(console.error);\n this.refreshPooledStakes().catch(console.error);\n\n // refresh lending data for all chains\n this.refreshLendingMarkets().catch(console.error);\n this.refreshLendingPositions().catch(console.error);\n }\n this.#selectedNetworkClientId =\n networkControllerState.selectedNetworkClientId;\n },\n );\n\n // Listen for account changes\n this.messagingSystem.subscribe(\n 'AccountsController:selectedAccountChange',\n (account) => {\n const address = account?.address;\n /**\n * TEMP: There's a race condition where the account state isn't updated immediately.\n * Until this has been fixed, we rely on the event payload for the latest account instead of #getCurrentAccount().\n * Issue: https://github.com/MetaMask/accounts-planning/issues/887\n */\n\n // TODO: temp solution, this will refresh lending eligibility also\n // we could have a more general check, as what is happening is a compliance address check\n this.refreshEarnEligibility({ address }).catch(console.error);\n\n this.refreshPooledStakes({ address }).catch(console.error);\n this.refreshLendingPositions({ address }).catch(console.error);\n },\n );\n\n // Listen for confirmed staking transactions\n this.messagingSystem.subscribe(\n 'TransactionController:transactionConfirmed',\n (transactionMeta) => {\n /**\n * When we speed up a transaction, we set the type as Retry and we lose\n * information about type of transaction that is being set up, so we use\n * original type to track that information.\n */\n const { type, originalType } = transactionMeta;\n\n const isStakingTransaction =\n stakingTransactionTypes.has(type as StakingTransactionTypes) ||\n stakingTransactionTypes.has(originalType as StakingTransactionTypes);\n\n const isLendingTransaction =\n lendingTransactionTypes.has(type as LendingTransactionTypes) ||\n lendingTransactionTypes.has(originalType as LendingTransactionTypes);\n\n const sender = transactionMeta.txParams.from;\n\n if (isStakingTransaction) {\n this.refreshPooledStakes({ resetCache: true, address: sender }).catch(\n console.error,\n );\n }\n if (isLendingTransaction) {\n this.refreshLendingPositions({ address: sender }).catch(\n console.error,\n );\n }\n },\n );\n }\n\n /**\n * Initializes the Earn SDK.\n *\n * @param networkClientId - The network client id to initialize the Earn SDK for (optional).\n */\n async #initializeSDK(networkClientId?: string) {\n const { selectedNetworkClientId } = networkClientId\n ? { selectedNetworkClientId: networkClientId }\n : this.messagingSystem.call('NetworkController:getState');\n\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n\n if (!networkClient?.provider) {\n this.#earnSDK = null;\n return;\n }\n\n const provider = new Web3Provider(networkClient.provider);\n const { chainId } = networkClient.configuration;\n\n // Initialize appropriate contracts based on chainId\n const config: EarnSdkConfig = {\n chainId: convertHexToDecimal(chainId),\n env: this.#env,\n };\n\n try {\n this.#earnSDK = await EarnSdk.create(provider, config);\n } catch (error) {\n this.#earnSDK = null;\n // Only log unexpected errors, not unsupported chain errors\n if (\n !(\n error instanceof Error &&\n error.message.includes('Unsupported chainId')\n )\n ) {\n console.error('Earn SDK initialization failed:', error);\n }\n }\n }\n\n /**\n * Gets the current account.\n *\n * @returns The current account.\n */\n #getCurrentAccount() {\n return this.messagingSystem.call('AccountsController:getSelectedAccount');\n }\n\n /**\n * Gets the current chain id.\n *\n * @param networkClientId - The network client id to get the chain id for (optional).\n * @returns The current chain id in decimal.\n */\n #getCurrentChainId(networkClientId?: string): number {\n const networkClientIdToUse =\n networkClientId ??\n this.messagingSystem.call('NetworkController:getState')\n .selectedNetworkClientId;\n\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientIdToUse,\n );\n return convertHexToDecimal(chainId);\n }\n\n /**\n * Ensures chainId is compatible with pooled-staking. Falls back to Ethereum Mainnet if chainId is not supported.\n *\n * @returns The current chain id in decimal. Ethereum Mainnet if it's not an ethereum chain.\n */\n #getActivePooledStakingChainId(): number {\n const activeChainId = this.#getCurrentChainId();\n\n if (\n !activeChainId ||\n !this.#supportedPooledStakingChains.includes(toHex(activeChainId))\n ) {\n // Fallback to Ethereum Mainnet if chainId is not supported.\n return convertHexToDecimal(CHAIN_IDS.MAINNET);\n }\n\n return activeChainId;\n }\n\n /**\n * Refreshes the pooled stakes data for the current account.\n * Fetches updated stake information including lifetime rewards, assets, and exit requests\n * from the staking API service and updates the state.\n *\n * @param options - Optional arguments\n * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).\n * @param [options.address] - The address to refresh pooled stakes for (optional).\n * @returns A promise that resolves when the stakes data has been updated\n */\n async refreshPooledStakes({\n resetCache = false,\n address,\n }: RefreshPooledStakesOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToUse) {\n return;\n }\n\n const chainId = this.#getActivePooledStakingChainId();\n\n const { accounts, exchangeRate } =\n await this.#earnApiService.pooledStaking.getPooledStakes(\n [addressToUse],\n chainId,\n resetCache,\n );\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainId] = {\n ...chainState,\n pooledStakes: accounts[0],\n exchangeRate,\n };\n });\n }\n\n /**\n * Refreshes the earn eligibility status for the current account.\n * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.\n *\n * Note: Pooled-staking and Lending used the same result since there isn't a need to split these up right now.\n *\n * @param options - Optional arguments\n * @param [options.address] - Address to refresh earn eligibility for (optional).\n * @returns A promise that resolves when the eligibility status has been updated\n */\n async refreshEarnEligibility({\n address,\n }: RefreshEarnEligibilityOptions = {}): Promise<void> {\n const addressToCheck = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToCheck) {\n return;\n }\n\n const { eligible: isEligible } =\n await this.#earnApiService.pooledStaking.getPooledStakingEligibility([\n addressToCheck,\n ]);\n\n this.update((state) => {\n state.pooled_staking.isEligible = isEligible;\n state.lending.isEligible = isEligible;\n });\n }\n\n /**\n * Refreshes pooled staking vault metadata for the current chain.\n * Updates the vault metadata in the controller state including APY, capacity,\n * fee percentage, total assets, and vault address.\n *\n * @returns A promise that resolves when the vault metadata has been updated\n */\n async refreshPooledStakingVaultMetadata(): Promise<void> {\n const chainId = this.#getActivePooledStakingChainId();\n\n const vaultMetadata =\n await this.#earnApiService.pooledStaking.getVaultData(chainId);\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainId] = {\n ...chainState,\n vaultMetadata,\n };\n });\n }\n\n /**\n * Refreshes pooled staking vault daily apys for the current chain.\n * Updates the pooled staking vault daily apys controller state.\n *\n * @param days - The number of days to fetch pooled staking vault daily apys for (defaults to 365).\n * @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').\n * @returns A promise that resolves when the pooled staking vault daily apys have been updated.\n */\n async refreshPooledStakingVaultDailyApys(\n days = 365,\n order: 'asc' | 'desc' = 'desc',\n ): Promise<void> {\n const chainId = this.#getActivePooledStakingChainId();\n\n const vaultDailyApys =\n await this.#earnApiService.pooledStaking.getVaultDailyApys(\n chainId,\n days,\n order,\n );\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainId] = {\n ...chainState,\n vaultDailyApys,\n };\n });\n }\n\n /**\n * Refreshes pooled staking vault apy averages for the current chain.\n * Updates the pooled staking vault apy averages controller state.\n *\n * @returns A promise that resolves when the pooled staking vault apy averages have been updated.\n */\n async refreshPooledStakingVaultApyAverages() {\n const chainId = this.#getActivePooledStakingChainId();\n\n const vaultApyAverages =\n await this.#earnApiService.pooledStaking.getVaultApyAverages(chainId);\n\n this.update((state) => {\n const chainState =\n state.pooled_staking[chainId] ?? DEFAULT_POOLED_STAKING_CHAIN_STATE;\n state.pooled_staking[chainId] = {\n ...chainState,\n vaultApyAverages,\n };\n });\n }\n\n /**\n * Refreshes all pooled staking related data including stakes, eligibility, and vault data.\n * This method allows partial success, meaning some data may update while other requests fail.\n * All errors are collected and thrown as a single error message.\n *\n * @param options - Optional arguments\n * @param [options.resetCache] - Control whether the BE cache should be invalidated (optional).\n * @param [options.address] - The address to refresh pooled stakes for (optional).\n * @returns A promise that resolves when all possible data has been updated\n * @throws {Error} If any of the refresh operations fail, with concatenated error messages\n */\n async refreshPooledStakingData({\n resetCache,\n address,\n }: RefreshPooledStakingDataOptions = {}): Promise<void> {\n const errors: Error[] = [];\n await Promise.all([\n this.refreshPooledStakes({ resetCache, address }).catch((error) => {\n errors.push(error);\n }),\n this.refreshEarnEligibility({ address }).catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultMetadata().catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultDailyApys().catch((error) => {\n errors.push(error);\n }),\n this.refreshPooledStakingVaultApyAverages().catch((error) => {\n errors.push(error);\n }),\n ]);\n\n if (errors.length > 0) {\n throw new Error(\n `Failed to refresh some staking data: ${errors\n .map((e) => e.message)\n .join(', ')}`,\n );\n }\n }\n\n /**\n * Refreshes the lending markets data for all chains.\n * Updates the lending markets in the controller state.\n *\n * @returns A promise that resolves when the lending markets have been updated\n */\n async refreshLendingMarkets(): Promise<void> {\n const markets = await this.#earnApiService.lending.getMarkets();\n\n this.update((state) => {\n state.lending.markets = markets;\n });\n }\n\n /**\n * Refreshes the lending positions for the current account.\n * Updates the lending positions in the controller state.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to refresh lending positions for (optional).\n * @returns A promise that resolves when the lending positions have been updated\n */\n async refreshLendingPositions({\n address,\n }: RefreshLendingPositionsOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n\n if (!addressToUse) {\n return;\n }\n\n // linter complaining about this not being a promise, but it is\n // TODO: figure out why this is not seen as a promise\n const positions = await Promise.resolve(\n this.#earnApiService.lending.getPositions(addressToUse),\n );\n\n this.update((state) => {\n state.lending.positions = positions.map((position) => ({\n ...position,\n marketId: position.market.id,\n marketAddress: position.market.address,\n protocol: position.market.protocol,\n }));\n });\n }\n\n /**\n * Refreshes the lending eligibility status for the current account.\n * Updates the eligibility status in the controller state based on the location and address blocklist for compliance.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to refresh lending eligibility for (optional).\n * @returns A promise that resolves when the eligibility status has been updated\n */\n async refreshLendingEligibility({\n address,\n }: RefreshLendingEligibilityOptions = {}): Promise<void> {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n // TODO: this is a temporary solution to refresh lending eligibility as\n // the eligibility check is not yet implemented for lending\n // this check will check the address against the same blocklist as the\n // staking eligibility check\n\n if (!addressToUse) {\n return;\n }\n\n const { eligible: isEligible } =\n await this.#earnApiService.pooledStaking.getPooledStakingEligibility([\n addressToUse,\n ]);\n\n this.update((state) => {\n state.lending.isEligible = isEligible;\n state.pooled_staking.isEligible = isEligible;\n });\n }\n\n /**\n * Refreshes all lending related data including markets, positions, and eligibility.\n * This method allows partial success, meaning some data may update while other requests fail.\n * All errors are collected and thrown as a single error message.\n *\n * @returns A promise that resolves when all possible data has been updated\n * @throws {Error} If any of the refresh operations fail, with concatenated error messages\n */\n async refreshLendingData(): Promise<void> {\n const errors: Error[] = [];\n\n await Promise.all([\n this.refreshLendingMarkets().catch((error) => {\n errors.push(error);\n }),\n this.refreshLendingPositions().catch((error) => {\n errors.push(error);\n }),\n this.refreshLendingEligibility().catch((error) => {\n errors.push(error);\n }),\n ]);\n\n if (errors.length > 0) {\n throw new Error(\n `Failed to refresh some lending data: ${errors\n .map((e) => e.message)\n .join(', ')}`,\n );\n }\n }\n\n /**\n * Gets the lending position history for the current account.\n *\n * @param options - Optional arguments\n * @param [options.address] - The address to get lending position history for (optional).\n * @param [options.chainId] - The chain id to get lending position history for (optional).\n * @param [options.positionId] - The position id to get lending position history for.\n * @param [options.marketId] - The market id to get lending position history for.\n * @param [options.marketAddress] - The market address to get lending position history for.\n * @param [options.protocol] - The protocol to get lending position history for.\n * @param [options.days] - The number of days to get lending position history for (optional).\n * @returns A promise that resolves when the lending position history has been updated\n */\n getLendingPositionHistory({\n address,\n chainId,\n positionId,\n marketId,\n marketAddress,\n protocol,\n days = 730,\n }: {\n address?: string;\n chainId?: number;\n positionId: string;\n marketId: string;\n marketAddress: string;\n protocol: string;\n days?: number;\n }) {\n const addressToUse = address ?? this.#getCurrentAccount()?.address;\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n\n if (!addressToUse || !isSupportedLendingChain(chainIdToUse)) {\n return [];\n }\n\n return this.#earnApiService.lending.getPositionHistory(\n addressToUse,\n chainIdToUse,\n protocol,\n marketId,\n marketAddress,\n positionId,\n days,\n );\n }\n\n /**\n * Gets the lending market daily apys and averages for the current chain.\n *\n * @param options - Optional arguments\n * @param [options.chainId] - The chain id to get lending market daily apys and averages for (optional).\n * @param [options.protocol] - The protocol to get lending market daily apys and averages for.\n * @param [options.marketId] - The market id to get lending market daily apys and averages for.\n * @param [options.days] - The number of days to get lending market daily apys and averages for (optional).\n * @returns A promise that resolves when the lending market daily apys and averages have been updated\n */\n getLendingMarketDailyApysAndAverages({\n chainId,\n protocol,\n marketId,\n days = 365,\n }: {\n chainId?: number;\n protocol: string;\n marketId: string;\n days?: number;\n }): Promise<HistoricLendingMarketApys> | undefined {\n const chainIdToUse = chainId ?? this.#getCurrentChainId();\n\n if (!isSupportedLendingChain(chainIdToUse)) {\n return undefined;\n }\n\n return this.#earnApiService.lending.getHistoricMarketApys(\n chainIdToUse,\n protocol,\n marketId,\n days,\n );\n }\n\n /**\n * Executes a lending deposit transaction.\n *\n * @param options - The options for the lending deposit transaction.\n * @param options.amount - The amount to deposit.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingDeposit({\n amount,\n protocol,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n amount: string;\n protocol: LendingMarket['protocol'];\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeDepositTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Executes a lending withdraw transaction.\n *\n * @param options - The options for the lending withdraw transaction.\n * @param options.amount - The amount to withdraw.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingWithdraw({\n amount,\n protocol,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n amount: string;\n protocol: LendingMarket['protocol'];\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeWithdrawTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Executes a lending token approve transaction.\n *\n * @param options - The options for the lending token approve transaction.\n * @param options.amount - The amount to approve.\n * @param options.protocol - The protocol of the lending market.\n * @param options.underlyingTokenAddress - The address of the underlying token.\n * @param options.gasOptions - The gas options for the transaction.\n * @param options.gasOptions.gasLimit - The gas limit for the transaction.\n * @param options.gasOptions.gasBufferPct - The gas buffer percentage for the transaction.\n * @param options.txOptions - The transaction options for the transaction.\n * @returns A promise that resolves to the transaction hash.\n */\n async executeLendingTokenApprove({\n protocol,\n amount,\n underlyingTokenAddress,\n gasOptions,\n txOptions,\n }: {\n protocol: LendingMarket['protocol'];\n amount: string;\n underlyingTokenAddress: string;\n gasOptions: {\n gasLimit?: GasLimitParams;\n gasBufferPct?: number;\n };\n txOptions: Parameters<\n typeof TransactionController.prototype.addTransaction\n >[1];\n }) {\n const address = this.#getCurrentAccount()?.address;\n\n const transactionData = await this.#earnSDK?.contracts?.lending?.[\n protocol\n ]?.[underlyingTokenAddress]?.encodeUnderlyingTokenApproveTransactionData(\n amount,\n address,\n gasOptions,\n );\n\n if (!transactionData) {\n throw new Error('Transaction data not found');\n }\n\n if (!this.#selectedNetworkClientId) {\n throw new Error('Selected network client id not found');\n }\n\n const gasLimit = !transactionData.gasLimit\n ? undefined\n : toHex(transactionData.gasLimit);\n\n const txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit,\n },\n {\n ...txOptions,\n networkClientId: this.#selectedNetworkClientId,\n },\n );\n\n return txHash;\n }\n\n /**\n * Gets the allowance for a lending token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the allowance.\n */\n async getLendingTokenAllowance(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const allowance =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.underlyingTokenAllowance(address);\n\n return allowance;\n }\n\n /**\n * Gets the maximum withdraw amount for a lending token's output token or shares if no output token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the maximum withdraw amount.\n */\n async getLendingTokenMaxWithdraw(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const maxWithdraw =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.maxWithdraw(address);\n\n return maxWithdraw;\n }\n\n /**\n * Gets the maximum deposit amount for a lending token.\n *\n * @param protocol - The protocol of the lending market.\n * @param underlyingTokenAddress - The address of the underlying token.\n * @returns A promise that resolves to the maximum deposit amount.\n */\n async getLendingTokenMaxDeposit(\n protocol: LendingMarket['protocol'],\n underlyingTokenAddress: string,\n ) {\n const address = this.#getCurrentAccount()?.address;\n\n const maxDeposit =\n await this.#earnSDK?.contracts?.lending?.[protocol]?.[\n underlyingTokenAddress\n ]?.maxDeposit(address);\n\n return maxDeposit;\n }\n}\n"]}
|
@@ -0,0 +1,6 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.HOODI_TESTNET_CHAIN_ID_DECIMAL = exports.HOODI_TESTNET_CHAIN_ID_HEX = void 0;
|
4
|
+
exports.HOODI_TESTNET_CHAIN_ID_HEX = '0x88bb0';
|
5
|
+
exports.HOODI_TESTNET_CHAIN_ID_DECIMAL = 560048;
|
6
|
+
//# sourceMappingURL=constants.cjs.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,0BAA0B,GAAG,SAAS,CAAC;AAEvC,QAAA,8BAA8B,GAAG,MAAM,CAAC","sourcesContent":["export const HOODI_TESTNET_CHAIN_ID_HEX = '0x88bb0';\n\nexport const HOODI_TESTNET_CHAIN_ID_DECIMAL = 560048;\n"]}
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,0BAA0B,YAAY,CAAC;AAEpD,eAAO,MAAM,8BAA8B,SAAS,CAAC"}
|