@metamask-previews/earn-controller 1.0.0-preview-b33c0741 → 1.1.0-preview-ef0f18a

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 CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.1.0]
11
+
12
+ ### Changed
13
+
14
+ - Replace hardcoded `"lendingWithdraw"` in `LendingTransactionTypes` with `TransactionType.lendingWithdraw` ([#5936](https://github.com/MetaMask/core/pull/5936))
15
+ - Bump `@metamask/controller-utils` to `^11.10.0` ([#5935](https://github.com/MetaMask/core/pull/5935))
16
+
10
17
  ## [1.0.0]
11
18
 
12
19
  ### Added
@@ -189,7 +196,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
189
196
 
190
197
  - Initial release ([#5271](https://github.com/MetaMask/core/pull/5271))
191
198
 
192
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@1.0.0...HEAD
199
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@1.1.0...HEAD
200
+ [1.1.0]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@1.0.0...@metamask/earn-controller@1.1.0
193
201
  [1.0.0]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@0.15.0...@metamask/earn-controller@1.0.0
194
202
  [0.15.0]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@0.14.0...@metamask/earn-controller@0.15.0
195
203
  [0.14.0]: https://github.com/MetaMask/core/compare/@metamask/earn-controller@0.13.0...@metamask/earn-controller@0.14.0
@@ -26,7 +26,7 @@ const stakingTransactionTypes = new Set([
26
26
  ]);
27
27
  const lendingTransactionTypes = new Set([
28
28
  transaction_controller_1.TransactionType.lendingDeposit,
29
- 'lendingWithdraw',
29
+ transaction_controller_1.TransactionType.lendingWithdraw,
30
30
  ]);
31
31
  /**
32
32
  * Metadata for the EarnController.
@@ -1 +1 @@
1
- {"version":3,"file":"EarnController.cjs","sourceRoot":"","sources":["../src/EarnController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wDAAwD;AAWxD,+DAA2D;AAC3D,iEAAwE;AAMxE,mDAe6B;AAC7B,6EAI0C;AAU7B,QAAA,cAAc,GAAG,gBAAgB,CAAC;AA4C/C,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,wCAAe,CAAC,cAAc;IAC9B,wCAAe,CAAC,cAAc;IAC9B,wCAAe,CAAC,YAAY;CAC7B,CAAC,CAAC;AAMH,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,wCAAe,CAAC,cAAc;IAC9B,iBAAiB;CAClB,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,sBAAsB,GAAuC;IACjE,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,OAAO,EAAE;QACP,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,WAAW,EAAE;QACX,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AASF,wBAAwB;AACX,QAAA,sBAAsB,GAAkB;IACnD,EAAE,EAAE,EAAE;IACN,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,EAA+B;IACzC,IAAI,EAAE,EAAE;IACR,OAAO,EAAE,EAAE;IACX,aAAa,EAAE,GAAG;IAClB,aAAa,EAAE,CAAC;IAChB,eAAe,EAAE,CAAC;IAClB,UAAU,EAAE;QACV,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IACD,WAAW,EAAE;QACX,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IACD,OAAO,EAAE;QACP;YACE,KAAK,EAAE;gBACL,OAAO,EAAE,EAAE;gBACX,OAAO,EAAE,CAAC;aACX;YACD,IAAI,EAAE,CAAC;SAC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AAA,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,IAAA,sCAAmB,EAAC,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 | 'lendingWithdraw';\n\nconst lendingTransactionTypes = new Set<LendingTransactionTypes>([\n TransactionType.lendingDeposit,\n '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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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"]}
1
+ {"version":3,"file":"EarnController.cjs","sourceRoot":"","sources":["../src/EarnController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,wDAAwD;AAWxD,+DAA2D;AAC3D,iEAAwE;AAMxE,mDAe6B;AAC7B,6EAI0C;AAU7B,QAAA,cAAc,GAAG,gBAAgB,CAAC;AA4C/C,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,wCAAe,CAAC,cAAc;IAC9B,wCAAe,CAAC,cAAc;IAC9B,wCAAe,CAAC,YAAY;CAC7B,CAAC,CAAC;AAMH,MAAM,uBAAuB,GAAG,IAAI,GAAG,CAA0B;IAC/D,wCAAe,CAAC,cAAc;IAC9B,wCAAe,CAAC,eAAe;CAChC,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,sBAAsB,GAAuC;IACjE,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,OAAO,EAAE;QACP,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,WAAW,EAAE;QACX,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AASF,wBAAwB;AACX,QAAA,sBAAsB,GAAkB;IACnD,EAAE,EAAE,EAAE;IACN,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,EAA+B;IACzC,IAAI,EAAE,EAAE;IACR,OAAO,EAAE,EAAE;IACX,aAAa,EAAE,GAAG;IAClB,aAAa,EAAE,CAAC;IAChB,eAAe,EAAE,CAAC;IAClB,UAAU,EAAE;QACV,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IACD,WAAW,EAAE;QACX,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,CAAC;KACX;IACD,OAAO,EAAE;QAC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AAO,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAA,CAAC;KACxD;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,IAAA,sCAAmB,EAAC,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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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"]}
@@ -23,7 +23,7 @@ const stakingTransactionTypes = new Set([
23
23
  ]);
24
24
  const lendingTransactionTypes = new Set([
25
25
  TransactionType.lendingDeposit,
26
- 'lendingWithdraw',
26
+ TransactionType.lendingWithdraw,
27
27
  ]);
28
28
  /**
29
29
  * Metadata for the EarnController.
@@ -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,iBAAiB;CAClB,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,sBAAsB,GAAuC;IACjE,cAAc,EAAE;QACd,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;IACD,OAAO,EAAE;QACP,OAAO,EAAE,IAAI;QACb,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ersproject/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 | 'lendingWithdraw';\n\nconst lendingTransactionTypes = new Set<LendingTransactionTypes>([\n TransactionType.lendingDeposit,\n '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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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"]}
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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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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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 txHash = await this.#addTransactionFn(\n {\n ...transactionData,\n value: transactionData.value.toString(),\n chainId: toHex(this.#getCurrentChainId()),\n gasLimit: String(transactionData.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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/earn-controller",
3
- "version": "1.0.0-preview-b33c0741",
3
+ "version": "1.1.0-preview-ef0f18a",
4
4
  "description": "Manages state for earning features and coordinates interactions between staking services, SDK integrations, and other controllers to enable users to participate in various earning opportunities",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -50,15 +50,15 @@
50
50
  "@ethersproject/bignumber": "^5.7.0",
51
51
  "@ethersproject/providers": "^5.7.0",
52
52
  "@metamask/base-controller": "^8.0.1",
53
- "@metamask/controller-utils": "^11.9.0",
53
+ "@metamask/controller-utils": "^11.10.0",
54
54
  "@metamask/stake-sdk": "^3.2.0",
55
55
  "reselect": "^5.1.1"
56
56
  },
57
57
  "devDependencies": {
58
58
  "@metamask/accounts-controller": "^30.0.0",
59
59
  "@metamask/auto-changelog": "^3.4.4",
60
- "@metamask/network-controller": "^23.5.1",
61
- "@metamask/transaction-controller": "^57.1.0",
60
+ "@metamask/network-controller": "^23.6.0",
61
+ "@metamask/transaction-controller": "^57.2.0",
62
62
  "@types/jest": "^27.4.1",
63
63
  "deepmerge": "^4.2.2",
64
64
  "jest": "^27.5.1",