@metamask-previews/assets-controller 20.3.1-preview-d1da3c817 → 20.3.1-preview-701acab40

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/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4iBA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,SAAqB,EACrB,UAAsB;IAEtB,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC;QAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /**\n * When true, the data source should poll only the user's `customAssets`\n * for the requested chains and skip refreshing the regular tracked\n * balances. Used by the AssetsController to issue a supplemental RPC\n * subscription on chains that another data source is already covering\n * (Accounts API v5 path). Ignored when Accounts API v6 is enabled.\n */\n customAssetsOnly?: boolean;\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n /**\n * Per-account status of the background (Snap + RPC) fetch that runs after\n * the initial balance has resolved. Tracked on every forced fetch.\n */\n assetsBackgroundLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAuiBA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,YAAY,CAC1B,SAAqB,EACrB,UAAsB;IAEtB,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,cAAc,GAAG,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC;QAC7C,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;QAEtE,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;QACnB,CAAC;QAED,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { SupportedCurrency } from '@metamask/core-backend';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\nimport type { CaipAssetType, CaipChainId, Json } from '@metamask/utils';\n\n/**\n * CAIP-19 compliant asset identifier\n * Format: \"{chainId}/{assetNamespace}:{assetReference}[/tokenId]\"\n *\n * Examples:\n * - Native: \"eip155:1/slip44:60\" (ETH)\n * - ERC20: \"eip155:1/erc20:0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48\" (USDC)\n * - ERC721: \"eip155:1/erc721:0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D/1234\" (BAYC #1234)\n * - SPL: \"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp/token:EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\"\n */\nexport type Caip19AssetId = CaipAssetType;\n\n/**\n * InternalAccount UUID from AccountsController\n * Not the blockchain address!\n */\nexport type AccountId = string;\n\n/**\n * CAIP-2 chain identifier\n */\nexport type ChainId = CaipChainId;\n\n// ============================================================================\n// ASSET TYPES - Defined by metadata structure\n// ============================================================================\n\n/**\n * Asset types define the metadata structure, not blockchain implementation.\n * - \"fungible\" includes: native, erc20, spl - all share balance, symbol, decimals\n * - \"nft\" includes: erc721, erc1155 - include tokenId, image, attributes\n */\nexport type AssetType = 'fungible' | 'nft' | 'collectible';\n\n/**\n * Token standards - blockchain implementation details\n */\nexport type TokenStandard =\n | 'native'\n | 'erc20'\n | 'erc721'\n | 'erc1155'\n | 'spl'\n | string;\n\n// ============================================================================\n// METADATA TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * UI preferences for an asset (stored in assetPreferences state, not in metadata).\n */\nexport type AssetPreferences = {\n /** Whether the asset is hidden from display */\n hidden?: boolean;\n};\n\n/**\n * Base metadata attributes shared by ALL asset types.\n */\nexport type BaseAssetMetadata = {\n /** Token standard - how it's implemented on the blockchain */\n type: TokenStandard;\n /** Display symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Full name (e.g., \"Ethereum\", \"USD Coin\") */\n name: string;\n /** Token decimals (18 for ETH, 6 for USDC, etc.) */\n decimals: number;\n /** Logo URL or data URI */\n image?: string;\n};\n\n// ============================================================================\n// TOKEN CONTRACT DATA TYPES\n// ============================================================================\n\n/** Fee information for token transfers */\nexport type TokenFees = {\n avgFee: number;\n maxFee: number;\n minFee: number;\n};\n\n/** Honeypot detection status */\nexport type HoneypotStatus = {\n honeypotIs: boolean;\n goPlus?: boolean;\n};\n\n/** Storage slot information for the contract */\nexport type StorageSlots = {\n balance: number;\n approval: number;\n};\n\n/** Localized description */\nexport type LocalizedDescription = {\n en: string;\n};\n\n// ============================================================================\n// ASSET METADATA TYPES\n// ============================================================================\n\n/**\n * Metadata for fungible tokens.\n * Structure mirrors V3AssetResponse from the Tokens API.\n *\n * Differences from V3AssetResponse:\n * - `type` is derived from assetId namespace (not in API response)\n * - `image` maps from API's `iconUrl`\n * - `assetId` is not stored (used as the key)\n */\nexport type FungibleAssetMetadata = {\n /** Token type derived from assetId namespace */\n type: 'native' | 'erc20' | 'spl';\n /** CoinGecko ID for price lookups */\n coingeckoId?: string;\n /** Number of token list occurrences */\n occurrences?: number;\n /** DEX/aggregator integrations */\n aggregators?: string[];\n /** Asset labels/tags (e.g., \"stable_coin\") */\n labels?: string[];\n /** Whether the token supports ERC-20 permit */\n erc20Permit?: boolean;\n /** Fee information for token transfers */\n fees?: TokenFees;\n /** Honeypot detection status */\n honeypotStatus?: HoneypotStatus;\n /** Storage slot information for the contract */\n storage?: StorageSlots;\n /** Whether the contract is verified */\n isContractVerified?: boolean;\n /** Localized description */\n description?: LocalizedDescription;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC721 NFTs\n * Asset Type: \"nft\"\n */\nexport type ERC721AssetMetadata = {\n type: 'erc721';\n decimals: 0;\n /** Collection name */\n collectionName?: string;\n /** Collection size */\n collectionSize?: number;\n /** NFT traits/attributes - must be Json-serializable */\n traits?: Record<string, Json>;\n /** Rarity score */\n rarity?: number;\n /** Verification status */\n verified?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Metadata for ERC1155 multi-tokens\n */\nexport type ERC1155AssetMetadata = {\n type: 'erc1155';\n /** Token URI */\n tokenUri?: string;\n /** Token category */\n category?: string;\n /** Spam detection flag */\n isSpam?: boolean;\n} & BaseAssetMetadata;\n\n/**\n * Union type representing all possible asset metadata types.\n * All types must be JSON-serializable.\n */\nexport type AssetMetadata =\n | FungibleAssetMetadata\n | ERC721AssetMetadata\n | ERC1155AssetMetadata\n | (BaseAssetMetadata & { [key: string]: Json });\n\n// ============================================================================\n// PRICE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Base price attributes.\n */\nexport type BaseAssetPrice = {\n /** Current price in selected currency */\n price: number;\n /** Timestamp of last price update */\n lastUpdated: number;\n};\n\n/**\n * Price data for fungible tokens (native, ERC20, SPL)\n * Matches V3SpotPricesResponse from the Price API.\n */\nexport type FungibleAssetPrice = BaseAssetPrice & {\n assetPriceType: 'fungible';\n /** CoinGecko ID */\n id?: string;\n /** Market capitalization */\n marketCap?: number;\n /** All-time high price */\n allTimeHigh?: number;\n /** All-time low price */\n allTimeLow?: number;\n /** 24h trading volume */\n totalVolume?: number;\n /** 24h high price */\n high1d?: number;\n /** 24h low price */\n low1d?: number;\n /** Circulating supply */\n circulatingSupply?: number;\n /** Fully diluted market cap */\n dilutedMarketCap?: number;\n /** 24h market cap change percentage */\n marketCapPercentChange1d?: number;\n /** 24h price change in USD */\n priceChange1d?: number;\n /** 5m price change percentage */\n pricePercentChange5m?: number;\n /** 1h price change percentage */\n pricePercentChange1h?: number;\n /** 4h price change percentage */\n pricePercentChange4h?: number;\n /** 24h price change percentage */\n pricePercentChange1d?: number;\n /** 7d price change percentage */\n pricePercentChange7d?: number;\n /** 14d price change percentage */\n pricePercentChange14d?: number;\n /** 30d price change percentage */\n pricePercentChange30d?: number;\n /** 200d price change percentage */\n pricePercentChange200d?: number;\n /** 1y price change percentage */\n pricePercentChange1y?: number;\n /** Current price in USD */\n usdPrice: number;\n};\n\n/**\n * Price data for NFT collections\n */\nexport type NFTAssetPrice = BaseAssetPrice & {\n assetPriceType: 'nft';\n /** Floor price */\n floorPrice?: number;\n /** Last sale price */\n lastSalePrice?: number;\n /** Collection trading volume */\n collectionVolume?: number;\n /** Average price */\n averagePrice?: number;\n /** Number of sales in 24h */\n sales24h?: number;\n};\n\n/**\n * Union type representing all possible asset price types.\n * All types must be JSON-serializable.\n */\nexport type AssetPrice = FungibleAssetPrice | NFTAssetPrice;\n\n// ============================================================================\n// BALANCE TYPES (vary by asset type)\n// ============================================================================\n\n/**\n * Balance data for fungible tokens (native, ERC20, SPL).\n */\nexport type FungibleAssetBalance = {\n /** Converted balance amount (e.g., \"1000\" for 1000 USDC) */\n amount: string;\n /**\n * Network-specific balance fields, when the source provides them. Stellar\n * native rows carry `spendableBalance` / `minimumReserveBalance`, and\n * trustlines carry `limit` / `authorized` / `sponsored`.\n */\n metadata?: Json;\n};\n\n/**\n * Balance data for ERC721 NFTs.\n * Each tokenId has its own CAIP-19 asset ID, so always \"1\".\n */\nexport type ERC721AssetBalance = {\n /** Always \"1\" for ERC721 (non-fungible) */\n amount: '1';\n};\n\n/**\n * Balance data for ERC1155 multi-tokens.\n */\nexport type ERC1155AssetBalance = {\n /** Quantity owned of this specific tokenId */\n amount: string;\n};\n\n/**\n * Union type representing all possible asset balance types.\n * All types must be JSON-serializable.\n */\nexport type AssetBalance =\n | FungibleAssetBalance\n | ERC721AssetBalance\n | ERC1155AssetBalance\n | { amount: string; [key: string]: Json };\n\n// ============================================================================\n// DATA SOURCE TYPES\n// ============================================================================\n\n/**\n * Data type dimension - what kind of data\n */\nexport type DataType = 'balance' | 'metadata' | 'price';\n\n/**\n * Account with its supported chains (enabled chains ∩ account scope).\n * Pre-computed by the controller so data sources do not need to implement\n * account-scope logic; they iterate over supportedChains for each account.\n */\nexport type AccountWithSupportedChains = {\n account: InternalAccount;\n supportedChains: ChainId[];\n};\n\n/**\n * Request for data from data sources\n */\nexport type DataRequest = {\n /** Accounts with their supported chains (enabled ∩ account scope). Data sources use this instead of computing accountSupportsChain. */\n accountsWithSupportedChains: AccountWithSupportedChains[];\n /** CAIP-2 chain IDs (union of chains in this request) */\n chainIds: ChainId[];\n /** Filter by asset types */\n assetTypes?: AssetType[];\n /** Which data to fetch */\n dataTypes: DataType[];\n /**\n * Optional scoped CAIP-19 asset IDs for this fetch (not the full pin list).\n * v5 force-update and v5 RPC fallback put pins here. v6 omits it: natives,\n * pins, and default tracked assets are read from controller state as\n * `includeAssetIds`; detected ERC-20 balances come back with the chain\n * snapshot. RPC fallback additionally refetches existing balances.\n */\n customAssets?: Caip19AssetId[];\n /**\n * When true, the data source should poll only the user's `customAssets`\n * for the requested chains and skip refreshing the regular tracked\n * balances. Used by the AssetsController to issue a supplemental RPC\n * subscription on chains that another data source is already covering\n * (Accounts API v5 path). Ignored when Accounts API v6 is enabled.\n */\n customAssetsOnly?: boolean;\n /** Force fresh fetch, bypass cache */\n forceUpdate?: boolean;\n /**\n * Bypass server-side HTTP caches in addition to the client-side ones that\n * `forceUpdate` already skips. Data sources backed by cached HTTP APIs\n * (e.g. the Accounts API with its 60s cache) append a random `bypassServerCache`\n * query param so the server re-reads instead of replaying a stale snapshot.\n * Use sparingly — e.g. right after a transaction confirms.\n */\n bypassServerCache?: boolean;\n /** Hint for polling interval (ms) - used by data sources that implement polling */\n updateInterval?: number;\n};\n\n/**\n * Response from data sources\n */\nexport type DataResponse = {\n /** Metadata for assets (shared across accounts) */\n assetsInfo?: Record<Caip19AssetId, AssetMetadata>;\n /** Price data for assets (shared across accounts) */\n assetsPrice?: Record<Caip19AssetId, AssetPrice>;\n /** Balance data per account */\n assetsBalance?: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Errors encountered, keyed by chain ID (chain-axis fallback + telemetry) */\n errors?: Record<ChainId, string>;\n /**\n * How to apply this response to state. See {@link AssetsUpdateMode}.\n * Defaults to `'merge'` if omitted.\n */\n updateMode?: AssetsUpdateMode;\n /**\n * When set with `updateMode: 'merge'`, balances on chains present in\n * `assetsBalance` replace the prior chain slice (stale tokens on those chains\n * are dropped). Custom assets on covered chains are preserved. Used for\n * Accounts API v5 `getAssets({ forceUpdate: true })`. Accounts API v6 uses\n * `updateMode: 'full'` instead.\n */\n replaceCoveredChainBalances?: boolean;\n};\n\n/**\n * Type of {@link DataResponse.updateMode}: how the controller applies the response to state.\n *\n * - **full**: Response is the full set for covered chains (those present in\n * `assetsBalance`). Assets in state on those chains but not in the response\n * are cleared, including custom assets (Accounts API v6 returns pins via\n * `includeAssetIds`). A chain the source could not answer in full is reported\n * in `errors` and left out of `assetsBalance` entirely, so it is never\n * covered. Use for Accounts API v6 and RpcDataSource v6 snapshots.\n * - **merge**: Only assets present in the response are updated; nothing is\n * removed, unless {@link DataResponse.replaceCoveredChainBalances} is set\n * (Accounts API v5 force refresh). Metadata and prices from the response\n * are applied. Use for event-driven updates and Accounts API v5.\n */\nexport type AssetsUpdateMode = 'full' | 'merge';\n\nexport type AssetsLoadingStatus = 'loading' | 'loaded';\n\n// ============================================================================\n// DATA SOURCE <-> CONTROLLER (DIRECT CALLS, NO MESSENGER PER SOURCE)\n// ============================================================================\n\n/**\n * Callbacks for data sources to report to AssetsController.\n * Passed to data sources so they report by direct call instead of messenger.\n */\nexport type AssetsControllerReport = {\n onActiveChainsUpdate: (dataSourceId: string, activeChains: ChainId[]) => void;\n onAssetsUpdate: (response: DataResponse, sourceId: string) => Promise<void>;\n};\n\n/** Request passed from controller to data source when subscribing */\nexport type DataSourceSubscriptionRequest = {\n request: DataRequest;\n subscriptionId: string;\n isUpdate: boolean;\n};\n\n/**\n * Interface for balance data sources that the controller calls directly.\n * No messenger is required for controller <-> data source communication.\n */\nexport type BalanceDataSource = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n getName: () => string;\n};\n\n/**\n * Interface for the price data source (subscribe/unsubscribe + middleware).\n * Controller calls these methods directly.\n */\nexport type PriceDataSourceInterface = {\n getAssetsMiddleware: () => Middleware;\n subscribe: (request: DataSourceSubscriptionRequest) => Promise<void>;\n unsubscribe: (subscriptionId: string) => Promise<void>;\n};\n\n/**\n * Middleware-only source (e.g. detection, token enrichment).\n * Controller calls getAssetsMiddleware() directly.\n */\nexport type MiddlewareDataSource = {\n getAssetsMiddleware: () => Middleware;\n};\n\n// ============================================================================\n// CONTROLLER STATE\n// ============================================================================\n\n/**\n * State structure for AssetsController following normalized design.\n *\n * All values must stay JSON-serializable. UI preferences (e.g. hidden) live in\n * assetPreferences, not in metadata.\n *\n * Keys use CAIP identifiers:\n * - assetsInfo keys: CAIP-19 asset IDs (e.g., \"eip155:1/erc20:0x...\")\n * - assetsBalance outer keys: Account IDs (InternalAccount.id UUIDs)\n * - assetsBalance inner keys: CAIP-19 asset IDs\n * - assetsPrice keys: CAIP-19 asset IDs\n * - customAssets outer keys: Account IDs (InternalAccount.id UUIDs)\n * - customAssets inner values: CAIP-19 asset IDs array\n * - assetPreferences keys: CAIP-19 asset IDs\n */\nexport type AssetsControllerState = {\n /** Shared metadata for all assets (stored once per asset) */\n assetsInfo: Record<Caip19AssetId, AssetMetadata>;\n /** Per-account balance data */\n assetsBalance: Record<AccountId, Record<Caip19AssetId, AssetBalance>>;\n /** Price data for assets */\n assetsPrice: Record<Caip19AssetId, AssetPrice>;\n /** Custom assets added by users per account */\n customAssets: Record<AccountId, Caip19AssetId[]>;\n /** UI preferences per asset (e.g. hidden) - separate from metadata */\n assetPreferences: Record<Caip19AssetId, AssetPreferences>;\n /** Currently-active ISO 4217 currency code */\n selectedCurrency: SupportedCurrency;\n assetsLoadingStatus?: Record<AccountId, AssetsLoadingStatus>;\n};\n\n// ============================================================================\n// UNIFIED MIDDLEWARE TYPES\n// ============================================================================\n\n/**\n * Base context for all middleware operations.\n * Contains the common interface shared by fetch and subscribe.\n */\nexport type Context = {\n /** The data request */\n request: DataRequest;\n /** The response data (mutated by middlewares) */\n response: DataResponse;\n /**\n * Optional breakdown of latency (ms) per data source, e.g. from parallel\n * middlewares. Keys are source names (often \"MiddlewareName.SourceName\").\n * Merged into the controller's durationByDataSource for tracing.\n */\n durationByDataSource?: Record<string, number>;\n};\n\n/**\n * Next function for middleware chain\n */\nexport type NextFunction = (context: Context) => Promise<Context>;\n\n/**\n * Middleware function - works for both fetch and subscribe operations.\n */\nexport type Middleware = (\n context: Context,\n next: NextFunction,\n) => Promise<Context>;\n\n/**\n * An assets data source: any object that can participate in the assets\n * middleware chain with a display name (e.g. for tracing). Used by\n * createParallelMiddleware and by the controller when executing the chain.\n */\nexport type AssetsDataSource = {\n getName(): string;\n assetsMiddleware: Middleware;\n};\n\n/**\n * Wraps a middleware to only execute if specific dataTypes are requested.\n *\n * @param dataTypes - DataTypes that must be in the request for middleware to run\n * @param middleware - The middleware to conditionally execute\n * @returns A middleware that skips execution if none of the dataTypes are requested\n *\n * @example\n * ```typescript\n * // Only runs for metadata requests\n * const metadataMiddleware = forDataTypes(['metadata'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Enrich metadata...\n * return result;\n * });\n *\n * // Runs for balance or price requests\n * const balanceOrPriceMiddleware = forDataTypes(['balance', 'price'], async (ctx, next) => {\n * const result = await next(ctx);\n * // Process balances or prices...\n * return result;\n * });\n * ```\n */\nexport function forDataTypes(\n dataTypes: DataType[],\n middleware: Middleware,\n): Middleware {\n return async (ctx, next) => {\n const requestedTypes = ctx.request.dataTypes;\n const shouldRun = dataTypes.some((dt) => requestedTypes.includes(dt));\n\n if (!shouldRun) {\n return next(ctx);\n }\n\n return middleware(ctx, next);\n };\n}\n\n/**\n * Context for fetch operations.\n * Extends base Context - no additional fields needed for fetch.\n */\nexport type FetchContext = Context;\n\n// Legacy aliases for backwards compatibility\nexport type FetchNextFunction = NextFunction;\nexport type FetchMiddleware = Middleware;\n\n/**\n * Subscription response returned when subscribing to asset updates.\n */\nexport type SubscriptionResponse = {\n /** Chains actively subscribed */\n chains: ChainId[];\n /** Account ID being watched */\n accountId: AccountId;\n /** Asset types being watched */\n assetTypes: AssetType[];\n /** Data types being kept fresh */\n dataTypes: DataType[];\n /** Cleanup function */\n unsubscribe: () => void;\n};\n\n// ============================================================================\n// COMBINED ASSET TYPE (for UI)\n// ============================================================================\n\n/**\n * Combined asset type matching state structure: balance, metadata, price\n */\nexport type Asset = {\n /** CAIP-19 asset ID */\n id: Caip19AssetId;\n /** CAIP-2 chain ID (extracted from id) */\n chainId: ChainId;\n /** Balance data */\n balance: AssetBalance;\n /** Metadata (symbol, name, decimals, etc.) */\n metadata: AssetMetadata;\n /** Price data */\n price: AssetPrice;\n /** Computed fiat value (balance × price) */\n fiatValue: number;\n};\n\n// ============================================================================\n// EVENT TYPES\n// ============================================================================\n\n/**\n * Event emitted when balances change\n */\nexport type BalanceChangeEvent = {\n accountId: AccountId;\n assetId: Caip19AssetId;\n previousAmount: string;\n newAmount: string;\n timestamp: number;\n};\n\n/**\n * Event emitted when prices change\n */\nexport type PriceChangeEvent = {\n assetIds: Caip19AssetId[];\n timestamp: number;\n};\n\n/**\n * Event emitted when metadata changes\n */\nexport type MetadataChangeEvent = {\n assetId: Caip19AssetId;\n changes: Partial<AssetMetadata>;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/assets-controller",
3
- "version": "20.3.1-preview-d1da3c817",
3
+ "version": "20.3.1-preview-701acab40",
4
4
  "description": "Tracks assets balances/prices and handles token detection across all digital assets",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -87,7 +87,6 @@
87
87
  "lodash-es": "^4.18.1"
88
88
  },
89
89
  "devDependencies": {
90
- "@metamask/authenticated-user-storage": "^4.1.0",
91
90
  "@metamask/auto-changelog": "^7.1.0",
92
91
  "@metamask/eth-json-rpc-provider": "^7.0.0",
93
92
  "@types/lodash-es": "^4.17.12",
@@ -1,12 +0,0 @@
1
- /**
2
- * Method decorator that mirrors a custom-token state change to AUS user
3
- * storage as the decorated method returns, fire-and-forget.
4
- *
5
- * @param target - The decorated custom-token method.
6
- * @param context - The decorator context.
7
- * @returns The wrapped method.
8
- * @throws If applied to a method that is not configured in
9
- * {@link AUS_SYNC_METHODS} (fails at class-definition time).
10
- */
11
- export declare function syncAusUserAssets<This, Args extends unknown[], Return>(target: (this: This, ...args: Args) => Return, context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>): (this: This, ...args: Args) => Return;
12
- //# sourceMappingURL=syncAusUserAssets.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncAusUserAssets.d.ts","sourceRoot":"","sources":["../src/syncAusUserAssets.ts"],"names":[],"mappings":"AA0KA;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,SAAS,OAAO,EAAE,EAAE,MAAM,EACpE,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,IAAI,KAAK,MAAM,EAC7C,OAAO,EAAE,2BAA2B,CAClC,IAAI,EACJ,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,IAAI,KAAK,MAAM,CACtC,GACA,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,IAAI,KAAK,MAAM,CAiBvC"}
@@ -1,128 +0,0 @@
1
- import { projectLogger, createModuleLogger } from './logger.js';
2
- import { normalizeAssetId } from './utils/index.js';
3
- const log = createModuleLogger(projectLogger, 'syncAusUserAssets');
4
- /**
5
- * The decorated methods and the AUS user-assets behavior each one mirrors.
6
- */
7
- const AUS_SYNC_METHODS = {
8
- addCustomAsset: {
9
- kind: 'merge',
10
- action: 'AuthenticatedUserStorageService:importTokens',
11
- assetIdArgIndex: 1,
12
- },
13
- removeCustomAsset: {
14
- kind: 'strip',
15
- stripFrom: 'importedAssets',
16
- assetIdArgIndex: 1,
17
- },
18
- hideAsset: {
19
- kind: 'merge',
20
- action: 'AuthenticatedUserStorageService:hideTokens',
21
- assetIdArgIndex: 0,
22
- },
23
- unhideAsset: {
24
- kind: 'strip',
25
- stripFrom: 'hiddenAssets',
26
- assetIdArgIndex: 0,
27
- },
28
- };
29
- /**
30
- * The tail of each controller instance's pending AUS sync queue.
31
- */
32
- const ausSyncQueues = new WeakMap();
33
- /**
34
- * Mirror a custom-token action to AUS user assets.
35
- *
36
- * @param caller - The controller whose messenger to call AUS actions on.
37
- * @param config - The AUS behavior configured for the invoked method.
38
- * @param assetId - The CAIP-19 asset ID the method was invoked with.
39
- */
40
- async function syncUserAssetsToAus(caller, config, assetId) {
41
- const normalizedAssetId = normalizeAssetId(assetId);
42
- if (config.kind === 'merge') {
43
- await caller.messenger.call(config.action, [normalizedAssetId]);
44
- return;
45
- }
46
- const blob = await caller.messenger.call('AuthenticatedUserStorageService:getUserAssets');
47
- // No stored blob means there is nothing to strip.
48
- if (blob === null) {
49
- return;
50
- }
51
- // Already absent means there is nothing to write (avoids version churn).
52
- if (!blob[config.stripFrom].includes(normalizedAssetId)) {
53
- return;
54
- }
55
- const nextBlob = {
56
- ...blob,
57
- [config.stripFrom]: blob[config.stripFrom].filter((id) => id !== normalizedAssetId),
58
- };
59
- await caller.messenger.call('AuthenticatedUserStorageService:setUserAssets', nextBlob);
60
- }
61
- /**
62
- * Report a failed AUS sync. Never throws, so it can never block or roll back
63
- * the local state change that already happened.
64
- *
65
- * @param caller - The controller whose messenger reports the error.
66
- * @param assetId - The CAIP-19 asset ID the method was invoked with.
67
- * @param error - The error the sync failed with.
68
- */
69
- function reportAusSyncError(caller, assetId, error) {
70
- log('Failed to sync user assets to AUS', { assetId, error });
71
- try {
72
- caller.messenger.captureException?.(new Error('Failed to sync user assets to AUS', { cause: error }));
73
- }
74
- catch {
75
- // Never let telemetry throw.
76
- }
77
- }
78
- /**
79
- * Fire the AUS sync, reporting any failure instead of propagating it so it
80
- * can never block or roll back the local state change that already happened.
81
- *
82
- * @param caller - The controller whose messenger to call AUS actions on.
83
- * @param config - The AUS behavior configured for the invoked method.
84
- * @param assetId - The CAIP-19 asset ID the method was invoked with.
85
- */
86
- function fireAusSync(caller, config, assetId) {
87
- const run = async () => syncUserAssetsToAus(caller, config, assetId).catch((error) => reportAusSyncError(caller, assetId, error));
88
- // Serialize syncs per controller instance: each one is a read-modify-write
89
- // of the whole AUS blob, so a sync must not read until the previous write
90
- // has landed (and invalidated the service's cached read). When idle, start
91
- // right away; `run` never rejects, so one failure cannot stall the queue.
92
- const previous = ausSyncQueues.get(caller);
93
- const next = previous ? previous.then(run) : run();
94
- ausSyncQueues.set(caller, next);
95
- // Drop the queue once it drains, so an idle caller starts synchronously.
96
- next
97
- .then(() => {
98
- if (ausSyncQueues.get(caller) === next) {
99
- ausSyncQueues.delete(caller);
100
- }
101
- })
102
- .catch(() => undefined);
103
- }
104
- /**
105
- * Method decorator that mirrors a custom-token state change to AUS user
106
- * storage as the decorated method returns, fire-and-forget.
107
- *
108
- * @param target - The decorated custom-token method.
109
- * @param context - The decorator context.
110
- * @returns The wrapped method.
111
- * @throws If applied to a method that is not configured in
112
- * {@link AUS_SYNC_METHODS} (fails at class-definition time).
113
- */
114
- export function syncAusUserAssets(target, context) {
115
- const config = AUS_SYNC_METHODS[context.name];
116
- if (!config) {
117
- throw new Error(`@syncAusUserAssets applied to unconfigured method '${String(context.name)}'`);
118
- }
119
- return function (...args) {
120
- const caller = this;
121
- const result = target.call(this, ...args);
122
- // The local mutation is applied by the time the method returns, so fire
123
- // the mirror now rather than when post-mutation work settles.
124
- fireAusSync(caller, config, args[config.assetIdArgIndex]);
125
- return result;
126
- };
127
- }
128
- //# sourceMappingURL=syncAusUserAssets.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"syncAusUserAssets.js","sourceRoot":"","sources":["../src/syncAusUserAssets.ts"],"names":[],"mappings":"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","sourcesContent":["import type {\n AuthenticatedUserStorageServiceHideTokensAction,\n AuthenticatedUserStorageServiceImportTokensAction,\n UserAssetsBlob,\n} from '@metamask/authenticated-user-storage';\n\nimport type { AssetsControllerMessenger } from './AssetsController.js';\nimport { projectLogger, createModuleLogger } from './logger.js';\nimport type { Caip19AssetId } from './types.js';\nimport { normalizeAssetId } from './utils/index.js';\n\nconst log = createModuleLogger(projectLogger, 'syncAusUserAssets');\n\n/** The list of a user-assets blob an asset can be stripped from. */\ntype StripFromList = 'importedAssets' | 'hiddenAssets';\n\n/** Merge configuration: a single high-level AUS SDK operation. */\ntype MergeConfig = {\n kind: 'merge';\n action:\n | AuthenticatedUserStorageServiceImportTokensAction['type']\n | AuthenticatedUserStorageServiceHideTokensAction['type'];\n assetIdArgIndex: number;\n};\n\n/** Strip configuration: remove from one blob list, leaving the other untouched. */\ntype StripConfig = {\n kind: 'strip';\n stripFrom: StripFromList;\n assetIdArgIndex: number;\n};\n\ntype AusSyncConfig = MergeConfig | StripConfig;\n\n/** The controller surface the AUS sync needs (`messenger` is protected). */\ntype AusSyncCaller = {\n messenger: Pick<AssetsControllerMessenger, 'call' | 'captureException'>;\n};\n\n/**\n * The decorated methods and the AUS user-assets behavior each one mirrors.\n */\nconst AUS_SYNC_METHODS = {\n addCustomAsset: {\n kind: 'merge',\n action: 'AuthenticatedUserStorageService:importTokens',\n assetIdArgIndex: 1,\n },\n removeCustomAsset: {\n kind: 'strip',\n stripFrom: 'importedAssets',\n assetIdArgIndex: 1,\n },\n hideAsset: {\n kind: 'merge',\n action: 'AuthenticatedUserStorageService:hideTokens',\n assetIdArgIndex: 0,\n },\n unhideAsset: {\n kind: 'strip',\n stripFrom: 'hiddenAssets',\n assetIdArgIndex: 0,\n },\n} as const satisfies Record<string, AusSyncConfig>;\n\n/**\n * The tail of each controller instance's pending AUS sync queue.\n */\nconst ausSyncQueues = new WeakMap<AusSyncCaller, Promise<void>>();\n\n/**\n * Mirror a custom-token action to AUS user assets.\n *\n * @param caller - The controller whose messenger to call AUS actions on.\n * @param config - The AUS behavior configured for the invoked method.\n * @param assetId - The CAIP-19 asset ID the method was invoked with.\n */\nasync function syncUserAssetsToAus(\n caller: AusSyncCaller,\n config: AusSyncConfig,\n assetId: Caip19AssetId,\n): Promise<void> {\n const normalizedAssetId = normalizeAssetId(assetId);\n\n if (config.kind === 'merge') {\n await caller.messenger.call(config.action, [normalizedAssetId]);\n return;\n }\n\n const blob = await caller.messenger.call(\n 'AuthenticatedUserStorageService:getUserAssets',\n );\n // No stored blob means there is nothing to strip.\n if (blob === null) {\n return;\n }\n // Already absent means there is nothing to write (avoids version churn).\n if (!blob[config.stripFrom].includes(normalizedAssetId)) {\n return;\n }\n const nextBlob: UserAssetsBlob = {\n ...blob,\n [config.stripFrom]: blob[config.stripFrom].filter(\n (id) => id !== normalizedAssetId,\n ),\n };\n await caller.messenger.call(\n 'AuthenticatedUserStorageService:setUserAssets',\n nextBlob,\n );\n}\n\n/**\n * Report a failed AUS sync. Never throws, so it can never block or roll back\n * the local state change that already happened.\n *\n * @param caller - The controller whose messenger reports the error.\n * @param assetId - The CAIP-19 asset ID the method was invoked with.\n * @param error - The error the sync failed with.\n */\nfunction reportAusSyncError(\n caller: AusSyncCaller,\n assetId: Caip19AssetId,\n error: unknown,\n): void {\n log('Failed to sync user assets to AUS', { assetId, error });\n try {\n caller.messenger.captureException?.(\n new Error('Failed to sync user assets to AUS', { cause: error }),\n );\n } catch {\n // Never let telemetry throw.\n }\n}\n\n/**\n * Fire the AUS sync, reporting any failure instead of propagating it so it\n * can never block or roll back the local state change that already happened.\n *\n * @param caller - The controller whose messenger to call AUS actions on.\n * @param config - The AUS behavior configured for the invoked method.\n * @param assetId - The CAIP-19 asset ID the method was invoked with.\n */\nfunction fireAusSync(\n caller: AusSyncCaller,\n config: AusSyncConfig,\n assetId: Caip19AssetId,\n): void {\n const run = async (): Promise<void> =>\n syncUserAssetsToAus(caller, config, assetId).catch((error: unknown) =>\n reportAusSyncError(caller, assetId, error),\n );\n\n // Serialize syncs per controller instance: each one is a read-modify-write\n // of the whole AUS blob, so a sync must not read until the previous write\n // has landed (and invalidated the service's cached read). When idle, start\n // right away; `run` never rejects, so one failure cannot stall the queue.\n const previous = ausSyncQueues.get(caller);\n const next = previous ? previous.then(run) : run();\n ausSyncQueues.set(caller, next);\n // Drop the queue once it drains, so an idle caller starts synchronously.\n next\n .then(() => {\n if (ausSyncQueues.get(caller) === next) {\n ausSyncQueues.delete(caller);\n }\n })\n .catch(() => undefined);\n}\n\n/**\n * Method decorator that mirrors a custom-token state change to AUS user\n * storage as the decorated method returns, fire-and-forget.\n *\n * @param target - The decorated custom-token method.\n * @param context - The decorator context.\n * @returns The wrapped method.\n * @throws If applied to a method that is not configured in\n * {@link AUS_SYNC_METHODS} (fails at class-definition time).\n */\nexport function syncAusUserAssets<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n context: ClassMethodDecoratorContext<\n This,\n (this: This, ...args: Args) => Return\n >,\n): (this: This, ...args: Args) => Return {\n const config =\n AUS_SYNC_METHODS[context.name as keyof typeof AUS_SYNC_METHODS];\n if (!config) {\n throw new Error(\n `@syncAusUserAssets applied to unconfigured method '${String(context.name)}'`,\n );\n }\n\n return function (this: This, ...args: Args): Return {\n const caller = this as unknown as AusSyncCaller;\n const result = target.call(this, ...args);\n // The local mutation is applied by the time the method returns, so fire\n // the mirror now rather than when post-mutation work settles.\n fireAusSync(caller, config, args[config.assetIdArgIndex] as Caip19AssetId);\n return result;\n };\n}\n"]}