@metamask-previews/eth-json-rpc-middleware 21.0.0-preview-ee982ebe → 21.0.0-preview-91b0ac79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"block-cache.cjs","sourceRoot":"","sources":["../src/block-cache.ts"],"names":[],"mappings":";;;AACA,+DAAkE;AAGlE,uDAAoE;AASpE,6CAMuB;AAEvB,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,aAAa,CAAC,CAAC;AAC7D,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAMzD,EAAE;AACF,mBAAmB;AACnB,EAAE;AAEF,MAAM,kBAAkB;IAGtB;QACE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,aAAa,CAAC,cAAsB;QAClC,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;QAChE,IAAI,UAAU,GAAe,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACrD,+BAA+B;QAC/B,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,QAAQ,GAAe,EAAE,CAAC;YAChC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC;YACnC,UAAU,GAAG,QAAQ,CAAC;SACvB;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK,CAAC,GAAG,CACP,OAAuB,EACvB,oBAA4B;QAE5B,qBAAqB;QACrB,MAAM,UAAU,GAAe,IAAI,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC;QACxE,gCAAgC;QAChC,MAAM,UAAU,GAAkB,IAAA,iCAAyB,EAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC3E,OAAO,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CA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wC;YACxC,GAAG,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;YAClC,MAAM,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,oBAAoB,EAAE,GAAG,CAAC,MAAe,CAAC,CAAC;SACpE;aAAM;YACL,4BAA4B;YAC5B,GAAG,CACD,8DAA8D,EAC9D,oBAAoB,CACrB,CAAC;YACF,GAAG,CAAC,MAAM,GAAG,WAAW,CAAC;SAC1B;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC;AApGD,gEAoGC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type {\n Block,\n BlockCache,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Cache,\n JsonRpcCacheMiddleware,\n JsonRpcRequestToCache,\n} from './types';\nimport {\n cacheIdentifierForRequest,\n blockTagForRequest,\n cacheTypeForMethod,\n canCache,\n CacheStrategy,\n} from './utils/cache';\n\nconst log = createModuleLogger(projectLogger, 'block-cache');\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [undefined, null, '\\u003cnil\\u003e'];\n\ntype BlockCacheMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n//\n// Cache Strategies\n//\n\nclass BlockCacheStrategy {\n private cache: Cache;\n\n constructor() {\n this.cache = {};\n }\n\n getBlockCache(blockNumberHex: string): BlockCache {\n const blockNumber: number = Number.parseInt(blockNumberHex, 16);\n let blockCache: BlockCache = this.cache[blockNumber];\n // create new cache if necesary\n if (!blockCache) {\n const newCache: BlockCache = {};\n this.cache[blockNumber] = newCache;\n blockCache = newCache;\n }\n return blockCache;\n }\n\n async get(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n ): Promise<Block | undefined> {\n // lookup block cache\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n // lookup payload in block cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n return identifier ? blockCache[identifier] : undefined;\n }\n\n async set(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n result: Block,\n ): Promise<void> {\n // check if we can cached this result\n const canCacheResult: boolean = this.canCacheResult(request, result);\n if (!canCacheResult) {\n return;\n }\n\n // set the value in the cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n if (!identifier) {\n return;\n }\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n blockCache[identifier] = result;\n }\n\n canCacheRequest(request: JsonRpcRequest): boolean {\n // check request method\n if (!canCache(request.method)) {\n return false;\n }\n // check blockTag\n const blockTag = blockTagForRequest(request);\n\n if (blockTag === 'pending') {\n return false;\n }\n // can be cached\n return true;\n }\n\n canCacheResult(request: JsonRpcRequest, result: Block): boolean {\n // never cache empty values (e.g. undefined)\n if (emptyValues.includes(result as any)) {\n return false;\n }\n\n // check if transactions have block reference before caching\n if (\n request.method &&\n ['eth_getTransactionByHash', 'eth_getTransactionReceipt'].includes(\n request.method,\n )\n ) {\n if (\n !result?.blockHash ||\n result.blockHash ===\n '0x0000000000000000000000000000000000000000000000000000000000000000'\n ) {\n return false;\n }\n }\n // otherwise true\n return true;\n }\n\n // removes all block caches with block number lower than `oldBlockHex`\n clearBefore(oldBlockHex: string): void {\n const oldBlockNumber: number = Number.parseInt(oldBlockHex, 16);\n // clear old caches\n Object.keys(this.cache)\n .map(Number)\n .filter((num) => num < oldBlockNumber)\n .forEach((num) => delete this.cache[num]);\n }\n}\n\nexport function createBlockCacheMiddleware({\n blockTracker,\n}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n // validate options\n if (!blockTracker) {\n throw new Error(\n 'createBlockCacheMiddleware - No PollingBlockTracker specified',\n );\n }\n\n // create caching strategies\n const blockCache: BlockCacheStrategy = new BlockCacheStrategy();\n const strategies: Record<CacheStrategy, BlockCacheStrategy | undefined> = {\n [CacheStrategy.Permanent]: blockCache,\n [CacheStrategy.Block]: blockCache,\n [CacheStrategy.Fork]: blockCache,\n [CacheStrategy.Never]: undefined,\n };\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // check type and matching strategy\n const type = cacheTypeForMethod(req.method);\n const strategy = strategies[type];\n // If there's no strategy in place, pass it down the chain.\n if (!strategy) {\n return next();\n }\n\n // If the strategy can't cache this request, ignore it.\n if (!strategy.canCacheRequest(req)) {\n return next();\n }\n\n // get block reference (number or keyword)\n const requestBlockTag = blockTagForRequest(req);\n const blockTag =\n requestBlockTag && typeof requestBlockTag === 'string'\n ? requestBlockTag\n : 'latest';\n\n log('blockTag = %o, req = %o', blockTag, req);\n\n // get exact block number\n let requestedBlockNumber: string;\n if (blockTag === 'earliest') {\n // this just exists for symmetry with \"latest\"\n requestedBlockNumber = '0x00';\n } else if (blockTag === 'latest') {\n // fetch latest block number\n log('Fetching latest block number to determine cache key');\n const latestBlockNumber = await blockTracker.getLatestBlock();\n // clear all cache before latest block\n log(\n 'Clearing values stored under block numbers before %o',\n latestBlockNumber,\n );\n blockCache.clearBefore(latestBlockNumber);\n requestedBlockNumber = latestBlockNumber;\n } else {\n // We have a hex number\n requestedBlockNumber = blockTag;\n }\n // end on a hit, continue on a miss\n const cacheResult: Block | undefined = await strategy.get(\n req,\n requestedBlockNumber,\n );\n if (cacheResult === undefined) {\n // cache miss\n // wait for other middleware to handle request\n log(\n 'No cache stored under block number %o, carrying request forward',\n requestedBlockNumber,\n );\n await next();\n\n // add result to cache\n // it's safe to cast res.result as Block, due to runtime type checks\n // performed when strategy.set is called\n log('Populating cache with', res);\n await strategy.set(req, requestedBlockNumber, res.result as Block);\n } else {\n // fill in result from cache\n log(\n 'Cache hit, reusing cache result stored under block number %o',\n requestedBlockNumber,\n );\n res.result = cacheResult;\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M,IAAI,EAAE,CAAC;YAEb,sBAAsB;YACtB,oEAAoE;YACpE,wCAAwC;YACxC,GAAG,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;YAClC,MAAM,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,oBAAoB,EAAE,GAAG,CAAC,MAAe,CAAC,CAAC;QACrE,CAAC;aAAM,CAAC;YACN,4BAA4B;YAC5B,GAAG,CACD,8DAA8D,EAC9D,oBAAoB,CACrB,CAAC;YACF,GAAG,CAAC,MAAM,GAAG,WAAW,CAAC;QAC3B,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC;AApGD,gEAoGC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type {\n Block,\n BlockCache,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Cache,\n JsonRpcCacheMiddleware,\n JsonRpcRequestToCache,\n} from './types';\nimport {\n cacheIdentifierForRequest,\n blockTagForRequest,\n cacheTypeForMethod,\n canCache,\n CacheStrategy,\n} from './utils/cache';\n\nconst log = createModuleLogger(projectLogger, 'block-cache');\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [undefined, null, '\\u003cnil\\u003e'];\n\ntype BlockCacheMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n//\n// Cache Strategies\n//\n\nclass BlockCacheStrategy {\n private cache: Cache;\n\n constructor() {\n this.cache = {};\n }\n\n getBlockCache(blockNumberHex: string): BlockCache {\n const blockNumber: number = Number.parseInt(blockNumberHex, 16);\n let blockCache: BlockCache = this.cache[blockNumber];\n // create new cache if necesary\n if (!blockCache) {\n const newCache: BlockCache = {};\n this.cache[blockNumber] = newCache;\n blockCache = newCache;\n }\n return blockCache;\n }\n\n async get(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n ): Promise<Block | undefined> {\n // lookup block cache\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n // lookup payload in block cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n return identifier ? blockCache[identifier] : undefined;\n }\n\n async set(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n result: Block,\n ): Promise<void> {\n // check if we can cached this result\n const canCacheResult: boolean = this.canCacheResult(request, result);\n if (!canCacheResult) {\n return;\n }\n\n // set the value in the cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n if (!identifier) {\n return;\n }\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n blockCache[identifier] = result;\n }\n\n canCacheRequest(request: JsonRpcRequest): boolean {\n // check request method\n if (!canCache(request.method)) {\n return false;\n }\n // check blockTag\n const blockTag = blockTagForRequest(request);\n\n if (blockTag === 'pending') {\n return false;\n }\n // can be cached\n return true;\n }\n\n canCacheResult(request: JsonRpcRequest, result: Block): boolean {\n // never cache empty values (e.g. undefined)\n if (emptyValues.includes(result as any)) {\n return false;\n }\n\n // check if transactions have block reference before caching\n if (\n request.method &&\n ['eth_getTransactionByHash', 'eth_getTransactionReceipt'].includes(\n request.method,\n )\n ) {\n if (\n !result?.blockHash ||\n result.blockHash ===\n '0x0000000000000000000000000000000000000000000000000000000000000000'\n ) {\n return false;\n }\n }\n // otherwise true\n return true;\n }\n\n // removes all block caches with block number lower than `oldBlockHex`\n clearBefore(oldBlockHex: string): void {\n const oldBlockNumber: number = Number.parseInt(oldBlockHex, 16);\n // clear old caches\n Object.keys(this.cache)\n .map(Number)\n .filter((num) => num < oldBlockNumber)\n .forEach((num) => delete this.cache[num]);\n }\n}\n\nexport function createBlockCacheMiddleware({\n blockTracker,\n}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n // validate options\n if (!blockTracker) {\n throw new Error(\n 'createBlockCacheMiddleware - No PollingBlockTracker specified',\n );\n }\n\n // create caching strategies\n const blockCache: BlockCacheStrategy = new BlockCacheStrategy();\n const strategies: Record<CacheStrategy, BlockCacheStrategy | undefined> = {\n [CacheStrategy.Permanent]: blockCache,\n [CacheStrategy.Block]: blockCache,\n [CacheStrategy.Fork]: blockCache,\n [CacheStrategy.Never]: undefined,\n };\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // check type and matching strategy\n const type = cacheTypeForMethod(req.method);\n const strategy = strategies[type];\n // If there's no strategy in place, pass it down the chain.\n if (!strategy) {\n return next();\n }\n\n // If the strategy can't cache this request, ignore it.\n if (!strategy.canCacheRequest(req)) {\n return next();\n }\n\n // get block reference (number or keyword)\n const requestBlockTag = blockTagForRequest(req);\n const blockTag =\n requestBlockTag && typeof requestBlockTag === 'string'\n ? requestBlockTag\n : 'latest';\n\n log('blockTag = %o, req = %o', blockTag, req);\n\n // get exact block number\n let requestedBlockNumber: string;\n if (blockTag === 'earliest') {\n // this just exists for symmetry with \"latest\"\n requestedBlockNumber = '0x00';\n } else if (blockTag === 'latest') {\n // fetch latest block number\n log('Fetching latest block number to determine cache key');\n const latestBlockNumber = await blockTracker.getLatestBlock();\n // clear all cache before latest block\n log(\n 'Clearing values stored under block numbers before %o',\n latestBlockNumber,\n );\n blockCache.clearBefore(latestBlockNumber);\n requestedBlockNumber = latestBlockNumber;\n } else {\n // We have a hex number\n requestedBlockNumber = blockTag;\n }\n // end on a hit, continue on a miss\n const cacheResult: Block | undefined = await strategy.get(\n req,\n requestedBlockNumber,\n );\n if (cacheResult === undefined) {\n // cache miss\n // wait for other middleware to handle request\n log(\n 'No cache stored under block number %o, carrying request forward',\n requestedBlockNumber,\n );\n await next();\n\n // add result to cache\n // it's safe to cast res.result as Block, due to runtime type checks\n // performed when strategy.set is called\n log('Populating cache with', res);\n await strategy.set(req, requestedBlockNumber, res.result as Block);\n } else {\n // fill in result from cache\n log(\n 'Cache hit, reusing cache result stored under block number %o',\n requestedBlockNumber,\n );\n res.result = cacheResult;\n }\n return undefined;\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-cache.mjs","sourceRoot":"","sources":["../src/block-cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAGlE,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AASpE,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACd,0BAAsB;AAEvB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC7D,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAMzD,EAAE;AACF,mBAAmB;AACnB,EAAE;AAEF,MAAM,kBAAkB;IAGtB;QACE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,aAAa,CAAC,cAAsB;QAClC,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;QAChE,IAAI,UAAU,GAAe,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACrD,+BAA+B;QAC/B,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,QAAQ,GAAe,EAAE,CAAC;YAChC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC;YACnC,UAAU,GAAG,QAAQ,CAAC;SACvB;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK,CAAC,GAAG,CACP,OAAuB,EACvB,oBAA4B;QAE5B,qBAAqB;QACrB,MAAM,UAAU,GAAe,IAAI,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC;QACxE,gCAAgC;QAChC,MAAM,UAAU,GAAkB,yBAAyB,CAAC,OA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E,CAAC;YAEb,sBAAsB;YACtB,oEAAoE;YACpE,wCAAwC;YACxC,GAAG,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;YAClC,MAAM,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,oBAAoB,EAAE,GAAG,CAAC,MAAe,CAAC,CAAC;SACpE;aAAM;YACL,4BAA4B;YAC5B,GAAG,CACD,8DAA8D,EAC9D,oBAAoB,CACrB,CAAC;YACF,GAAG,CAAC,MAAM,GAAG,WAAW,CAAC;SAC1B;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type {\n Block,\n BlockCache,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Cache,\n JsonRpcCacheMiddleware,\n JsonRpcRequestToCache,\n} from './types';\nimport {\n cacheIdentifierForRequest,\n blockTagForRequest,\n cacheTypeForMethod,\n canCache,\n CacheStrategy,\n} from './utils/cache';\n\nconst log = createModuleLogger(projectLogger, 'block-cache');\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [undefined, null, '\\u003cnil\\u003e'];\n\ntype BlockCacheMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n//\n// Cache Strategies\n//\n\nclass BlockCacheStrategy {\n private cache: Cache;\n\n constructor() {\n this.cache = {};\n }\n\n getBlockCache(blockNumberHex: string): BlockCache {\n const blockNumber: number = Number.parseInt(blockNumberHex, 16);\n let blockCache: BlockCache = this.cache[blockNumber];\n // create new cache if necesary\n if (!blockCache) {\n const newCache: BlockCache = {};\n this.cache[blockNumber] = newCache;\n blockCache = newCache;\n }\n return blockCache;\n }\n\n async get(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n ): Promise<Block | undefined> {\n // lookup block cache\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n // lookup payload in block cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n return identifier ? blockCache[identifier] : undefined;\n }\n\n async set(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n result: Block,\n ): Promise<void> {\n // check if we can cached this result\n const canCacheResult: boolean = this.canCacheResult(request, result);\n if (!canCacheResult) {\n return;\n }\n\n // set the value in the cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n if (!identifier) {\n return;\n }\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n blockCache[identifier] = result;\n }\n\n canCacheRequest(request: JsonRpcRequest): boolean {\n // check request method\n if (!canCache(request.method)) {\n return false;\n }\n // check blockTag\n const blockTag = blockTagForRequest(request);\n\n if (blockTag === 'pending') {\n return false;\n }\n // can be cached\n return true;\n }\n\n canCacheResult(request: JsonRpcRequest, result: Block): boolean {\n // never cache empty values (e.g. undefined)\n if (emptyValues.includes(result as any)) {\n return false;\n }\n\n // check if transactions have block reference before caching\n if (\n request.method &&\n ['eth_getTransactionByHash', 'eth_getTransactionReceipt'].includes(\n request.method,\n )\n ) {\n if (\n !result?.blockHash ||\n result.blockHash ===\n '0x0000000000000000000000000000000000000000000000000000000000000000'\n ) {\n return false;\n }\n }\n // otherwise true\n return true;\n }\n\n // removes all block caches with block number lower than `oldBlockHex`\n clearBefore(oldBlockHex: string): void {\n const oldBlockNumber: number = Number.parseInt(oldBlockHex, 16);\n // clear old caches\n Object.keys(this.cache)\n .map(Number)\n .filter((num) => num < oldBlockNumber)\n .forEach((num) => delete this.cache[num]);\n }\n}\n\nexport function createBlockCacheMiddleware({\n blockTracker,\n}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n // validate options\n if (!blockTracker) {\n throw new Error(\n 'createBlockCacheMiddleware - No PollingBlockTracker specified',\n );\n }\n\n // create caching strategies\n const blockCache: BlockCacheStrategy = new BlockCacheStrategy();\n const strategies: Record<CacheStrategy, BlockCacheStrategy | undefined> = {\n [CacheStrategy.Permanent]: blockCache,\n [CacheStrategy.Block]: blockCache,\n [CacheStrategy.Fork]: blockCache,\n [CacheStrategy.Never]: undefined,\n };\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // check type and matching strategy\n const type = cacheTypeForMethod(req.method);\n const strategy = strategies[type];\n // If there's no strategy in place, pass it down the chain.\n if (!strategy) {\n return next();\n }\n\n // If the strategy can't cache this request, ignore it.\n if (!strategy.canCacheRequest(req)) {\n return next();\n }\n\n // get block reference (number or keyword)\n const requestBlockTag = blockTagForRequest(req);\n const blockTag =\n requestBlockTag && typeof requestBlockTag === 'string'\n ? requestBlockTag\n : 'latest';\n\n log('blockTag = %o, req = %o', blockTag, req);\n\n // get exact block number\n let requestedBlockNumber: string;\n if (blockTag === 'earliest') {\n // this just exists for symmetry with \"latest\"\n requestedBlockNumber = '0x00';\n } else if (blockTag === 'latest') {\n // fetch latest block number\n log('Fetching latest block number to determine cache key');\n const latestBlockNumber = await blockTracker.getLatestBlock();\n // clear all cache before latest block\n log(\n 'Clearing values stored under block numbers before %o',\n latestBlockNumber,\n );\n blockCache.clearBefore(latestBlockNumber);\n requestedBlockNumber = latestBlockNumber;\n } else {\n // We have a hex number\n requestedBlockNumber = blockTag;\n }\n // end on a hit, continue on a miss\n const cacheResult: Block | undefined = await strategy.get(\n req,\n requestedBlockNumber,\n );\n if (cacheResult === undefined) {\n // cache miss\n // wait for other middleware to handle request\n log(\n 'No cache stored under block number %o, carrying request forward',\n requestedBlockNumber,\n );\n await next();\n\n // add result to cache\n // it's safe to cast res.result as Block, due to runtime type checks\n // performed when strategy.set is called\n log('Populating cache with', res);\n await strategy.set(req, requestedBlockNumber, res.result as Block);\n } else {\n // fill in result from cache\n log(\n 'Cache hit, reusing cache result stored under block number %o',\n requestedBlockNumber,\n );\n res.result = cacheResult;\n }\n return undefined;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"block-cache.mjs","sourceRoot":"","sources":["../src/block-cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAGlE,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AASpE,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,kBAAkB,EAClB,QAAQ,EACR,aAAa,EACd,0BAAsB;AAEvB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC7D,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,SAAS,EAAE,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAMzD,EAAE;AACF,mBAAmB;AACnB,EAAE;AAEF,MAAM,kBAAkB;IAGtB;QACE,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;IAClB,CAAC;IAED,aAAa,CAAC,cAAsB;QAClC,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC;QAChE,IAAI,UAAU,GAAe,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACrD,+BAA+B;QAC/B,IAAI,CAAC,UAAU,EAAE,CAAC;YAChB,MAAM,QAAQ,GAAe,EAAE,CAAC;YAChC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC;YACnC,UAAU,GAAG,QAAQ,CAAC;QACxB,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,KAAK,CAAC,GAAG,CACP,OAAuB,EACvB,oBAA4B;QAE5B,qBAAqB;QACrB,MAAM,UAAU,GAAe,IAAI,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC;QACxE,gCAAgC;QAChC,MAAM,UAAU,GAAkB,yBAAyB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC3E,OAAO,UAA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AAI,WAAW,KAAK,SAAS,EAAE,CAAC;YAC9B,aAAa;YACb,8CAA8C;YAC9C,GAAG,CACD,iEAAiE,EACjE,oBAAoB,CACrB,CAAC;YACF,MAAM,IAAI,EAAE,CAAC;YAEb,sBAAsB;YACtB,oEAAoE;YACpE,wCAAwC;YACxC,GAAG,CAAC,uBAAuB,EAAE,GAAG,CAAC,CAAC;YAClC,MAAM,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,oBAAoB,EAAE,GAAG,CAAC,MAAe,CAAC,CAAC;QACrE,CAAC;aAAM,CAAC;YACN,4BAA4B;YAC5B,GAAG,CACD,8DAA8D,EAC9D,oBAAoB,CACrB,CAAC;YACF,GAAG,CAAC,MAAM,GAAG,WAAW,CAAC;QAC3B,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type {\n Block,\n BlockCache,\n // eslint-disable-next-line @typescript-eslint/no-shadow\n Cache,\n JsonRpcCacheMiddleware,\n JsonRpcRequestToCache,\n} from './types';\nimport {\n cacheIdentifierForRequest,\n blockTagForRequest,\n cacheTypeForMethod,\n canCache,\n CacheStrategy,\n} from './utils/cache';\n\nconst log = createModuleLogger(projectLogger, 'block-cache');\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [undefined, null, '\\u003cnil\\u003e'];\n\ntype BlockCacheMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n//\n// Cache Strategies\n//\n\nclass BlockCacheStrategy {\n private cache: Cache;\n\n constructor() {\n this.cache = {};\n }\n\n getBlockCache(blockNumberHex: string): BlockCache {\n const blockNumber: number = Number.parseInt(blockNumberHex, 16);\n let blockCache: BlockCache = this.cache[blockNumber];\n // create new cache if necesary\n if (!blockCache) {\n const newCache: BlockCache = {};\n this.cache[blockNumber] = newCache;\n blockCache = newCache;\n }\n return blockCache;\n }\n\n async get(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n ): Promise<Block | undefined> {\n // lookup block cache\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n // lookup payload in block cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n return identifier ? blockCache[identifier] : undefined;\n }\n\n async set(\n request: JsonRpcRequest,\n requestedBlockNumber: string,\n result: Block,\n ): Promise<void> {\n // check if we can cached this result\n const canCacheResult: boolean = this.canCacheResult(request, result);\n if (!canCacheResult) {\n return;\n }\n\n // set the value in the cache\n const identifier: string | null = cacheIdentifierForRequest(request, true);\n if (!identifier) {\n return;\n }\n const blockCache: BlockCache = this.getBlockCache(requestedBlockNumber);\n blockCache[identifier] = result;\n }\n\n canCacheRequest(request: JsonRpcRequest): boolean {\n // check request method\n if (!canCache(request.method)) {\n return false;\n }\n // check blockTag\n const blockTag = blockTagForRequest(request);\n\n if (blockTag === 'pending') {\n return false;\n }\n // can be cached\n return true;\n }\n\n canCacheResult(request: JsonRpcRequest, result: Block): boolean {\n // never cache empty values (e.g. undefined)\n if (emptyValues.includes(result as any)) {\n return false;\n }\n\n // check if transactions have block reference before caching\n if (\n request.method &&\n ['eth_getTransactionByHash', 'eth_getTransactionReceipt'].includes(\n request.method,\n )\n ) {\n if (\n !result?.blockHash ||\n result.blockHash ===\n '0x0000000000000000000000000000000000000000000000000000000000000000'\n ) {\n return false;\n }\n }\n // otherwise true\n return true;\n }\n\n // removes all block caches with block number lower than `oldBlockHex`\n clearBefore(oldBlockHex: string): void {\n const oldBlockNumber: number = Number.parseInt(oldBlockHex, 16);\n // clear old caches\n Object.keys(this.cache)\n .map(Number)\n .filter((num) => num < oldBlockNumber)\n .forEach((num) => delete this.cache[num]);\n }\n}\n\nexport function createBlockCacheMiddleware({\n blockTracker,\n}: BlockCacheMiddlewareOptions = {}): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n // validate options\n if (!blockTracker) {\n throw new Error(\n 'createBlockCacheMiddleware - No PollingBlockTracker specified',\n );\n }\n\n // create caching strategies\n const blockCache: BlockCacheStrategy = new BlockCacheStrategy();\n const strategies: Record<CacheStrategy, BlockCacheStrategy | undefined> = {\n [CacheStrategy.Permanent]: blockCache,\n [CacheStrategy.Block]: blockCache,\n [CacheStrategy.Fork]: blockCache,\n [CacheStrategy.Never]: undefined,\n };\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // check type and matching strategy\n const type = cacheTypeForMethod(req.method);\n const strategy = strategies[type];\n // If there's no strategy in place, pass it down the chain.\n if (!strategy) {\n return next();\n }\n\n // If the strategy can't cache this request, ignore it.\n if (!strategy.canCacheRequest(req)) {\n return next();\n }\n\n // get block reference (number or keyword)\n const requestBlockTag = blockTagForRequest(req);\n const blockTag =\n requestBlockTag && typeof requestBlockTag === 'string'\n ? requestBlockTag\n : 'latest';\n\n log('blockTag = %o, req = %o', blockTag, req);\n\n // get exact block number\n let requestedBlockNumber: string;\n if (blockTag === 'earliest') {\n // this just exists for symmetry with \"latest\"\n requestedBlockNumber = '0x00';\n } else if (blockTag === 'latest') {\n // fetch latest block number\n log('Fetching latest block number to determine cache key');\n const latestBlockNumber = await blockTracker.getLatestBlock();\n // clear all cache before latest block\n log(\n 'Clearing values stored under block numbers before %o',\n latestBlockNumber,\n );\n blockCache.clearBefore(latestBlockNumber);\n requestedBlockNumber = latestBlockNumber;\n } else {\n // We have a hex number\n requestedBlockNumber = blockTag;\n }\n // end on a hit, continue on a miss\n const cacheResult: Block | undefined = await strategy.get(\n req,\n requestedBlockNumber,\n );\n if (cacheResult === undefined) {\n // cache miss\n // wait for other middleware to handle request\n log(\n 'No cache stored under block number %o, carrying request forward',\n requestedBlockNumber,\n );\n await next();\n\n // add result to cache\n // it's safe to cast res.result as Block, due to runtime type checks\n // performed when strategy.set is called\n log('Populating cache with', res);\n await strategy.set(req, requestedBlockNumber, res.result as Block);\n } else {\n // fill in result from cache\n log(\n 'Cache hit, reusing cache result stored under block number %o',\n requestedBlockNumber,\n );\n res.result = cacheResult;\n }\n return undefined;\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-ref-rewrite.cjs","sourceRoot":"","sources":["../src/block-ref-rewrite.ts"],"names":[],"mappings":";;;AAEA,+DAAkE;AAGlE,6CAAmD;AAMnD;;;;;;;GAOG;AACH,SAAgB,+BAA+B,CAAC,EAC9C,YAAY,MACwB,EAAE;IAItC,IAAI,CAAC,YAAY,EAAE;QACjB,MAAM,KAAK,CACT,yEAAyE,CAC1E,CAAC;KACH;IAED,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACrD,MAAM,aAAa,GAAuB,IAAA,0BAAkB,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzE,IAAI,aAAa,KAAK,SAAS,EAAE;YAC/B,OAAO,IAAI,EAAE,CAAC;SACf;QAED,MAAM,QAAQ,GACZ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC;YACpD,CAAC,CAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAY;YACvC,CAAC,CAAC,oCAAoC;gBACpC,QAAQ,CAAC;QAEf,IAAI,QAAQ,KAAK,QAAQ,EAAE;YACzB,OAAO,IAAI,EAAE,CAAC;SACf;QAED,mDAAmD;QACnD,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAC7B,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;SAC/C;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAnCD,0EAmCC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefRewriteMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n/**\n * Creates a middleware that rewrites \"latest\" block references to the known\n * latest block number from a block tracker.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockRefRewriteMiddleware({\n blockTracker,\n}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n if (!blockTracker) {\n throw Error(\n 'BlockRefRewriteMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, _res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : // omitted blockRef implies \"latest\"\n 'latest';\n\n if (blockRef !== 'latest') {\n return next();\n }\n\n // rewrite blockRef to block-tracker's block number\n const latestBlockNumber = await blockTracker.getLatestBlock();\n if (Array.isArray(req.params)) {\n req.params[blockRefIndex] = latestBlockNumber;\n }\n return next();\n });\n}\n"]}
1
+ {"version":3,"file":"block-ref-rewrite.cjs","sourceRoot":"","sources":["../src/block-ref-rewrite.ts"],"names":[],"mappings":";;;AAEA,+DAAkE;AAGlE,6CAAmD;AAMnD;;;;;;;GAOG;AACH,SAAgB,+BAA+B,CAAC,EAC9C,YAAY,MACwB,EAAE;IAItC,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,KAAK,CACT,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IAED,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACrD,MAAM,aAAa,GAAuB,IAAA,0BAAkB,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzE,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,GACZ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC;YACpD,CAAC,CAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAY;YACvC,CAAC,CAAC,oCAAoC;gBACpC,QAAQ,CAAC;QAEf,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC1B,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,mDAAmD;QACnD,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YAC9B,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;QAChD,CAAC;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAnCD,0EAmCC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefRewriteMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n/**\n * Creates a middleware that rewrites \"latest\" block references to the known\n * latest block number from a block tracker.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockRefRewriteMiddleware({\n blockTracker,\n}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n if (!blockTracker) {\n throw Error(\n 'BlockRefRewriteMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, _res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : // omitted blockRef implies \"latest\"\n 'latest';\n\n if (blockRef !== 'latest') {\n return next();\n }\n\n // rewrite blockRef to block-tracker's block number\n const latestBlockNumber = await blockTracker.getLatestBlock();\n if (Array.isArray(req.params)) {\n req.params[blockRefIndex] = latestBlockNumber;\n }\n return next();\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-ref-rewrite.mjs","sourceRoot":"","sources":["../src/block-ref-rewrite.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAGlE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AAMnD;;;;;;;GAOG;AACH,MAAM,UAAU,+BAA+B,CAAC,EAC9C,YAAY,MACwB,EAAE;IAItC,IAAI,CAAC,YAAY,EAAE;QACjB,MAAM,KAAK,CACT,yEAAyE,CAC1E,CAAC;KACH;IAED,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACrD,MAAM,aAAa,GAAuB,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzE,IAAI,aAAa,KAAK,SAAS,EAAE;YAC/B,OAAO,IAAI,EAAE,CAAC;SACf;QAED,MAAM,QAAQ,GACZ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC;YACpD,CAAC,CAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAY;YACvC,CAAC,CAAC,oCAAoC;gBACpC,QAAQ,CAAC;QAEf,IAAI,QAAQ,KAAK,QAAQ,EAAE;YACzB,OAAO,IAAI,EAAE,CAAC;SACf;QAED,mDAAmD;QACnD,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAC7B,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;SAC/C;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefRewriteMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n/**\n * Creates a middleware that rewrites \"latest\" block references to the known\n * latest block number from a block tracker.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockRefRewriteMiddleware({\n blockTracker,\n}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n if (!blockTracker) {\n throw Error(\n 'BlockRefRewriteMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, _res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : // omitted blockRef implies \"latest\"\n 'latest';\n\n if (blockRef !== 'latest') {\n return next();\n }\n\n // rewrite blockRef to block-tracker's block number\n const latestBlockNumber = await blockTracker.getLatestBlock();\n if (Array.isArray(req.params)) {\n req.params[blockRefIndex] = latestBlockNumber;\n }\n return next();\n });\n}\n"]}
1
+ {"version":3,"file":"block-ref-rewrite.mjs","sourceRoot":"","sources":["../src/block-ref-rewrite.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAGlE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AAMnD;;;;;;;GAOG;AACH,MAAM,UAAU,+BAA+B,CAAC,EAC9C,YAAY,MACwB,EAAE;IAItC,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,KAAK,CACT,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IAED,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;QACrD,MAAM,aAAa,GAAuB,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACzE,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,GACZ,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC;YACpD,CAAC,CAAE,GAAG,CAAC,MAAM,CAAC,aAAa,CAAY;YACvC,CAAC,CAAC,oCAAoC;gBACpC,QAAQ,CAAC;QAEf,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC1B,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,mDAAmD;QACnD,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YAC9B,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;QAChD,CAAC;QACD,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\n\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefRewriteMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n};\n\n/**\n * Creates a middleware that rewrites \"latest\" block references to the known\n * latest block number from a block tracker.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockRefRewriteMiddleware({\n blockTracker,\n}: BlockRefRewriteMiddlewareOptions = {}): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n if (!blockTracker) {\n throw Error(\n 'BlockRefRewriteMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, _res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : // omitted blockRef implies \"latest\"\n 'latest';\n\n if (blockRef !== 'latest') {\n return next();\n }\n\n // rewrite blockRef to block-tracker's block number\n const latestBlockNumber = await blockTracker.getLatestBlock();\n if (Array.isArray(req.params)) {\n req.params[blockRefIndex] = latestBlockNumber;\n }\n return next();\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-ref.cjs","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":";;;AAGA,+DAAkE;AAElE,qCAAmC;AAEnC,uDAAoE;AAEpE,6CAAmD;AAOnD,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,WAAW,CAAC,CAAC;AAE3D,SAAgB,wBA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AAM,QAAQ,CAAC,OAAO,CAAuB,YAAY,CAAC,CAAC;QAExE,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AApDD,4DAoDC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n provider?: InternalProvider;\n};\n\nconst log = createModuleLogger(projectLogger, 'block-ref');\n\nexport function createBlockRefMiddleware({\n provider,\n blockTracker,\n}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error('BlockRefMiddleware - mandatory \"provider\" option is missing.');\n }\n\n if (!blockTracker) {\n throw Error(\n 'BlockRefMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex = blockTagParamIndex(req.method);\n\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef = Array.isArray(req.params)\n ? (req.params[blockRefIndex] ?? 'latest')\n : 'latest';\n\n // skip if not \"latest\"\n if (blockRef !== 'latest') {\n log('blockRef is not \"latest\", carrying request forward');\n return next();\n }\n\n // lookup latest block\n const latestBlockNumber = await blockTracker.getLatestBlock();\n log(\n `blockRef is \"latest\", setting param ${blockRefIndex} to latest block ${latestBlockNumber}`,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n\n if (Array.isArray(childRequest.params)) {\n childRequest.params[blockRefIndex] = latestBlockNumber;\n }\n\n // perform child request\n log('Performing another request %o', childRequest);\n // copy child result onto original response\n res.result = await provider.request<JsonRpcParams, Block>(childRequest);\n\n return undefined;\n });\n}\n"]}
1
+ {"version":3,"file":"block-ref.cjs","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":";;;AAGA,+DAAkE;AAElE,qCAAmC;AAEnC,uDAAoE;AAEpE,6CAAmD;AAOnD,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,WAAW,CAAC,CAAC;AAE3D,SAAgB,wBAAwB,CAAC,EACvC,QAAQ,EACR,YAAY,MACiB,EAAE;IAC/B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,KAAK,CAAC,8DAA8D,CAAC,CAAC;IAC9E,CAAC;IAED,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,KAAK,CACT,kEAAkE,CACnE,CAAC;IACJ,CAAC;IAED,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,aAAa,GAAG,IAAA,0BAAkB,EAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAErD,2CAA2C;QAC3C,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YAChC,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACxC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,QAAQ,CAAC;YACzC,CAAC,CAAC,QAAQ,CAAC;QAEb,uBAAuB;QACvB,IAAI,QAAQ,KAAK,QAAQ,EAAE,CAAC;YAC1B,GAAG,CAAC,oDAAoD,CAAC,CAAC;YAC1D,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QAED,sBAAsB;QACtB,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,GAAG,CACD,uCAAuC,aAAa,oBAAoB,iBAAiB,EAAE,CAC5F,CAAC;QAEF,+CAA+C;QAC/C,MAAM,YAAY,GAAG,IAAA,YAAK,EAAC,GAAG,CAAC,CAAC;QAEhC,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;YACvC,YAAY,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;QACzD,CAAC;QAED,wBAAwB;QACxB,GAAG,CAAC,+BAA+B,EAAE,YAAY,CAAC,CAAC;QACnD,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAuB,YAAY,CAAC,CAAC;QAExE,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AApDD,4DAoDC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n provider?: InternalProvider;\n};\n\nconst log = createModuleLogger(projectLogger, 'block-ref');\n\nexport function createBlockRefMiddleware({\n provider,\n blockTracker,\n}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error('BlockRefMiddleware - mandatory \"provider\" option is missing.');\n }\n\n if (!blockTracker) {\n throw Error(\n 'BlockRefMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex = blockTagParamIndex(req.method);\n\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef = Array.isArray(req.params)\n ? (req.params[blockRefIndex] ?? 'latest')\n : 'latest';\n\n // skip if not \"latest\"\n if (blockRef !== 'latest') {\n log('blockRef is not \"latest\", carrying request forward');\n return next();\n }\n\n // lookup latest block\n const latestBlockNumber = await blockTracker.getLatestBlock();\n log(\n `blockRef is \"latest\", setting param ${blockRefIndex} to latest block ${latestBlockNumber}`,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n\n if (Array.isArray(childRequest.params)) {\n childRequest.params[blockRefIndex] = latestBlockNumber;\n }\n\n // perform child request\n log('Performing another request %o', childRequest);\n // copy child result onto original response\n res.result = await provider.request<JsonRpcParams, Block>(childRequest);\n\n return undefined;\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-ref.mjs","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAElE,OAAO,EAAE,KAAK,EAAE,mBAAmB;AAEnC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AAOnD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;AAE3D,MAAM,UAAU,wBAAwB,CAAC,EACvC,QAAQ,EACR,YAAY,MACiB,EAAE;IAC/B,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,KAAK,CAAC,8DAA8D,CAAC,CAAC;KAC7E;IAED,IAAI,CAAC,YAAY,EAAE;QACjB,MAAM,KAAK,CACT,kEAAkE,CACnE,CAAC;KACH;IAED,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,MAAM,aAAa,GAAG,kBAAkB,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAErD,2CAA2C;QAC3C,IAAI,aAAa,KAAK,SAAS,EAAE;YAC/B,OAAO,IAAI,EAAE,CAAC;SACf;QAED,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACxC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,QAAQ,CAAC;YACzC,CAAC,CAAC,QAAQ,CAAC;QAEb,uBAAuB;QACvB,IAAI,QAAQ,KAAK,QAAQ,EAAE;YACzB,GAAG,CAAC,oDAAoD,CAAC,CAAC;YAC1D,OAAO,IAAI,EAAE,CAAC;SACf;QAED,sBAAsB;QACtB,MAAM,iBAAiB,GAAG,MAAM,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9D,GAAG,CACD,uCAAuC,aAAa,oBAAoB,iBAAiB,EAAE,CAC5F,CAAC;QAEF,+CAA+C;QAC/C,MAAM,YAAY,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;QAEhC,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC,EAAE;YACtC,YAAY,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,iBAAiB,CAAC;SACxD;QAED,wBAAwB;QACxB,GAAG,CAAC,+BAA+B,EAAE,YAAY,CAAC,CAAC;QACnD,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAuB,YAAY,CAAC,CAAC;QAExE,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n provider?: InternalProvider;\n};\n\nconst log = createModuleLogger(projectLogger, 'block-ref');\n\nexport function createBlockRefMiddleware({\n provider,\n blockTracker,\n}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error('BlockRefMiddleware - mandatory \"provider\" option is missing.');\n }\n\n if (!blockTracker) {\n throw Error(\n 'BlockRefMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex = blockTagParamIndex(req.method);\n\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef = Array.isArray(req.params)\n ? (req.params[blockRefIndex] ?? 'latest')\n : 'latest';\n\n // skip if not \"latest\"\n if (blockRef !== 'latest') {\n log('blockRef is not \"latest\", carrying request forward');\n return next();\n }\n\n // lookup latest block\n const latestBlockNumber = await blockTracker.getLatestBlock();\n log(\n `blockRef is \"latest\", setting param ${blockRefIndex} to latest block ${latestBlockNumber}`,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n\n if (Array.isArray(childRequest.params)) {\n childRequest.params[blockRefIndex] = latestBlockNumber;\n }\n\n // perform child request\n log('Performing another request %o', childRequest);\n // copy child result onto original response\n res.result = await provider.request<JsonRpcParams, Block>(childRequest);\n\n return undefined;\n });\n}\n"]}
1
+ {"version":3,"file":"block-ref.mjs","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAElE,OAAO,EAAE,KAAK,EAAE,mBAAmB;AAEnC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AAOnD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;AAE3D,MAAM,UAAU,wBAAwB,CAAC,EACvC,QAAQ,EACR,YAAY,MACiB,EAAE;IAC/B,IAAI,CAAC,Q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O,CAAuB,YAAY,CAAC,CAAC;QAExE,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\n\ntype BlockRefMiddlewareOptions = {\n blockTracker?: PollingBlockTracker;\n provider?: InternalProvider;\n};\n\nconst log = createModuleLogger(projectLogger, 'block-ref');\n\nexport function createBlockRefMiddleware({\n provider,\n blockTracker,\n}: BlockRefMiddlewareOptions = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error('BlockRefMiddleware - mandatory \"provider\" option is missing.');\n }\n\n if (!blockTracker) {\n throw Error(\n 'BlockRefMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex = blockTagParamIndex(req.method);\n\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n\n const blockRef = Array.isArray(req.params)\n ? (req.params[blockRefIndex] ?? 'latest')\n : 'latest';\n\n // skip if not \"latest\"\n if (blockRef !== 'latest') {\n log('blockRef is not \"latest\", carrying request forward');\n return next();\n }\n\n // lookup latest block\n const latestBlockNumber = await blockTracker.getLatestBlock();\n log(\n `blockRef is \"latest\", setting param ${blockRefIndex} to latest block ${latestBlockNumber}`,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n\n if (Array.isArray(childRequest.params)) {\n childRequest.params[blockRefIndex] = latestBlockNumber;\n }\n\n // perform child request\n log('Performing another request %o', childRequest);\n // copy child result onto original response\n res.result = await provider.request<JsonRpcParams, Block>(childRequest);\n\n return undefined;\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-tracker-inspector.cjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":";;;AAEA,+DAAkE;AAClE,2CAA8C;AAO9C,uDAAoE;AAEpE,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,yBAAyB,CAAC,CAAC;AACzE,MAAM,sBAAsB,GAAsB;IAChD,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAEF;;;;;;;GAOG;AACH,SAAgB,qCAAqC,CAAC,EACpD,YAAY,GAGb;IACC,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAChD,OAAO,IAAI,EAAE,CAAC;SACf;QACD,MAAM,IAAI,EAAE,CAAC;QAEb,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QACtD,IAAI,CAAC,mBAAmB,EAAE;YACxB,OAAO,SAAS,CAAC;SAClB;QAED,GAAG,CAAC,qDAAqD,EAAE,GAAG,CAAC,CAAC;QAEhE,mEAAmE;QACnE,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;QACrE,MAAM,kBAAkB,GAAW,MAAM,CAAC,QAAQ;QAChD,4FAA4F;QAC5F,YAAY,CAAC,eAAe,EAAY,EACxC,EAAE,CACH,CAAC;QACF,IAAI,WAAW,GAAG,kBAAkB,EAAE;YACpC,GAAG,CACD,iGAAiG,CAClG,CAAC;YACF,MAAM,YAAY,CAAC,mBAAmB,EAAE,CAAC;SAC1C;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAjCD,sFAiCC;AAED,SAAS,oBAAoB,CAC3B,QAAgC;IAEhC,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;IAC5B,IACE,CAAC,MAAM;QACP,OAAO,MAAM,KAAK,QAAQ;QAC1B,CAAC,IAAA,mBAAW,EAAC,MAAM,EAAE,aAAa,CAAC,EACnC;QACA,OAAO,SAAS,CAAC;KAClB;IAED,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EAAE;QAC1C,OAAO,MAAM,CAAC,WAAW,CAAC;KAC3B;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\n\nconst log = createModuleLogger(projectLogger, 'block-tracker-inspector');\nconst futureBlockRefRequests: readonly string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\n/**\n * Creates a middleware that checks whether response block references are higher than the current block.\n * If the block reference is higher, the middleware will make the block tracker check for a new block.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: {\n blockTracker: PollingBlockTracker;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n const responseBlockNumber = getResultBlockNumber(res);\n if (!responseBlockNumber) {\n return undefined;\n }\n\n log('res.result.blockNumber exists, proceeding. res = %o', res);\n\n // If number is higher, suggest block-tracker check for a new block\n const blockNumber: number = Number.parseInt(responseBlockNumber, 16);\n const currentBlockNumber: number = Number.parseInt(\n // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n blockTracker.getCurrentBlock() as string,\n 16,\n );\n if (blockNumber > currentBlockNumber) {\n log(\n 'blockNumber from response is greater than current block number, refreshing current block number',\n );\n await blockTracker.checkForLatestBlock();\n }\n return undefined;\n });\n}\n\nfunction getResultBlockNumber(\n response: PendingJsonRpcResponse,\n): string | undefined {\n const { result } = response;\n if (\n !result ||\n typeof result !== 'object' ||\n !hasProperty(result, 'blockNumber')\n ) {\n return undefined;\n }\n\n if (typeof result.blockNumber === 'string') {\n return result.blockNumber;\n }\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"block-tracker-inspector.cjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":";;;AAEA,+DAAkE;AAClE,2CAA8C;AAO9C,uDAAoE;AAEpE,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,yBAAyB,CAAC,CAAC;AACzE,MAAM,sBAAsB,GAAsB;IAChD,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAEF;;;;;;;GAOG;AACH,SAAgB,qCAAqC,CAAC,EACpD,YAAY,GAGb;IACC,OAAO,IAAA,uCAAqB,EAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACjD,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QACD,MAAM,IAAI,EAAE,CAAC;QAEb,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QACtD,IAAI,CAAC,mBAAmB,EAAE,CAAC;YACzB,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,GAAG,CAAC,qDAAqD,EAAE,GAAG,CAAC,CAAC;QAEhE,mEAAmE;QACnE,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;QACrE,MAAM,kBAAkB,GAAW,MAAM,CAAC,QAAQ;QAChD,4FAA4F;QAC5F,YAAY,CAAC,eAAe,EAAY,EACxC,EAAE,CACH,CAAC;QACF,IAAI,WAAW,GAAG,kBAAkB,EAAE,CAAC;YACrC,GAAG,CACD,iGAAiG,CAClG,CAAC;YACF,MAAM,YAAY,CAAC,mBAAmB,EAAE,CAAC;QAC3C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAjCD,sFAiCC;AAED,SAAS,oBAAoB,CAC3B,QAAgC;IAEhC,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;IAC5B,IACE,CAAC,MAAM;QACP,OAAO,MAAM,KAAK,QAAQ;QAC1B,CAAC,IAAA,mBAAW,EAAC,MAAM,EAAE,aAAa,CAAC,EACnC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAC3C,OAAO,MAAM,CAAC,WAAW,CAAC;IAC5B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\n\nconst log = createModuleLogger(projectLogger, 'block-tracker-inspector');\nconst futureBlockRefRequests: readonly string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\n/**\n * Creates a middleware that checks whether response block references are higher than the current block.\n * If the block reference is higher, the middleware will make the block tracker check for a new block.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: {\n blockTracker: PollingBlockTracker;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n const responseBlockNumber = getResultBlockNumber(res);\n if (!responseBlockNumber) {\n return undefined;\n }\n\n log('res.result.blockNumber exists, proceeding. res = %o', res);\n\n // If number is higher, suggest block-tracker check for a new block\n const blockNumber: number = Number.parseInt(responseBlockNumber, 16);\n const currentBlockNumber: number = Number.parseInt(\n // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n blockTracker.getCurrentBlock() as string,\n 16,\n );\n if (blockNumber > currentBlockNumber) {\n log(\n 'blockNumber from response is greater than current block number, refreshing current block number',\n );\n await blockTracker.checkForLatestBlock();\n }\n return undefined;\n });\n}\n\nfunction getResultBlockNumber(\n response: PendingJsonRpcResponse,\n): string | undefined {\n const { result } = response;\n if (\n !result ||\n typeof result !== 'object' ||\n !hasProperty(result, 'blockNumber')\n ) {\n return undefined;\n }\n\n if (typeof result.blockNumber === 'string') {\n return result.blockNumber;\n }\n return undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"block-tracker-inspector.mjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAClE,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAO9C,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AACzE,MAAM,sBAAsB,GAAsB;IAChD,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,UAAU,qCAAqC,CAAC,EACpD,YAAY,GAGb;IACC,OAAO,qBAAqB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACpD,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YAChD,OAAO,IAAI,EAAE,CAAC;SACf;QACD,MAAM,IAAI,EAAE,CAAC;QAEb,MAAM,mBAAmB,GAAG,oBAAoB,CAAC,GAAG,CAAC,CAAC;QACtD,IAAI,CAAC,mBAAmB,EAAE;YACxB,OAAO,SAAS,CAAC;SAClB;QAED,GAAG,CAAC,qDAAqD,EAAE,GAAG,CAAC,CAAC;QAEhE,mEAAmE;QACnE,MAAM,WAAW,GAAW,MAAM,CAAC,QAAQ,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAC;QACrE,MAAM,kBAAkB,GAAW,MAAM,CAAC,QAAQ;QAChD,4FAA4F;QAC5F,YAAY,CAAC,eAAe,EAAY,EACxC,EAAE,CACH,CAAC;QACF,IAAI,WAAW,GAAG,kBAAkB,EAAE;YACpC,GAAG,CACD,iGAAiG,CAClG,CAAC;YACF,MAAM,YAAY,CAAC,mBAAmB,EAAE,CAAC;SAC1C;QACD,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,oBAAoB,CAC3B,QAAgC;IAEhC,MAAM,EAAE,MAAM,EAAE,GAAG,QAAQ,CAAC;IAC5B,IACE,CAAC,MAAM;QACP,OAAO,MAAM,KAAK,QAAQ;QAC1B,CAAC,WAAW,CAAC,MAAM,EAAE,aAAa,CAAC,EACnC;QACA,OAAO,SAAS,CAAC;KAClB;IAED,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EAAE;QAC1C,OAAO,MAAM,CAAC,WAAW,CAAC;KAC3B;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\n\nconst log = createModuleLogger(projectLogger, 'block-tracker-inspector');\nconst futureBlockRefRequests: readonly string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\n/**\n * Creates a middleware that checks whether response block references are higher than the current block.\n * If the block reference is higher, the middleware will make the block tracker check for a new block.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: {\n blockTracker: PollingBlockTracker;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n const responseBlockNumber = getResultBlockNumber(res);\n if (!responseBlockNumber) {\n return undefined;\n }\n\n log('res.result.blockNumber exists, proceeding. res = %o', res);\n\n // If number is higher, suggest block-tracker check for a new block\n const blockNumber: number = Number.parseInt(responseBlockNumber, 16);\n const currentBlockNumber: number = Number.parseInt(\n // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n blockTracker.getCurrentBlock() as string,\n 16,\n );\n if (blockNumber > currentBlockNumber) {\n log(\n 'blockNumber from response is greater than current block number, refreshing current block number',\n );\n await blockTracker.checkForLatestBlock();\n }\n return undefined;\n });\n}\n\nfunction getResultBlockNumber(\n response: PendingJsonRpcResponse,\n): string | undefined {\n const { result } = response;\n if (\n !result ||\n typeof result !== 'object' ||\n !hasProperty(result, 'blockNumber')\n ) {\n return undefined;\n }\n\n if (typeof result.blockNumber === 'string') {\n return result.blockNumber;\n }\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"block-tracker-inspector.mjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAClE,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAO9C,OAAO,EAAE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,MAAM,EAAE,aAAa,CAAC,EACnC,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,OAAO,MAAM,CAAC,WAAW,KAAK,QAAQ,EAAE,CAAC;QAC3C,OAAO,MAAM,CAAC,WAAW,CAAC;IAC5B,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { hasProperty } from '@metamask/utils';\nimport type {\n Json,\n JsonRpcParams,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\n\nconst log = createModuleLogger(projectLogger, 'block-tracker-inspector');\nconst futureBlockRefRequests: readonly string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\n/**\n * Creates a middleware that checks whether response block references are higher than the current block.\n * If the block reference is higher, the middleware will make the block tracker check for a new block.\n *\n * @param options - The options for the middleware.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: {\n blockTracker: PollingBlockTracker;\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n const responseBlockNumber = getResultBlockNumber(res);\n if (!responseBlockNumber) {\n return undefined;\n }\n\n log('res.result.blockNumber exists, proceeding. res = %o', res);\n\n // If number is higher, suggest block-tracker check for a new block\n const blockNumber: number = Number.parseInt(responseBlockNumber, 16);\n const currentBlockNumber: number = Number.parseInt(\n // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n blockTracker.getCurrentBlock() as string,\n 16,\n );\n if (blockNumber > currentBlockNumber) {\n log(\n 'blockNumber from response is greater than current block number, refreshing current block number',\n );\n await blockTracker.checkForLatestBlock();\n }\n return undefined;\n });\n}\n\nfunction getResultBlockNumber(\n response: PendingJsonRpcResponse,\n): string | undefined {\n const { result } = response;\n if (\n !result ||\n typeof result !== 'object' ||\n !hasProperty(result, 'blockNumber')\n ) {\n return undefined;\n }\n\n if (typeof result.blockNumber === 'string') {\n return result.blockNumber;\n }\n return undefined;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":";;;AACA,+DAAkE;AAClE,qDAAiD;AAcjD;;;;;;;;;;;GAWG;AACH,SAAgB,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAO,GAAG,EAAE,GAMb;IACC,OAAO,IAAA,uCAAqB,EAC1B,KAAK,EAAE,GAA4C,EAAE,GAAG,EAAE,EAAE;QAC1D,MAAM,OAAO,GACX,qBAAqB,IAAI,OAAO;YAChC,OAAO,CAAC,mBAAmB,KAAK,SAAS;YACzC,GAAG,CAAC,MAAM,KAAK,SAAS;YACtB,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE;YAC/C,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,OAAO,CAC9C;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,EACD;YACE,OAAO;SACR,CACF,CAAC;QAEF,0EAA0E;QAC1E,4CAA4C;QAC5C,sEAAsE;QACtE,uEAAuE;QACvE,IAAI,OAAO,IAAI,eAAe,EAAE;YAC9B,MAAM,sBAAS,CAAC,QAAQ,CAAC;gBACvB,IAAI,EAAE,eAAe,CAAC,KAAK;aAC5B,CAAC,CAAC;SACJ;QAED,6DAA6D;QAC7D,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC;IACtC,CAAC,CACF,CAAC;AACJ,CAAC;AA7CD,sDA6CC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AbstractRpcServiceLike } from './types';\n\n/**\n * Like a JSON-RPC request, but includes an optional `origin` property.\n * This will be included in the request as a header if specified.\n */\ntype JsonRpcRequestWithOrigin<Params extends JsonRpcParams> =\n JsonRpcRequest<Params> & {\n origin?: string;\n };\n\n/**\n * Creates middleware for sending a JSON-RPC request through the given RPC\n * service.\n *\n * @param args - The arguments to this function.\n * @param args.rpcService - The RPC service to use.\n * @param args.options - Options.\n * @param args.options.originHttpHeaderKey - If provided, the origin field for\n * each JSON-RPC request will be attached to each outgoing fetch request under\n * this header.\n * @returns The fetch middleware.\n */\nexport function createFetchMiddleware({\n rpcService,\n options = {},\n}: {\n rpcService: AbstractRpcServiceLike;\n options?: {\n originHttpHeaderKey?: string;\n };\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(\n async (req: JsonRpcRequestWithOrigin<JsonRpcParams>, res) => {\n const headers =\n 'originHttpHeaderKey' in options &&\n options.originHttpHeaderKey !== undefined &&\n req.origin !== undefined\n ? { [options.originHttpHeaderKey]: req.origin }\n : {};\n\n const jsonRpcResponse = await rpcService.request(\n {\n id: req.id,\n jsonrpc: req.jsonrpc,\n method: req.method,\n params: req.params,\n },\n {\n headers,\n },\n );\n\n // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is\n // strictly a JSON-RPC error response as per\n // <https://www.jsonrpc.org/specification#error_object> to account for\n // Ganache returning error objects with extra properties such as `name`\n if ('error' in jsonRpcResponse) {\n throw rpcErrors.internal({\n data: jsonRpcResponse.error,\n });\n }\n\n // Discard the `id` and `jsonrpc` fields in the response body\n // (the JSON-RPC engine will fill those in)\n res.result = jsonRpcResponse.result;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":";;;AACA,+DAAkE;AAClE,qDAAiD;AAcjD;;;;;;;;;;;GAWG;AACH,SAAgB,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAO,GAAG,EAAE,GAMb;IACC,OAAO,IAAA,uCAAqB,EAC1B,KAAK,EAAE,GAA4C,EAAE,GAAG,EAAE,EAAE;QAC1D,MAAM,OAAO,GACX,qBAAqB,IAAI,OAAO;YAChC,OAAO,CAAC,mBAAmB,KAAK,SAAS;YACzC,GAAG,CAAC,MAAM,KAAK,SAAS;YACtB,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE;YAC/C,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,OAAO,CAC9C;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,EACD;YACE,OAAO;SACR,CACF,CAAC;QAEF,0EAA0E;QAC1E,4CAA4C;QAC5C,sEAAsE;QACtE,uEAAuE;QACvE,IAAI,OAAO,IAAI,eAAe,EAAE,CAAC;YAC/B,MAAM,sBAAS,CAAC,QAAQ,CAAC;gBACvB,IAAI,EAAE,eAAe,CAAC,KAAK;aAC5B,CAAC,CAAC;QACL,CAAC;QAED,6DAA6D;QAC7D,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC;IACtC,CAAC,CACF,CAAC;AACJ,CAAC;AA7CD,sDA6CC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AbstractRpcServiceLike } from './types';\n\n/**\n * Like a JSON-RPC request, but includes an optional `origin` property.\n * This will be included in the request as a header if specified.\n */\ntype JsonRpcRequestWithOrigin<Params extends JsonRpcParams> =\n JsonRpcRequest<Params> & {\n origin?: string;\n };\n\n/**\n * Creates middleware for sending a JSON-RPC request through the given RPC\n * service.\n *\n * @param args - The arguments to this function.\n * @param args.rpcService - The RPC service to use.\n * @param args.options - Options.\n * @param args.options.originHttpHeaderKey - If provided, the origin field for\n * each JSON-RPC request will be attached to each outgoing fetch request under\n * this header.\n * @returns The fetch middleware.\n */\nexport function createFetchMiddleware({\n rpcService,\n options = {},\n}: {\n rpcService: AbstractRpcServiceLike;\n options?: {\n originHttpHeaderKey?: string;\n };\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(\n async (req: JsonRpcRequestWithOrigin<JsonRpcParams>, res) => {\n const headers =\n 'originHttpHeaderKey' in options &&\n options.originHttpHeaderKey !== undefined &&\n req.origin !== undefined\n ? { [options.originHttpHeaderKey]: req.origin }\n : {};\n\n const jsonRpcResponse = await rpcService.request(\n {\n id: req.id,\n jsonrpc: req.jsonrpc,\n method: req.method,\n params: req.params,\n },\n {\n headers,\n },\n );\n\n // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is\n // strictly a JSON-RPC error response as per\n // <https://www.jsonrpc.org/specification#error_object> to account for\n // Ganache returning error objects with extra properties such as `name`\n if ('error' in jsonRpcResponse) {\n throw rpcErrors.internal({\n data: jsonRpcResponse.error,\n });\n }\n\n // Discard the `id` and `jsonrpc` fields in the response body\n // (the JSON-RPC engine will fill those in)\n res.result = jsonRpcResponse.result;\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAClE,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAcjD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAO,GAAG,EAAE,GAMb;IACC,OAAO,qBAAqB,CAC1B,KAAK,EAAE,GAA4C,EAAE,GAAG,EAAE,EAAE;QAC1D,MAAM,OAAO,GACX,qBAAqB,IAAI,OAAO;YAChC,OAAO,CAAC,mBAAmB,KAAK,SAAS;YACzC,GAAG,CAAC,MAAM,KAAK,SAAS;YACtB,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE;YAC/C,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,OAAO,CAC9C;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,EACD;YACE,OAAO;SACR,CACF,CAAC;QAEF,0EAA0E;QAC1E,4CAA4C;QAC5C,sEAAsE;QACtE,uEAAuE;QACvE,IAAI,OAAO,IAAI,eAAe,EAAE;YAC9B,MAAM,SAAS,CAAC,QAAQ,CAAC;gBACvB,IAAI,EAAE,eAAe,CAAC,KAAK;aAC5B,CAAC,CAAC;SACJ;QAED,6DAA6D;QAC7D,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC;IACtC,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AbstractRpcServiceLike } from './types';\n\n/**\n * Like a JSON-RPC request, but includes an optional `origin` property.\n * This will be included in the request as a header if specified.\n */\ntype JsonRpcRequestWithOrigin<Params extends JsonRpcParams> =\n JsonRpcRequest<Params> & {\n origin?: string;\n };\n\n/**\n * Creates middleware for sending a JSON-RPC request through the given RPC\n * service.\n *\n * @param args - The arguments to this function.\n * @param args.rpcService - The RPC service to use.\n * @param args.options - Options.\n * @param args.options.originHttpHeaderKey - If provided, the origin field for\n * each JSON-RPC request will be attached to each outgoing fetch request under\n * this header.\n * @returns The fetch middleware.\n */\nexport function createFetchMiddleware({\n rpcService,\n options = {},\n}: {\n rpcService: AbstractRpcServiceLike;\n options?: {\n originHttpHeaderKey?: string;\n };\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(\n async (req: JsonRpcRequestWithOrigin<JsonRpcParams>, res) => {\n const headers =\n 'originHttpHeaderKey' in options &&\n options.originHttpHeaderKey !== undefined &&\n req.origin !== undefined\n ? { [options.originHttpHeaderKey]: req.origin }\n : {};\n\n const jsonRpcResponse = await rpcService.request(\n {\n id: req.id,\n jsonrpc: req.jsonrpc,\n method: req.method,\n params: req.params,\n },\n {\n headers,\n },\n );\n\n // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is\n // strictly a JSON-RPC error response as per\n // <https://www.jsonrpc.org/specification#error_object> to account for\n // Ganache returning error objects with extra properties such as `name`\n if ('error' in jsonRpcResponse) {\n throw rpcErrors.internal({\n data: jsonRpcResponse.error,\n });\n }\n\n // Discard the `id` and `jsonrpc` fields in the response body\n // (the JSON-RPC engine will fill those in)\n res.result = jsonRpcResponse.result;\n },\n );\n}\n"]}
1
+ {"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAClE,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAcjD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAO,GAAG,EAAE,GAMb;IACC,OAAO,qBAAqB,CAC1B,KAAK,EAAE,GAA4C,EAAE,GAAG,EAAE,EAAE;QAC1D,MAAM,OAAO,GACX,qBAAqB,IAAI,OAAO;YAChC,OAAO,CAAC,mBAAmB,KAAK,SAAS;YACzC,GAAG,CAAC,MAAM,KAAK,SAAS;YACtB,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE;YAC/C,CAAC,CAAC,EAAE,CAAC;QAET,MAAM,eAAe,GAAG,MAAM,UAAU,CAAC,OAAO,CAC9C;YACE,EAAE,EAAE,GAAG,CAAC,EAAE;YACV,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,MAAM,EAAE,GAAG,CAAC,MAAM;SACnB,EACD;YACE,OAAO;SACR,CACF,CAAC;QAEF,0EAA0E;QAC1E,4CAA4C;QAC5C,sEAAsE;QACtE,uEAAuE;QACvE,IAAI,OAAO,IAAI,eAAe,EAAE,CAAC;YAC/B,MAAM,SAAS,CAAC,QAAQ,CAAC;gBACvB,IAAI,EAAE,eAAe,CAAC,KAAK;aAC5B,CAAC,CAAC;QACL,CAAC;QAED,6DAA6D;QAC7D,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC;IACtC,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\n\nimport type { AbstractRpcServiceLike } from './types';\n\n/**\n * Like a JSON-RPC request, but includes an optional `origin` property.\n * This will be included in the request as a header if specified.\n */\ntype JsonRpcRequestWithOrigin<Params extends JsonRpcParams> =\n JsonRpcRequest<Params> & {\n origin?: string;\n };\n\n/**\n * Creates middleware for sending a JSON-RPC request through the given RPC\n * service.\n *\n * @param args - The arguments to this function.\n * @param args.rpcService - The RPC service to use.\n * @param args.options - Options.\n * @param args.options.originHttpHeaderKey - If provided, the origin field for\n * each JSON-RPC request will be attached to each outgoing fetch request under\n * this header.\n * @returns The fetch middleware.\n */\nexport function createFetchMiddleware({\n rpcService,\n options = {},\n}: {\n rpcService: AbstractRpcServiceLike;\n options?: {\n originHttpHeaderKey?: string;\n };\n}): JsonRpcMiddleware<JsonRpcParams, Json> {\n return createAsyncMiddleware(\n async (req: JsonRpcRequestWithOrigin<JsonRpcParams>, res) => {\n const headers =\n 'originHttpHeaderKey' in options &&\n options.originHttpHeaderKey !== undefined &&\n req.origin !== undefined\n ? { [options.originHttpHeaderKey]: req.origin }\n : {};\n\n const jsonRpcResponse = await rpcService.request(\n {\n id: req.id,\n jsonrpc: req.jsonrpc,\n method: req.method,\n params: req.params,\n },\n {\n headers,\n },\n );\n\n // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is\n // strictly a JSON-RPC error response as per\n // <https://www.jsonrpc.org/specification#error_object> to account for\n // Ganache returning error objects with extra properties such as `name`\n if ('error' in jsonRpcResponse) {\n throw rpcErrors.internal({\n data: jsonRpcResponse.error,\n });\n }\n\n // Discard the `id` and `jsonrpc` fields in the response body\n // (the JSON-RPC engine will fill those in)\n res.result = jsonRpcResponse.result;\n },\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"inflight-cache.cjs","sourceRoot":"","sources":["../src/inflight-cache.ts"],"names":[],"mappings":";;;AAAA,+DAAkE;AAMlE,qCAAmC;AAEnC,uDAAoE;AAEpE,6CAA0D;AAO1D,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,SAAgB,6BAA6B;IAI3C,MAAM,gBAAgB,GAAoB,EAAE,CAAC;IAE7C,OAAO,IAAA,uCAAqB,EAC1B,KAAK,EAAE,GAAyC,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;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kC,EAAE,EAAE;YAChE,wDAAwD;YACxD,GAAG,CAAC,MAAM,GAAG,IAAA,YAAK,EAAC,UAAU,CAAC,MAAM,CAAC,CAAC;YACtC,GAAG,CAAC,KAAK,GAAG,IAAA,YAAK,EAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACpC,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,SAAS,mBAAmB,CAC1B,GAA2B,EAC3B,qBAAwC;QAExC,8DAA8D;QAC9D,UAAU,CAAC,GAAG,EAAE;YACd,qBAAqB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBACxC,IAAI;oBACF,OAAO,CAAC,GAAG,CAAC,CAAC;iBACd;gBAAC,OAAO,GAAG,EAAE;oBACZ,oDAAoD;oBACpD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;iBACpB;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AApFD,sEAoFC;AAED,SAAS,eAAe;IACtB,IAAI,OAAY,CAAC;IACjB,MAAM,OAAO,GAAkB,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;QACtD,OAAO,GAAG,QAAQ,CAAC;IACrB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n JsonRpcParams,\n Json,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';\nimport { cacheIdentifierForRequest } from './utils/cache';\n\ntype RequestHandlers = (handledRes: PendingJsonRpcResponse) => void;\ntype InflightRequest = {\n [cacheId: string]: RequestHandlers[];\n};\n\nconst log = createModuleLogger(projectLogger, 'inflight-cache');\n\nexport function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n const inflightRequests: InflightRequest = {};\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // get cacheId, if cacheable\n const cacheId: string | null = cacheIdentifierForRequest(req);\n // if not cacheable, skip\n if (!cacheId) {\n log('Request is not cacheable, proceeding. req = %o', req);\n return next();\n }\n // check for matching requests\n let activeRequestHandlers: RequestHandlers[] = inflightRequests[cacheId];\n // if found, wait for the active request to be handled\n if (activeRequestHandlers) {\n // setup the response listener and wait for it to be called\n // it will handle copying the result and request fields\n log(\n 'Running %i handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n await createActiveRequestHandler(res, activeRequestHandlers);\n return undefined;\n }\n // setup response handler array for subsequent requests\n activeRequestHandlers = [];\n inflightRequests[cacheId] = activeRequestHandlers;\n // allow request to be handled normally\n log('Carrying original request forward %o', req);\n await next();\n\n // clear inflight requests\n delete inflightRequests[cacheId];\n // schedule activeRequestHandlers to be handled\n log(\n 'Running %i collected handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n handleActiveRequest(res, activeRequestHandlers);\n // complete\n return undefined;\n },\n );\n\n async function createActiveRequestHandler(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): Promise<void> {\n const { resolve, promise } = deferredPromise();\n activeRequestHandlers.push((handledRes: PendingJsonRpcResponse) => {\n // append a copy of the result and error to the response\n res.result = klona(handledRes.result);\n res.error = klona(handledRes.error);\n resolve();\n });\n return promise;\n }\n\n function handleActiveRequest(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): void {\n // use setTimeout so we can resolve our original request first\n setTimeout(() => {\n activeRequestHandlers.forEach((handler) => {\n try {\n handler(res);\n } catch (err) {\n // catch error so all requests are handled correctly\n console.error(err);\n }\n });\n });\n }\n}\n\nfunction deferredPromise() {\n let resolve: any;\n const promise: Promise<void> = new Promise((_resolve) => {\n resolve = _resolve;\n });\n return { resolve, promise };\n}\n"]}
1
+ {"version":3,"file":"inflight-cache.cjs","sourceRoot":"","sources":["../src/inflight-cache.ts"],"names":[],"mappings":";;;AAAA,+DAAkE;AAMlE,qCAAmC;AAEnC,uDAAoE;AAEpE,6CAA0D;AAO1D,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,SAAgB,6BAA6B;IAI3C,MAAM,gBAAgB,GAAoB,EAAE,CAAC;IAE7C,OAAO,IAAA,uCAAqB,EAC1B,KAAK,EAAE,GAAyC,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC7D,2CAA2C;QAC3C,IAAI,GAAG,CAAC,SAAS,EAAE,CAAC;YAClB,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QACD,4BAA4B;QAC5B,MAAM,OAAO,GAAkB,IAAA,iCAAyB,EAAC,GAAG,CAAC,CAAC;QAC9D,yBAAyB;QACzB,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,GAAG,CAAC,gDAAgD,EAAE,GAAG,CAAC,CAAC;YAC3D,OAAO,IAAI,EAAE,CAAC;QAChB,CAAC;QACD,8BAA8B;QAC9B,IAAI,qBAAqB,GAAsB,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACzE,sDAAsD;QACtD,IAAI,qBAAqB,EAAE,CAAC;YAC1B,2DAA2D;YAC3D,uDAAuD;YACvD,GAAG,CACD,sCAAsC,EACtC,qBAAqB,CAAC,MAAM,EAC5B,GAAG,CACJ,CAAC;YACF,MAAM,0BAA0B,CAAC,GAAG,EAAE,qBAAqB,CAAC,CAAC;YAC7D,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,uDAAuD;QACvD,qBAAqB,GAAG,EAAE,CAAC;QAC3B,gBAAgB,CAAC,OAAO,CAAC,GAAG,qBAAqB,CAAC;QAClD,uCAAu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B,MAAM,OAAO,GAAkB,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;QACtD,OAAO,GAAG,QAAQ,CAAC;IACrB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n JsonRpcParams,\n Json,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';\nimport { cacheIdentifierForRequest } from './utils/cache';\n\ntype RequestHandlers = (handledRes: PendingJsonRpcResponse) => void;\ntype InflightRequest = {\n [cacheId: string]: RequestHandlers[];\n};\n\nconst log = createModuleLogger(projectLogger, 'inflight-cache');\n\nexport function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n const inflightRequests: InflightRequest = {};\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // get cacheId, if cacheable\n const cacheId: string | null = cacheIdentifierForRequest(req);\n // if not cacheable, skip\n if (!cacheId) {\n log('Request is not cacheable, proceeding. req = %o', req);\n return next();\n }\n // check for matching requests\n let activeRequestHandlers: RequestHandlers[] = inflightRequests[cacheId];\n // if found, wait for the active request to be handled\n if (activeRequestHandlers) {\n // setup the response listener and wait for it to be called\n // it will handle copying the result and request fields\n log(\n 'Running %i handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n await createActiveRequestHandler(res, activeRequestHandlers);\n return undefined;\n }\n // setup response handler array for subsequent requests\n activeRequestHandlers = [];\n inflightRequests[cacheId] = activeRequestHandlers;\n // allow request to be handled normally\n log('Carrying original request forward %o', req);\n await next();\n\n // clear inflight requests\n delete inflightRequests[cacheId];\n // schedule activeRequestHandlers to be handled\n log(\n 'Running %i collected handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n handleActiveRequest(res, activeRequestHandlers);\n // complete\n return undefined;\n },\n );\n\n async function createActiveRequestHandler(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): Promise<void> {\n const { resolve, promise } = deferredPromise();\n activeRequestHandlers.push((handledRes: PendingJsonRpcResponse) => {\n // append a copy of the result and error to the response\n res.result = klona(handledRes.result);\n res.error = klona(handledRes.error);\n resolve();\n });\n return promise;\n }\n\n function handleActiveRequest(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): void {\n // use setTimeout so we can resolve our original request first\n setTimeout(() => {\n activeRequestHandlers.forEach((handler) => {\n try {\n handler(res);\n } catch (err) {\n // catch error so all requests are handled correctly\n console.error(err);\n }\n });\n });\n }\n}\n\nfunction deferredPromise() {\n let resolve: any;\n const promise: Promise<void> = new Promise((_resolve) => {\n resolve = _resolve;\n });\n return { resolve, promise };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"inflight-cache.mjs","sourceRoot":"","sources":["../src/inflight-cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAMlE,OAAO,EAAE,KAAK,EAAE,mBAAmB;AAEnC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,OAAO,EAAE,yBAAyB,EAAE,0BAAsB;AAO1D,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,MAAM,UAAU,6BAA6B;IAI3C,MAAM,gBAAgB,GAAoB,EAAE,CAAC;IAE7C,OAAO,qBAAqB,CAC1B,KAAK,EAAE,GAAyC,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC7D,2CAA2C;QAC3C,IAAI,GAAG,CAAC,SAAS,EAAE;YACjB,OAAO,IAAI,EAAE,CAAC;SACf;QACD,4BAA4B;QAC5B,M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AAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACpC,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;QACH,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,SAAS,mBAAmB,CAC1B,GAA2B,EAC3B,qBAAwC;QAExC,8DAA8D;QAC9D,UAAU,CAAC,GAAG,EAAE;YACd,qBAAqB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;gBACxC,IAAI;oBACF,OAAO,CAAC,GAAG,CAAC,CAAC;iBACd;gBAAC,OAAO,GAAG,EAAE;oBACZ,oDAAoD;oBACpD,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;iBACpB;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC;AAED,SAAS,eAAe;IACtB,IAAI,OAAY,CAAC;IACjB,MAAM,OAAO,GAAkB,IAAI,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;QACtD,OAAO,GAAG,QAAQ,CAAC;IACrB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n JsonRpcParams,\n Json,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';\nimport { cacheIdentifierForRequest } from './utils/cache';\n\ntype RequestHandlers = (handledRes: PendingJsonRpcResponse) => void;\ntype InflightRequest = {\n [cacheId: string]: RequestHandlers[];\n};\n\nconst log = createModuleLogger(projectLogger, 'inflight-cache');\n\nexport function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n const inflightRequests: InflightRequest = {};\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // get cacheId, if cacheable\n const cacheId: string | null = cacheIdentifierForRequest(req);\n // if not cacheable, skip\n if (!cacheId) {\n log('Request is not cacheable, proceeding. req = %o', req);\n return next();\n }\n // check for matching requests\n let activeRequestHandlers: RequestHandlers[] = inflightRequests[cacheId];\n // if found, wait for the active request to be handled\n if (activeRequestHandlers) {\n // setup the response listener and wait for it to be called\n // it will handle copying the result and request fields\n log(\n 'Running %i handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n await createActiveRequestHandler(res, activeRequestHandlers);\n return undefined;\n }\n // setup response handler array for subsequent requests\n activeRequestHandlers = [];\n inflightRequests[cacheId] = activeRequestHandlers;\n // allow request to be handled normally\n log('Carrying original request forward %o', req);\n await next();\n\n // clear inflight requests\n delete inflightRequests[cacheId];\n // schedule activeRequestHandlers to be handled\n log(\n 'Running %i collected handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n handleActiveRequest(res, activeRequestHandlers);\n // complete\n return undefined;\n },\n );\n\n async function createActiveRequestHandler(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): Promise<void> {\n const { resolve, promise } = deferredPromise();\n activeRequestHandlers.push((handledRes: PendingJsonRpcResponse) => {\n // append a copy of the result and error to the response\n res.result = klona(handledRes.result);\n res.error = klona(handledRes.error);\n resolve();\n });\n return promise;\n }\n\n function handleActiveRequest(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): void {\n // use setTimeout so we can resolve our original request first\n setTimeout(() => {\n activeRequestHandlers.forEach((handler) => {\n try {\n handler(res);\n } catch (err) {\n // catch error so all requests are handled correctly\n console.error(err);\n }\n });\n });\n }\n}\n\nfunction deferredPromise() {\n let resolve: any;\n const promise: Promise<void> = new Promise((_resolve) => {\n resolve = _resolve;\n });\n return { resolve, promise };\n}\n"]}
1
+ {"version":3,"file":"inflight-cache.mjs","sourceRoot":"","sources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,OAAO,GAAG,QAAQ,CAAC;IACrB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type {\n JsonRpcParams,\n Json,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { JsonRpcRequestToCache, JsonRpcCacheMiddleware } from './types';\nimport { cacheIdentifierForRequest } from './utils/cache';\n\ntype RequestHandlers = (handledRes: PendingJsonRpcResponse) => void;\ntype InflightRequest = {\n [cacheId: string]: RequestHandlers[];\n};\n\nconst log = createModuleLogger(projectLogger, 'inflight-cache');\n\nexport function createInflightCacheMiddleware(): JsonRpcCacheMiddleware<\n JsonRpcParams,\n Json\n> {\n const inflightRequests: InflightRequest = {};\n\n return createAsyncMiddleware(\n async (req: JsonRpcRequestToCache<JsonRpcParams>, res, next) => {\n // allow cach to be skipped if so specified\n if (req.skipCache) {\n return next();\n }\n // get cacheId, if cacheable\n const cacheId: string | null = cacheIdentifierForRequest(req);\n // if not cacheable, skip\n if (!cacheId) {\n log('Request is not cacheable, proceeding. req = %o', req);\n return next();\n }\n // check for matching requests\n let activeRequestHandlers: RequestHandlers[] = inflightRequests[cacheId];\n // if found, wait for the active request to be handled\n if (activeRequestHandlers) {\n // setup the response listener and wait for it to be called\n // it will handle copying the result and request fields\n log(\n 'Running %i handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n await createActiveRequestHandler(res, activeRequestHandlers);\n return undefined;\n }\n // setup response handler array for subsequent requests\n activeRequestHandlers = [];\n inflightRequests[cacheId] = activeRequestHandlers;\n // allow request to be handled normally\n log('Carrying original request forward %o', req);\n await next();\n\n // clear inflight requests\n delete inflightRequests[cacheId];\n // schedule activeRequestHandlers to be handled\n log(\n 'Running %i collected handler(s) for request %o',\n activeRequestHandlers.length,\n req,\n );\n handleActiveRequest(res, activeRequestHandlers);\n // complete\n return undefined;\n },\n );\n\n async function createActiveRequestHandler(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): Promise<void> {\n const { resolve, promise } = deferredPromise();\n activeRequestHandlers.push((handledRes: PendingJsonRpcResponse) => {\n // append a copy of the result and error to the response\n res.result = klona(handledRes.result);\n res.error = klona(handledRes.error);\n resolve();\n });\n return promise;\n }\n\n function handleActiveRequest(\n res: PendingJsonRpcResponse,\n activeRequestHandlers: RequestHandlers[],\n ): void {\n // use setTimeout so we can resolve our original request first\n setTimeout(() => {\n activeRequestHandlers.forEach((handler) => {\n try {\n handler(res);\n } catch (err) {\n // catch error so all requests are handled correctly\n console.error(err);\n }\n });\n });\n }\n}\n\nfunction deferredPromise() {\n let resolve: any;\n const promise: Promise<void> = new Promise((_resolve) => {\n resolve = _resolve;\n });\n return { resolve, promise };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet-request-execution-permissions.cjs","sourceRoot":"","sources":["../../src/methods/wallet-request-execution-permissions.ts"],"names":[],"mappings":";;;AAAA,qDAAiD;AAEjD,uDAU+B;AAC/B,2CAOyB;AAEzB,wDAAqD;AAErD,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAAC;IAC9B,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,mBAAmB,EAAE,IAAA,qBAAO,GAAE;IAC9B,IAAI,EAAE,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,qBAAO,GAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,UAAU,GAAG,IAAA,oBAAM,EAAC;IACxB,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,mBAAmB,EAAE,IAAA,qBAAO,GAAE;IAC9B,IAAI,EAAE,IAAA,oBAAM,EAAC,IAAA,oBAAM,GAAE,EAAE,IAAA,qBAAO,GAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,mBAAmB,GAAG,IAAA,oBAAM,EAAC;IACjC,IAAI,EAAE,IAAA,qBAAO,EAAC,SAAS,CAAC;IACxB,IAAI,EAAE,IAAA,oBAAM,EAAC;QACX,OAAO,EAAE,gCAAwB;KAClC,CAAC;CACH,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,IAAA,oBAAM,EAAC;IACrC,OAAO,EAAE,uBAAe;IACxB,OAAO,EAAE,IAAA,sBAAQ,EAAC,gCAAwB,CAAC;IAC3C,MAAM,EAAE,mBAAmB;IAC3B,UAAU,EAAE,gBAAgB;IAC5B,KAAK,EAAE,IAAA,sBAAQ,EAAC,IAAA,mBAAK,EAAC,CAAC,IAAA,mBAAK,EAAC,UAAU,CAAC,EAAE,IAAA,qBAAO,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CAC3D,CAAC,CAAC;AAEU,QAAA,iCAAiC,GAAG,IAAA,mBAAK,EAAC,uBAAuB,CAAC,CAAC;AAiBzE,KAAK,UAAU,iCAAiC,CACrD,GAAmB,EACnB,GAA2B,EAC3B,EACE,kCAAkC,GAGnC;IAED,IAAI,CAAC,kCAAkC,EAAE;QACvC,MAAM,sBAAS,CAAC,kBAAkB,CAChC,+DAA+D,CAChE,CAAC;KACH;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAA,2BAAc,EAAC,MAAM,EAAE,yCAAiC,CAAC,CAAC;IAE1D,GAAG,CAAC,MAAM,GAAG,MAAM,kCAAkC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACrE,CAAC;AApBD,8EAoBC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n literal,\n object,\n optional,\n record,\n string,\n union,\n unknown,\n} from '@metamask/superstruct';\nimport {\n HexChecksumAddressStruct,\n type Hex,\n type Json,\n type JsonRpcRequest,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nconst PermissionStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst RuleStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst AccountSignerStruct = object({\n type: literal('account'),\n data: object({\n address: HexChecksumAddressStruct,\n }),\n});\n\nconst PermissionRequestStruct = object({\n chainId: StrictHexStruct,\n address: optional(HexChecksumAddressStruct),\n signer: AccountSignerStruct,\n permission: PermissionStruct,\n rules: optional(union([array(RuleStruct), literal(null)])),\n});\n\nexport const RequestExecutionPermissionsStruct = array(PermissionRequestStruct);\n\n// RequestExecutionPermissions API types\nexport type RequestExecutionPermissionsRequestParams = Infer<\n typeof RequestExecutionPermissionsStruct\n>;\n\nexport type RequestExecutionPermissionsResult = Json &\n (Infer<typeof PermissionRequestStruct> & {\n context: Hex;\n })[];\n\nexport type ProcessRequestExecutionPermissionsHook = (\n request: RequestExecutionPermissionsRequestParams,\n req: JsonRpcRequest,\n) => Promise<RequestExecutionPermissionsResult>;\n\nexport async function walletRequestExecutionPermissions(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRequestExecutionPermissions,\n }: {\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n },\n): Promise<void> {\n if (!processRequestExecutionPermissions) {\n throw rpcErrors.methodNotSupported(\n 'wallet_requestExecutionPermissions - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RequestExecutionPermissionsStruct);\n\n res.result = await processRequestExecutionPermissions(params, req);\n}\n"]}
1
+ {"version":3,"file":"wallet-request-execution-permissions.cjs","sourceRoot":"","sources":["../../src/methods/wallet-request-execution-permissions.ts"],"names":[],"mappings":";;;AAAA,qDAAiD;AAEjD,uDAU+B;AAC/B,2CAOyB;AAEzB,wDAAqD;AAErD,MAAM,gBAAgB,GAAG,IAAA,oBAAM,EAAC;IAC9B,IAAI,EAAE,IAAA,oBAAM,GAAE;IACd,mBAAmB,EAAE,IAAA,qBAA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AAC,CAAC;IAE1D,GAAG,CAAC,MAAM,GAAG,MAAM,kCAAkC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACrE,CAAC;AApBD,8EAoBC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n literal,\n object,\n optional,\n record,\n string,\n union,\n unknown,\n} from '@metamask/superstruct';\nimport {\n HexChecksumAddressStruct,\n type Hex,\n type Json,\n type JsonRpcRequest,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nconst PermissionStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst RuleStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst AccountSignerStruct = object({\n type: literal('account'),\n data: object({\n address: HexChecksumAddressStruct,\n }),\n});\n\nconst PermissionRequestStruct = object({\n chainId: StrictHexStruct,\n address: optional(HexChecksumAddressStruct),\n signer: AccountSignerStruct,\n permission: PermissionStruct,\n rules: optional(union([array(RuleStruct), literal(null)])),\n});\n\nexport const RequestExecutionPermissionsStruct = array(PermissionRequestStruct);\n\n// RequestExecutionPermissions API types\nexport type RequestExecutionPermissionsRequestParams = Infer<\n typeof RequestExecutionPermissionsStruct\n>;\n\nexport type RequestExecutionPermissionsResult = Json &\n (Infer<typeof PermissionRequestStruct> & {\n context: Hex;\n })[];\n\nexport type ProcessRequestExecutionPermissionsHook = (\n request: RequestExecutionPermissionsRequestParams,\n req: JsonRpcRequest,\n) => Promise<RequestExecutionPermissionsResult>;\n\nexport async function walletRequestExecutionPermissions(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRequestExecutionPermissions,\n }: {\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n },\n): Promise<void> {\n if (!processRequestExecutionPermissions) {\n throw rpcErrors.methodNotSupported(\n 'wallet_requestExecutionPermissions - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RequestExecutionPermissionsStruct);\n\n res.result = await processRequestExecutionPermissions(params, req);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet-request-execution-permissions.mjs","sourceRoot":"","sources":["../../src/methods/wallet-request-execution-permissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,KAAK,EACL,OAAO,EACR,8BAA8B;AAC/B,OAAO,EACL,wBAAwB,EAKxB,eAAe,EAChB,wBAAwB;AAEzB,OAAO,EAAE,cAAc,EAAE,gCAA4B;AAErD,MAAM,gBAAgB,GAAG,MAAM,CAAC;IAC9B,IAAI,EAAE,MAAM,EAAE;IACd,mBAAmB,EAAE,OAAO,EAAE;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,UAAU,GAAG,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,EAAE;IACd,mBAAmB,EAAE,OAAO,EAAE;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,mBAAmB,GAAG,MAAM,CAAC;IACjC,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,wBAAwB;KAClC,CAAC;CACH,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,MAAM,CAAC;IACrC,OAAO,EAAE,eAAe;IACxB,OAAO,EAAE,QAAQ,CAAC,wBAAwB,CAAC;IAC3C,MAAM,EAAE,mBAAmB;IAC3B,UAAU,EAAE,gBAAgB;IAC5B,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CAC3D,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAiBhF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,GAAmB,EACnB,GAA2B,EAC3B,EACE,kCAAkC,GAGnC;IAED,IAAI,CAAC,kCAAkC,EAAE;QACvC,MAAM,SAAS,CAAC,kBAAkB,CAChC,+DAA+D,CAChE,CAAC;KACH;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,cAAc,CAAC,MAAM,EAAE,iCAAiC,CAAC,CAAC;IAE1D,GAAG,CAAC,MAAM,GAAG,MAAM,kCAAkC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n literal,\n object,\n optional,\n record,\n string,\n union,\n unknown,\n} from '@metamask/superstruct';\nimport {\n HexChecksumAddressStruct,\n type Hex,\n type Json,\n type JsonRpcRequest,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nconst PermissionStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst RuleStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst AccountSignerStruct = object({\n type: literal('account'),\n data: object({\n address: HexChecksumAddressStruct,\n }),\n});\n\nconst PermissionRequestStruct = object({\n chainId: StrictHexStruct,\n address: optional(HexChecksumAddressStruct),\n signer: AccountSignerStruct,\n permission: PermissionStruct,\n rules: optional(union([array(RuleStruct), literal(null)])),\n});\n\nexport const RequestExecutionPermissionsStruct = array(PermissionRequestStruct);\n\n// RequestExecutionPermissions API types\nexport type RequestExecutionPermissionsRequestParams = Infer<\n typeof RequestExecutionPermissionsStruct\n>;\n\nexport type RequestExecutionPermissionsResult = Json &\n (Infer<typeof PermissionRequestStruct> & {\n context: Hex;\n })[];\n\nexport type ProcessRequestExecutionPermissionsHook = (\n request: RequestExecutionPermissionsRequestParams,\n req: JsonRpcRequest,\n) => Promise<RequestExecutionPermissionsResult>;\n\nexport async function walletRequestExecutionPermissions(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRequestExecutionPermissions,\n }: {\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n },\n): Promise<void> {\n if (!processRequestExecutionPermissions) {\n throw rpcErrors.methodNotSupported(\n 'wallet_requestExecutionPermissions - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RequestExecutionPermissionsStruct);\n\n res.result = await processRequestExecutionPermissions(params, req);\n}\n"]}
1
+ {"version":3,"file":"wallet-request-execution-permissions.mjs","sourceRoot":"","sources":["../../src/methods/wallet-request-execution-permissions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EACL,KAAK,EACL,OAAO,EACP,OAAO,EACP,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,KAAK,EACL,OAAO,EACR,8BAA8B;AAC/B,OAAO,EACL,wBAAwB,EAKxB,eAAe,EAChB,wBAAwB;AAEzB,OAAO,EAAE,cAAc,EAAE,gCAA4B;AAErD,MAAM,gBAAgB,GAAG,MAAM,CAAC;IAC9B,IAAI,EAAE,MAAM,EAAE;IACd,mBAAmB,EAAE,OAAO,EAAE;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,UAAU,GAAG,MAAM,CAAC;IACxB,IAAI,EAAE,MAAM,EAAE;IACd,mBAAmB,EAAE,OAAO,EAAE;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC;CAClC,CAAC,CAAC;AAEH,MAAM,mBAAmB,GAAG,MAAM,CAAC;IACjC,IAAI,EAAE,OAAO,CAAC,SAAS,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,wBAAwB;KAClC,CAAC;CACH,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,MAAM,CAAC;IACrC,OAAO,EAAE,eAAe;IACxB,OAAO,EAAE,QAAQ,CAAC,wBAAwB,CAAC;IAC3C,MAAM,EAAE,mBAAmB;IAC3B,UAAU,EAAE,gBAAgB;IAC5B,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CAC3D,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAiBhF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,GAAmB,EACnB,GAA2B,EAC3B,EACE,kCAAkC,GAGnC;IAED,IAAI,CAAC,kCAAkC,EAAE,CAAC;QACxC,MAAM,SAAS,CAAC,kBAAkB,CAChC,+DAA+D,CAChE,CAAC;IACJ,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,cAAc,CAAC,MAAM,EAAE,iCAAiC,CAAC,CAAC;IAE1D,GAAG,CAAC,MAAM,GAAG,MAAM,kCAAkC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n boolean,\n literal,\n object,\n optional,\n record,\n string,\n union,\n unknown,\n} from '@metamask/superstruct';\nimport {\n HexChecksumAddressStruct,\n type Hex,\n type Json,\n type JsonRpcRequest,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nconst PermissionStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst RuleStruct = object({\n type: string(),\n isAdjustmentAllowed: boolean(),\n data: record(string(), unknown()),\n});\n\nconst AccountSignerStruct = object({\n type: literal('account'),\n data: object({\n address: HexChecksumAddressStruct,\n }),\n});\n\nconst PermissionRequestStruct = object({\n chainId: StrictHexStruct,\n address: optional(HexChecksumAddressStruct),\n signer: AccountSignerStruct,\n permission: PermissionStruct,\n rules: optional(union([array(RuleStruct), literal(null)])),\n});\n\nexport const RequestExecutionPermissionsStruct = array(PermissionRequestStruct);\n\n// RequestExecutionPermissions API types\nexport type RequestExecutionPermissionsRequestParams = Infer<\n typeof RequestExecutionPermissionsStruct\n>;\n\nexport type RequestExecutionPermissionsResult = Json &\n (Infer<typeof PermissionRequestStruct> & {\n context: Hex;\n })[];\n\nexport type ProcessRequestExecutionPermissionsHook = (\n request: RequestExecutionPermissionsRequestParams,\n req: JsonRpcRequest,\n) => Promise<RequestExecutionPermissionsResult>;\n\nexport async function walletRequestExecutionPermissions(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRequestExecutionPermissions,\n }: {\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n },\n): Promise<void> {\n if (!processRequestExecutionPermissions) {\n throw rpcErrors.methodNotSupported(\n 'wallet_requestExecutionPermissions - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RequestExecutionPermissionsStruct);\n\n res.result = await processRequestExecutionPermissions(params, req);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet-revoke-execution-permission.cjs","sourceRoot":"","sources":["../../src/methods/wallet-revoke-execution-permission.ts"],"names":[],"mappings":";;;AAAA,qDAAiD;AAEjD,2CAKyB;AAEzB,wDAAqD;AAExC,QAAA,qCAAqC,GAAG,IAAA,cAAM,EAAC,EAAE,CAAC,CAAC;AAMnD,QAAA,4CAA4C,GAAG,IAAA,cAAM,EAAC;IACjE,iBAAiB,EAAE,uBAAe;CACnC,CAAC,CAAC;AAWI,KAAK,UAAU,+BAA+B,CACnD,GAAmB,EACnB,GAA2B,EAC3B,EACE,gCAAgC,GAGjC;IAED,IAAI,CAAC,gCAAgC,EAAE;QACrC,MAAM,sBAAS,CAAC,kBAAkB,CAChC,6DAA6D,CAC9D,CAAC;KACH;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAA,2BAAc,EAAC,MAAM,EAAE,oDAA4C,CAAC,CAAC;IAErE,GAAG,CAAC,MAAM,GAAG,MAAM,gCAAgC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACnE,CAAC;AApBD,0EAoBC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n type JsonRpcRequest,\n object,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nexport const RevokeExecutionPermissionResultStruct = object({});\n\nexport type RevokeExecutionPermissionResult = Infer<\n typeof RevokeExecutionPermissionResultStruct\n>;\n\nexport const RevokeExecutionPermissionRequestParamsStruct = object({\n permissionContext: StrictHexStruct,\n});\n\nexport type RevokeExecutionPermissionRequestParams = Infer<\n typeof RevokeExecutionPermissionRequestParamsStruct\n>;\n\nexport type ProcessRevokeExecutionPermissionHook = (\n request: RevokeExecutionPermissionRequestParams,\n req: JsonRpcRequest,\n) => Promise<RevokeExecutionPermissionResult>;\n\nexport async function walletRevokeExecutionPermission(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRevokeExecutionPermission,\n }: {\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n },\n): Promise<void> {\n if (!processRevokeExecutionPermission) {\n throw rpcErrors.methodNotSupported(\n 'wallet_revokeExecutionPermission - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RevokeExecutionPermissionRequestParamsStruct);\n\n res.result = await processRevokeExecutionPermission(params, req);\n}\n"]}
1
+ {"version":3,"file":"wallet-revoke-execution-permission.cjs","sourceRoot":"","sources":["../../src/methods/wallet-revoke-execution-permission.ts"],"names":[],"mappings":";;;AAAA,qDAAiD;AAEjD,2CAKyB;AAEzB,wDAAqD;AAExC,QAAA,qCAAqC,GAAG,IAAA,cAAM,EAAC,EAAE,CAAC,CAAC;AAMnD,QAAA,4CAA4C,GAAG,IAAA,cAAM,EAAC;IACjE,iBAAiB,EAAE,uBAAe;CACnC,CAAC,CAAC;AAWI,KAAK,UAAU,+BAA+B,CACnD,GAAmB,EACnB,GAA2B,EAC3B,EACE,gCAAgC,GAGjC;IAED,IAAI,CAAC,gCAAgC,EAAE,CAAC;QACtC,MAAM,sBAAS,CAAC,kBAAkB,CAChC,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,IAAA,2BAAc,EAAC,MAAM,EAAE,oDAA4C,CAAC,CAAC;IAErE,GAAG,CAAC,MAAM,GAAG,MAAM,gCAAgC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACnE,CAAC;AApBD,0EAoBC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n type JsonRpcRequest,\n object,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nexport const RevokeExecutionPermissionResultStruct = object({});\n\nexport type RevokeExecutionPermissionResult = Infer<\n typeof RevokeExecutionPermissionResultStruct\n>;\n\nexport const RevokeExecutionPermissionRequestParamsStruct = object({\n permissionContext: StrictHexStruct,\n});\n\nexport type RevokeExecutionPermissionRequestParams = Infer<\n typeof RevokeExecutionPermissionRequestParamsStruct\n>;\n\nexport type ProcessRevokeExecutionPermissionHook = (\n request: RevokeExecutionPermissionRequestParams,\n req: JsonRpcRequest,\n) => Promise<RevokeExecutionPermissionResult>;\n\nexport async function walletRevokeExecutionPermission(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRevokeExecutionPermission,\n }: {\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n },\n): Promise<void> {\n if (!processRevokeExecutionPermission) {\n throw rpcErrors.methodNotSupported(\n 'wallet_revokeExecutionPermission - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RevokeExecutionPermissionRequestParamsStruct);\n\n res.result = await processRevokeExecutionPermission(params, req);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet-revoke-execution-permission.mjs","sourceRoot":"","sources":["../../src/methods/wallet-revoke-execution-permission.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAEL,MAAM,EAEN,eAAe,EAChB,wBAAwB;AAEzB,OAAO,EAAE,cAAc,EAAE,gCAA4B;AAErD,MAAM,CAAC,MAAM,qCAAqC,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAMhE,MAAM,CAAC,MAAM,4CAA4C,GAAG,MAAM,CAAC;IACjE,iBAAiB,EAAE,eAAe;CACnC,CAAC,CAAC;AAWH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,GAAmB,EACnB,GAA2B,EAC3B,EACE,gCAAgC,GAGjC;IAED,IAAI,CAAC,gCAAgC,EAAE;QACrC,MAAM,SAAS,CAAC,kBAAkB,CAChC,6DAA6D,CAC9D,CAAC;KACH;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,cAAc,CAAC,MAAM,EAAE,4CAA4C,CAAC,CAAC;IAErE,GAAG,CAAC,MAAM,GAAG,MAAM,gCAAgC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n type JsonRpcRequest,\n object,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nexport const RevokeExecutionPermissionResultStruct = object({});\n\nexport type RevokeExecutionPermissionResult = Infer<\n typeof RevokeExecutionPermissionResultStruct\n>;\n\nexport const RevokeExecutionPermissionRequestParamsStruct = object({\n permissionContext: StrictHexStruct,\n});\n\nexport type RevokeExecutionPermissionRequestParams = Infer<\n typeof RevokeExecutionPermissionRequestParamsStruct\n>;\n\nexport type ProcessRevokeExecutionPermissionHook = (\n request: RevokeExecutionPermissionRequestParams,\n req: JsonRpcRequest,\n) => Promise<RevokeExecutionPermissionResult>;\n\nexport async function walletRevokeExecutionPermission(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRevokeExecutionPermission,\n }: {\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n },\n): Promise<void> {\n if (!processRevokeExecutionPermission) {\n throw rpcErrors.methodNotSupported(\n 'wallet_revokeExecutionPermission - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RevokeExecutionPermissionRequestParamsStruct);\n\n res.result = await processRevokeExecutionPermission(params, req);\n}\n"]}
1
+ {"version":3,"file":"wallet-revoke-execution-permission.mjs","sourceRoot":"","sources":["../../src/methods/wallet-revoke-execution-permission.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAEL,MAAM,EAEN,eAAe,EAChB,wBAAwB;AAEzB,OAAO,EAAE,cAAc,EAAE,gCAA4B;AAErD,MAAM,CAAC,MAAM,qCAAqC,GAAG,MAAM,CAAC,EAAE,CAAC,CAAC;AAMhE,MAAM,CAAC,MAAM,4CAA4C,GAAG,MAAM,CAAC;IACjE,iBAAiB,EAAE,eAAe;CACnC,CAAC,CAAC;AAWH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,GAAmB,EACnB,GAA2B,EAC3B,EACE,gCAAgC,GAGjC;IAED,IAAI,CAAC,gCAAgC,EAAE,CAAC;QACtC,MAAM,SAAS,CAAC,kBAAkB,CAChC,6DAA6D,CAC9D,CAAC;IACJ,CAAC;IAED,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC;IAEvB,cAAc,CAAC,MAAM,EAAE,4CAA4C,CAAC,CAAC;IAErE,GAAG,CAAC,MAAM,GAAG,MAAM,gCAAgC,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n type JsonRpcRequest,\n object,\n type PendingJsonRpcResponse,\n StrictHexStruct,\n} from '@metamask/utils';\n\nimport { validateParams } from '../utils/validation';\n\nexport const RevokeExecutionPermissionResultStruct = object({});\n\nexport type RevokeExecutionPermissionResult = Infer<\n typeof RevokeExecutionPermissionResultStruct\n>;\n\nexport const RevokeExecutionPermissionRequestParamsStruct = object({\n permissionContext: StrictHexStruct,\n});\n\nexport type RevokeExecutionPermissionRequestParams = Infer<\n typeof RevokeExecutionPermissionRequestParamsStruct\n>;\n\nexport type ProcessRevokeExecutionPermissionHook = (\n request: RevokeExecutionPermissionRequestParams,\n req: JsonRpcRequest,\n) => Promise<RevokeExecutionPermissionResult>;\n\nexport async function walletRevokeExecutionPermission(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n {\n processRevokeExecutionPermission,\n }: {\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n },\n): Promise<void> {\n if (!processRevokeExecutionPermission) {\n throw rpcErrors.methodNotSupported(\n 'wallet_revokeExecutionPermission - no middleware configured',\n );\n }\n\n const { params } = req;\n\n validateParams(params, RevokeExecutionPermissionRequestParamsStruct);\n\n res.result = await processRevokeExecutionPermission(params, req);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"retryOnEmpty.cjs","sourceRoot":"","sources":["../src/retryOnEmpty.ts"],"names":[],"mappings":";;;AAGA,+DAAkE;AAElE,qCAAmC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QACvB,CAAC,CAAC,CAAC;QACH,GAAG,CAAC,mBAAmB,EAAE,WAAW,CAAC,CAAC;QACtC,2CAA2C;QAC3C,GAAG,CAAC,MAAM,GAAG,WAAW,CAAC;QACzB,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AA3FD,oEA2FC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,KAAK,CAClB,UAAkB,EAClB,OAA8B;IAE9B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE;QAC/C,IAAI;YACF,OAAO,MAAM,OAAO,EAAE,CAAC;SACxB;QAAC,OAAO,GAAY,EAAE;YACrB,IAAI,IAAA,gCAAwB,EAAC,GAAG,CAAC,EAAE;gBACjC,MAAM,GAAc,CAAC;aACtB;YACD,GAAG,CAAC,wDAAwD,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YACzE,MAAM,IAAA,iBAAO,EAAC,IAAI,CAAC,CAAC;SACrB;KACF;IACD,GAAG,CAAC,mBAAmB,CAAC,CAAC;IACzB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\nimport { isExecutionRevertedError } from './utils/error';\nimport { timeout } from './utils/timeout';\n\n//\n// RetryOnEmptyMiddleware will retry any request with an empty response that has\n// a numbered block reference at or lower than the blockTracker's latest block.\n// Its useful for dealing with load-balanced ethereum JSON RPC\n// nodes that are not always in sync with each other.\n//\n\nconst log = createModuleLogger(projectLogger, 'retry-on-empty');\n// empty values used to determine if a request should be retried\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [null, '\\u003cnil\\u003e'];\n\n/**\n * Creates a middleware that retries requests with empty responses.\n *\n * @param options - The options for the middleware.\n * @param options.provider - The provider to use.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createRetryOnEmptyMiddleware({\n provider,\n blockTracker,\n}: {\n provider?: InternalProvider;\n blockTracker?: PollingBlockTracker;\n} = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"provider\" option is missing.',\n );\n }\n\n if (!blockTracker) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n // skip if not exact block references\n let blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : undefined;\n // omitted blockRef implies \"latest\"\n if (blockRef === undefined) {\n blockRef = 'latest';\n }\n\n // skip if non-number block reference\n if (['latest', 'pending'].includes(blockRef)) {\n return next();\n }\n // skip if block refernce is not a valid number\n const blockRefNumber: number = Number.parseInt(blockRef.slice(2), 16);\n if (Number.isNaN(blockRefNumber)) {\n return next();\n }\n // lookup latest block\n const latestBlockNumberHex: string = await blockTracker.getLatestBlock();\n const latestBlockNumber: number = Number.parseInt(\n latestBlockNumberHex.slice(2),\n 16,\n );\n // skip if request block number is higher than current\n if (blockRefNumber > latestBlockNumber) {\n log(\n 'Requested block number %o is higher than latest block number %o, falling through to original request',\n blockRefNumber,\n latestBlockNumber,\n );\n return next();\n }\n\n log(\n 'Requested block number %o is not higher than latest block number %o, trying request until non-empty response is received',\n blockRefNumber,\n latestBlockNumber,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n // attempt child request until non-empty response is received\n const childResult = await retry(10, async () => {\n log('Performing request %o', childRequest);\n const attemptResult = await provider.request<JsonRpcParams, Block>(\n childRequest,\n );\n log('Result is %o', attemptResult);\n // verify result\n const allEmptyValues: unknown[] = emptyValues;\n if (allEmptyValues.includes(attemptResult)) {\n throw new Error(\n `RetryOnEmptyMiddleware - empty result \"${JSON.stringify(\n attemptResult,\n )}\" for request \"${JSON.stringify(childRequest)}\"`,\n );\n }\n return attemptResult;\n });\n log('Copying result %o', childResult);\n // copy child result onto original response\n res.result = childResult;\n return undefined;\n });\n}\n\n/**\n * Retries an asynchronous function up to a maximum number of times.\n *\n * @param maxRetries - The maximum number of retries.\n * @param asyncFn - The asynchronous function to retry.\n * @returns The result of the asynchronous function.\n */\nasync function retry<Result>(\n maxRetries: number,\n asyncFn: () => Promise<Result>,\n): Promise<Result> {\n for (let index = 0; index < maxRetries; index++) {\n try {\n return await asyncFn();\n } catch (err: unknown) {\n if (isExecutionRevertedError(err)) {\n throw err as unknown;\n }\n log('(call %i) Request failed, waiting 1s to retry again...', index + 1);\n await timeout(1000);\n }\n }\n log('Retries exhausted');\n throw new Error('RetryOnEmptyMiddleware - retries exhausted');\n}\n"]}
1
+ {"version":3,"file":"retryOnEmpty.cjs","sourceRoot":"","sources":["../src/retryOnEmpty.ts"],"names":[],"mappings":";;;AAGA,+DAAkE;AAElE,qCAAmC;AAEnC,uDAAoE;AAEpE,6CAAmD;AACnD,6CAAyD;AACzD,iDAA0C;AAE1C,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8DAA8D;AAC9D,qDAAqD;AACrD,EAAE;AAEF,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,gBAAgB,CAAC,CAAC;AAChE,gEAAgE;AAChE,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAE9C;;;;;;;GAOG;AACH,SAAgB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,CAClB,UAAkB,EAClB,OAA8B;IAE9B,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,UAAU,EAAE,KAAK,EAAE,EAAE,CAAC;QAChD,IAAI,CAAC;YACH,OAAO,MAAM,OAAO,EAAE,CAAC;QACzB,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACtB,IAAI,IAAA,gCAAwB,EAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,MAAM,GAAc,CAAC;YACvB,CAAC;YACD,GAAG,CAAC,wDAAwD,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YACzE,MAAM,IAAA,iBAAO,EAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IACD,GAAG,CAAC,mBAAmB,CAAC,CAAC;IACzB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\nimport { isExecutionRevertedError } from './utils/error';\nimport { timeout } from './utils/timeout';\n\n//\n// RetryOnEmptyMiddleware will retry any request with an empty response that has\n// a numbered block reference at or lower than the blockTracker's latest block.\n// Its useful for dealing with load-balanced ethereum JSON RPC\n// nodes that are not always in sync with each other.\n//\n\nconst log = createModuleLogger(projectLogger, 'retry-on-empty');\n// empty values used to determine if a request should be retried\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [null, '\\u003cnil\\u003e'];\n\n/**\n * Creates a middleware that retries requests with empty responses.\n *\n * @param options - The options for the middleware.\n * @param options.provider - The provider to use.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createRetryOnEmptyMiddleware({\n provider,\n blockTracker,\n}: {\n provider?: InternalProvider;\n blockTracker?: PollingBlockTracker;\n} = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"provider\" option is missing.',\n );\n }\n\n if (!blockTracker) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n // skip if not exact block references\n let blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : undefined;\n // omitted blockRef implies \"latest\"\n if (blockRef === undefined) {\n blockRef = 'latest';\n }\n\n // skip if non-number block reference\n if (['latest', 'pending'].includes(blockRef)) {\n return next();\n }\n // skip if block refernce is not a valid number\n const blockRefNumber: number = Number.parseInt(blockRef.slice(2), 16);\n if (Number.isNaN(blockRefNumber)) {\n return next();\n }\n // lookup latest block\n const latestBlockNumberHex: string = await blockTracker.getLatestBlock();\n const latestBlockNumber: number = Number.parseInt(\n latestBlockNumberHex.slice(2),\n 16,\n );\n // skip if request block number is higher than current\n if (blockRefNumber > latestBlockNumber) {\n log(\n 'Requested block number %o is higher than latest block number %o, falling through to original request',\n blockRefNumber,\n latestBlockNumber,\n );\n return next();\n }\n\n log(\n 'Requested block number %o is not higher than latest block number %o, trying request until non-empty response is received',\n blockRefNumber,\n latestBlockNumber,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n // attempt child request until non-empty response is received\n const childResult = await retry(10, async () => {\n log('Performing request %o', childRequest);\n const attemptResult = await provider.request<JsonRpcParams, Block>(\n childRequest,\n );\n log('Result is %o', attemptResult);\n // verify result\n const allEmptyValues: unknown[] = emptyValues;\n if (allEmptyValues.includes(attemptResult)) {\n throw new Error(\n `RetryOnEmptyMiddleware - empty result \"${JSON.stringify(\n attemptResult,\n )}\" for request \"${JSON.stringify(childRequest)}\"`,\n );\n }\n return attemptResult;\n });\n log('Copying result %o', childResult);\n // copy child result onto original response\n res.result = childResult;\n return undefined;\n });\n}\n\n/**\n * Retries an asynchronous function up to a maximum number of times.\n *\n * @param maxRetries - The maximum number of retries.\n * @param asyncFn - The asynchronous function to retry.\n * @returns The result of the asynchronous function.\n */\nasync function retry<Result>(\n maxRetries: number,\n asyncFn: () => Promise<Result>,\n): Promise<Result> {\n for (let index = 0; index < maxRetries; index++) {\n try {\n return await asyncFn();\n } catch (err: unknown) {\n if (isExecutionRevertedError(err)) {\n throw err as unknown;\n }\n log('(call %i) Request failed, waiting 1s to retry again...', index + 1);\n await timeout(1000);\n }\n }\n log('Retries exhausted');\n throw new Error('RetryOnEmptyMiddleware - retries exhausted');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"retryOnEmpty.mjs","sourceRoot":"","sources":["../src/retryOnEmpty.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAElE,OAAO,EAAE,KAAK,EAAE,mBAAmB;AAEnC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AACnD,OAAO,EAAE,wBAAwB,EAAE,0BAAsB;AACzD,OAAO,EAAE,OAAO,EAAE,4BAAwB;AAE1C,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8DAA8D;AAC9D,qDAAqD;AACrD,EAAE;AAEF,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAChE,gEAAgE;AAChE,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,4BAA4B,CAAC,EAC3C,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;SACxB;QAAC,OAAO,GAAY,EAAE;YACrB,IAAI,wBAAwB,CAAC,GAAG,CAAC,EAAE;gBACjC,MAAM,GAAc,CAAC;aACtB;YACD,GAAG,CAAC,wDAAwD,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YACzE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;SACrB;KACF;IACD,GAAG,CAAC,mBAAmB,CAAC,CAAC;IACzB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\nimport { isExecutionRevertedError } from './utils/error';\nimport { timeout } from './utils/timeout';\n\n//\n// RetryOnEmptyMiddleware will retry any request with an empty response that has\n// a numbered block reference at or lower than the blockTracker's latest block.\n// Its useful for dealing with load-balanced ethereum JSON RPC\n// nodes that are not always in sync with each other.\n//\n\nconst log = createModuleLogger(projectLogger, 'retry-on-empty');\n// empty values used to determine if a request should be retried\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [null, '\\u003cnil\\u003e'];\n\n/**\n * Creates a middleware that retries requests with empty responses.\n *\n * @param options - The options for the middleware.\n * @param options.provider - The provider to use.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createRetryOnEmptyMiddleware({\n provider,\n blockTracker,\n}: {\n provider?: InternalProvider;\n blockTracker?: PollingBlockTracker;\n} = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"provider\" option is missing.',\n );\n }\n\n if (!blockTracker) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n // skip if not exact block references\n let blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : undefined;\n // omitted blockRef implies \"latest\"\n if (blockRef === undefined) {\n blockRef = 'latest';\n }\n\n // skip if non-number block reference\n if (['latest', 'pending'].includes(blockRef)) {\n return next();\n }\n // skip if block refernce is not a valid number\n const blockRefNumber: number = Number.parseInt(blockRef.slice(2), 16);\n if (Number.isNaN(blockRefNumber)) {\n return next();\n }\n // lookup latest block\n const latestBlockNumberHex: string = await blockTracker.getLatestBlock();\n const latestBlockNumber: number = Number.parseInt(\n latestBlockNumberHex.slice(2),\n 16,\n );\n // skip if request block number is higher than current\n if (blockRefNumber > latestBlockNumber) {\n log(\n 'Requested block number %o is higher than latest block number %o, falling through to original request',\n blockRefNumber,\n latestBlockNumber,\n );\n return next();\n }\n\n log(\n 'Requested block number %o is not higher than latest block number %o, trying request until non-empty response is received',\n blockRefNumber,\n latestBlockNumber,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n // attempt child request until non-empty response is received\n const childResult = await retry(10, async () => {\n log('Performing request %o', childRequest);\n const attemptResult = await provider.request<JsonRpcParams, Block>(\n childRequest,\n );\n log('Result is %o', attemptResult);\n // verify result\n const allEmptyValues: unknown[] = emptyValues;\n if (allEmptyValues.includes(attemptResult)) {\n throw new Error(\n `RetryOnEmptyMiddleware - empty result \"${JSON.stringify(\n attemptResult,\n )}\" for request \"${JSON.stringify(childRequest)}\"`,\n );\n }\n return attemptResult;\n });\n log('Copying result %o', childResult);\n // copy child result onto original response\n res.result = childResult;\n return undefined;\n });\n}\n\n/**\n * Retries an asynchronous function up to a maximum number of times.\n *\n * @param maxRetries - The maximum number of retries.\n * @param asyncFn - The asynchronous function to retry.\n * @returns The result of the asynchronous function.\n */\nasync function retry<Result>(\n maxRetries: number,\n asyncFn: () => Promise<Result>,\n): Promise<Result> {\n for (let index = 0; index < maxRetries; index++) {\n try {\n return await asyncFn();\n } catch (err: unknown) {\n if (isExecutionRevertedError(err)) {\n throw err as unknown;\n }\n log('(call %i) Request failed, waiting 1s to retry again...', index + 1);\n await timeout(1000);\n }\n }\n log('Retries exhausted');\n throw new Error('RetryOnEmptyMiddleware - retries exhausted');\n}\n"]}
1
+ {"version":3,"file":"retryOnEmpty.mjs","sourceRoot":"","sources":["../src/retryOnEmpty.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAElE,OAAO,EAAE,KAAK,EAAE,mBAAmB;AAEnC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,OAAO,EAAE,kBAAkB,EAAE,0BAAsB;AACnD,OAAO,EAAE,wBAAwB,EAAE,0BAAsB;AACzD,OAAO,EAAE,OAAO,EAAE,4BAAwB;AAE1C,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8DAA8D;AAC9D,qDAAqD;AACrD,EAAE;AAEF,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAChE,gEAAgE;AAChE,0EAA0E;AAC1E,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;AAE9C;;;;;;;GAOG;AACH,MAAM,UAAU,4BAA4B,CAAC,EAC3C,QAAQ,EACR,YAAY,MAIV,EAAE;IACJ,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,MAAM,KAAK,CACT,kEAAkE,CACnE,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,MAAM,KAAK,CACT,sEAAsE,CACvE,CAAC;IACJ,CAAC;IAED,OAAO,qBAAqB,CA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YACvB,CAAC;YACD,GAAG,CAAC,wDAAwD,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YACzE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IACD,GAAG,CAAC,mBAAmB,CAAC,CAAC;IACzB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { InternalProvider } from '@metamask/eth-json-rpc-provider';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport { createAsyncMiddleware } from '@metamask/json-rpc-engine';\nimport type { Json, JsonRpcParams } from '@metamask/utils';\nimport { klona } from 'klona/full';\n\nimport { projectLogger, createModuleLogger } from './logging-utils';\nimport type { Block } from './types';\nimport { blockTagParamIndex } from './utils/cache';\nimport { isExecutionRevertedError } from './utils/error';\nimport { timeout } from './utils/timeout';\n\n//\n// RetryOnEmptyMiddleware will retry any request with an empty response that has\n// a numbered block reference at or lower than the blockTracker's latest block.\n// Its useful for dealing with load-balanced ethereum JSON RPC\n// nodes that are not always in sync with each other.\n//\n\nconst log = createModuleLogger(projectLogger, 'retry-on-empty');\n// empty values used to determine if a request should be retried\n// `<nil>` comes from https://github.com/ethereum/go-ethereum/issues/16925\nconst emptyValues = [null, '\\u003cnil\\u003e'];\n\n/**\n * Creates a middleware that retries requests with empty responses.\n *\n * @param options - The options for the middleware.\n * @param options.provider - The provider to use.\n * @param options.blockTracker - The block tracker to use.\n * @returns The middleware.\n */\nexport function createRetryOnEmptyMiddleware({\n provider,\n blockTracker,\n}: {\n provider?: InternalProvider;\n blockTracker?: PollingBlockTracker;\n} = {}): JsonRpcMiddleware<JsonRpcParams, Json> {\n if (!provider) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"provider\" option is missing.',\n );\n }\n\n if (!blockTracker) {\n throw Error(\n 'RetryOnEmptyMiddleware - mandatory \"blockTracker\" option is missing.',\n );\n }\n\n return createAsyncMiddleware(async (req, res, next) => {\n const blockRefIndex: number | undefined = blockTagParamIndex(req.method);\n // skip if method does not include blockRef\n if (blockRefIndex === undefined) {\n return next();\n }\n // skip if not exact block references\n let blockRef: string | undefined =\n Array.isArray(req.params) && req.params[blockRefIndex]\n ? (req.params[blockRefIndex] as string)\n : undefined;\n // omitted blockRef implies \"latest\"\n if (blockRef === undefined) {\n blockRef = 'latest';\n }\n\n // skip if non-number block reference\n if (['latest', 'pending'].includes(blockRef)) {\n return next();\n }\n // skip if block refernce is not a valid number\n const blockRefNumber: number = Number.parseInt(blockRef.slice(2), 16);\n if (Number.isNaN(blockRefNumber)) {\n return next();\n }\n // lookup latest block\n const latestBlockNumberHex: string = await blockTracker.getLatestBlock();\n const latestBlockNumber: number = Number.parseInt(\n latestBlockNumberHex.slice(2),\n 16,\n );\n // skip if request block number is higher than current\n if (blockRefNumber > latestBlockNumber) {\n log(\n 'Requested block number %o is higher than latest block number %o, falling through to original request',\n blockRefNumber,\n latestBlockNumber,\n );\n return next();\n }\n\n log(\n 'Requested block number %o is not higher than latest block number %o, trying request until non-empty response is received',\n blockRefNumber,\n latestBlockNumber,\n );\n\n // create child request with specific block-ref\n const childRequest = klona(req);\n // attempt child request until non-empty response is received\n const childResult = await retry(10, async () => {\n log('Performing request %o', childRequest);\n const attemptResult = await provider.request<JsonRpcParams, Block>(\n childRequest,\n );\n log('Result is %o', attemptResult);\n // verify result\n const allEmptyValues: unknown[] = emptyValues;\n if (allEmptyValues.includes(attemptResult)) {\n throw new Error(\n `RetryOnEmptyMiddleware - empty result \"${JSON.stringify(\n attemptResult,\n )}\" for request \"${JSON.stringify(childRequest)}\"`,\n );\n }\n return attemptResult;\n });\n log('Copying result %o', childResult);\n // copy child result onto original response\n res.result = childResult;\n return undefined;\n });\n}\n\n/**\n * Retries an asynchronous function up to a maximum number of times.\n *\n * @param maxRetries - The maximum number of retries.\n * @param asyncFn - The asynchronous function to retry.\n * @returns The result of the asynchronous function.\n */\nasync function retry<Result>(\n maxRetries: number,\n asyncFn: () => Promise<Result>,\n): Promise<Result> {\n for (let index = 0; index < maxRetries; index++) {\n try {\n return await asyncFn();\n } catch (err: unknown) {\n if (isExecutionRevertedError(err)) {\n throw err as unknown;\n }\n log('(call %i) Request failed, waiting 1s to retry again...', index + 1);\n await timeout(1000);\n }\n }\n log('Retries exhausted');\n throw new Error('RetryOnEmptyMiddleware - retries exhausted');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.cjs","sourceRoot":"","sources":["../../src/utils/cache.ts"],"names":[],"mappings":";;;AACA,iEAAkD;AAElD,MAAM,SAAS,GAAG,IAAA,iCAAS,EAAC,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,CAAC;AAErE;;GAEG;AACH,IAAY,aAiBX;AAjBD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,8BAAa,CAAA;IACb;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,oCAAmB,CAAA;AACrB,CAAC,EAjBW,aAAa,6BAAb,aAAa,QAiBxB;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,yBAAyB,CACvC,OAAuB,EACvB,YAAsB;IAEtB,MAAM,YAAY,GAAG,YAAY;QAC/B,CAAC,CAAC,qBAAqB,CAAC,OAAO,CAAC;QAChC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAC3B,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;QAC5B,OAAO,GAAG,OAAO,CAAC,MAAM,IAAI,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC;KACvD;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAXD,8DAWC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,MAAc;IACrC,OAAO,kBAAkB,CAAC,MAAM,CAAC,KAAK,aAAa,CAAC,KAAK,CAAC;AAC5D,C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AAC;QACvB,KAAK,mBAAmB,CAAC;QACzB,KAAK,aAAa,CAAC;QACnB,KAAK,iBAAiB;YACpB,OAAO,aAAa,CAAC,KAAK,CAAC;QAE7B,cAAc;QACd;YACE,OAAO,aAAa,CAAC,KAAK,CAAC;KAC9B;AACH,CAAC;AAhDD,gDAgDC","sourcesContent":["import type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { configure } from 'safe-stable-stringify';\n\nconst stringify = configure({ bigint: false, circularValue: Error });\n\n/**\n * The cache strategy to use for a given method.\n */\nexport enum CacheStrategy {\n /**\n * Cache per-block.\n */\n Block = 'block',\n /**\n * Cache until a chain reorganization occurs.\n */\n Fork = 'fork',\n /**\n * Never cache.\n */\n Never = 'never',\n /**\n * Permanently cache.\n */\n Permanent = 'perma',\n}\n\n/**\n * Return a cache identifier for the given request.\n *\n * This identifier should include any request details that might impact the\n * response, with the exception of the block parameter if the `skipBlockRef`\n * option is set,\n *\n * If the request cannot be cached, this will return `null`.\n *\n * @param request - The JSON-RPC request.\n * @param skipBlockRef - Skip the block parameter when generating the cache\n * identifier.\n * @returns The cache identifier for this request, or `null` if it can't be\n * cached.\n */\nexport function cacheIdentifierForRequest(\n request: JsonRpcRequest,\n skipBlockRef?: boolean,\n): string | null {\n const simpleParams = skipBlockRef\n ? paramsWithoutBlockTag(request)\n : (request.params ?? []);\n if (canCache(request.method)) {\n return `${request.method}:${stringify(simpleParams)}`;\n }\n return null;\n}\n\n/**\n * Return whether a method can be cached or not.\n *\n * @param method - The method to check.\n * @returns Whether the method can be cached.\n */\nexport function canCache(method: string): boolean {\n return cacheTypeForMethod(method) !== CacheStrategy.Never;\n}\n\n/**\n * Return the block parameter for the given request, if it has one.\n *\n * @param request - The JSON-RPC request.\n * @returns The block parameter in the given request, or `undefined` if none was found.\n */\nexport function blockTagForRequest(request: JsonRpcRequest): Json | undefined {\n if (!request.params) {\n return undefined;\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return undefined;\n }\n\n return request.params[index];\n}\n\n/**\n * Return the request parameters without the block parameter.\n *\n * @param request - The JSON-RPC request.\n * @returns The request parameters with the block parameter removed, if one was found.\n */\nfunction paramsWithoutBlockTag(request: JsonRpcRequest): Json {\n if (!request.params) {\n return [];\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return request.params;\n }\n\n // eth_getBlockByNumber has the block tag first, then the optional includeTx? param\n if (request.method === 'eth_getBlockByNumber') {\n return request.params.slice(1);\n }\n return request.params.slice(0, index);\n}\n\n/**\n * Returns the index of the block parameter for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The index of the block parameter for that method, or `undefined` if\n * there is no known block parameter.\n */\nexport function blockTagParamIndex(method: string): number | undefined {\n switch (method) {\n // blockTag is at index 2\n case 'eth_getStorageAt':\n return 2;\n // blockTag is at index 1\n case 'eth_getBalance':\n case 'eth_getCode':\n case 'eth_getTransactionCount':\n case 'eth_call':\n return 1;\n // blockTag is at index 0\n case 'eth_getBlockByNumber':\n return 0;\n // there is no blockTag\n default:\n return undefined;\n }\n}\n\n/**\n * Return the cache type used for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The cache type to use for that method.\n */\nexport function cacheTypeForMethod(method: string): CacheStrategy {\n switch (method) {\n // cache permanently\n case 'web3_clientVersion':\n case 'web3_sha3':\n case 'eth_protocolVersion':\n case 'eth_getBlockTransactionCountByHash':\n case 'eth_getUncleCountByBlockHash':\n case 'eth_getCode':\n case 'eth_getBlockByHash':\n case 'eth_getTransactionByHash':\n case 'eth_getTransactionByBlockHashAndIndex':\n case 'eth_getTransactionReceipt':\n case 'eth_getUncleByBlockHashAndIndex':\n case 'eth_getCompilers':\n case 'eth_compileLLL':\n case 'eth_compileSolidity':\n case 'eth_compileSerpent':\n case 'shh_version':\n case 'test_permaCache':\n return CacheStrategy.Permanent;\n\n // cache until fork\n case 'eth_getBlockByNumber':\n case 'eth_getBlockTransactionCountByNumber':\n case 'eth_getUncleCountByBlockNumber':\n case 'eth_getTransactionByBlockNumberAndIndex':\n case 'eth_getUncleByBlockNumberAndIndex':\n case 'test_forkCache':\n return CacheStrategy.Fork;\n\n // cache for block\n case 'eth_gasPrice':\n case 'eth_blockNumber':\n case 'eth_getBalance':\n case 'eth_getStorageAt':\n case 'eth_getTransactionCount':\n case 'eth_call':\n case 'eth_estimateGas':\n case 'eth_getFilterLogs':\n case 'eth_getLogs':\n case 'test_blockCache':\n return CacheStrategy.Block;\n\n // never cache\n default:\n return CacheStrategy.Never;\n }\n}\n"]}
1
+ {"version":3,"file":"cache.cjs","sourceRoot":"","sources":["../../src/utils/cache.ts"],"names":[],"mappings":";;;AACA,iEAAkD;AAElD,MAAM,SAAS,GAAG,IAAA,iCAAS,EAAC,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,CAAC;AAErE;;GAEG;AACH,IAAY,aAiBX;AAjBD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,8BAAa,CAAA;IACb;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,oCAAmB,CAAA;AACrB,CAAC,EAjBW,aAAa,6BAAb,aAAa,QAiBxB;AAED;;;;;;;;;;;;;;GAcG;AACH,SAAgB,yBAAyB,CACvC,OAAuB,EACvB,YAAsB;IAEtB,MAAM,YAAY,GAAG,YAAY;QAC/B,CAAC,CAAC,qBAAqB,CAAC,OAAO,CAAC;QAChC,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAC3B,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7B,OAAO,GAAG,OAAO,CAAC,MAAM,IAAI,SAAS,CAAC,YAAY,CAAC,EAAE,CAAC;IACxD,CAAC;IACD,OAA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AAK,gBAAgB;YACnB,OAAO,aAAa,CAAC,IAAI,CAAC;QAE5B,kBAAkB;QAClB,KAAK,cAAc,CAAC;QACpB,KAAK,iBAAiB,CAAC;QACvB,KAAK,gBAAgB,CAAC;QACtB,KAAK,kBAAkB,CAAC;QACxB,KAAK,yBAAyB,CAAC;QAC/B,KAAK,UAAU,CAAC;QAChB,KAAK,iBAAiB,CAAC;QACvB,KAAK,mBAAmB,CAAC;QACzB,KAAK,aAAa,CAAC;QACnB,KAAK,iBAAiB;YACpB,OAAO,aAAa,CAAC,KAAK,CAAC;QAE7B,cAAc;QACd;YACE,OAAO,aAAa,CAAC,KAAK,CAAC;IAC/B,CAAC;AACH,CAAC;AAhDD,gDAgDC","sourcesContent":["import type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { configure } from 'safe-stable-stringify';\n\nconst stringify = configure({ bigint: false, circularValue: Error });\n\n/**\n * The cache strategy to use for a given method.\n */\nexport enum CacheStrategy {\n /**\n * Cache per-block.\n */\n Block = 'block',\n /**\n * Cache until a chain reorganization occurs.\n */\n Fork = 'fork',\n /**\n * Never cache.\n */\n Never = 'never',\n /**\n * Permanently cache.\n */\n Permanent = 'perma',\n}\n\n/**\n * Return a cache identifier for the given request.\n *\n * This identifier should include any request details that might impact the\n * response, with the exception of the block parameter if the `skipBlockRef`\n * option is set,\n *\n * If the request cannot be cached, this will return `null`.\n *\n * @param request - The JSON-RPC request.\n * @param skipBlockRef - Skip the block parameter when generating the cache\n * identifier.\n * @returns The cache identifier for this request, or `null` if it can't be\n * cached.\n */\nexport function cacheIdentifierForRequest(\n request: JsonRpcRequest,\n skipBlockRef?: boolean,\n): string | null {\n const simpleParams = skipBlockRef\n ? paramsWithoutBlockTag(request)\n : (request.params ?? []);\n if (canCache(request.method)) {\n return `${request.method}:${stringify(simpleParams)}`;\n }\n return null;\n}\n\n/**\n * Return whether a method can be cached or not.\n *\n * @param method - The method to check.\n * @returns Whether the method can be cached.\n */\nexport function canCache(method: string): boolean {\n return cacheTypeForMethod(method) !== CacheStrategy.Never;\n}\n\n/**\n * Return the block parameter for the given request, if it has one.\n *\n * @param request - The JSON-RPC request.\n * @returns The block parameter in the given request, or `undefined` if none was found.\n */\nexport function blockTagForRequest(request: JsonRpcRequest): Json | undefined {\n if (!request.params) {\n return undefined;\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return undefined;\n }\n\n return request.params[index];\n}\n\n/**\n * Return the request parameters without the block parameter.\n *\n * @param request - The JSON-RPC request.\n * @returns The request parameters with the block parameter removed, if one was found.\n */\nfunction paramsWithoutBlockTag(request: JsonRpcRequest): Json {\n if (!request.params) {\n return [];\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return request.params;\n }\n\n // eth_getBlockByNumber has the block tag first, then the optional includeTx? param\n if (request.method === 'eth_getBlockByNumber') {\n return request.params.slice(1);\n }\n return request.params.slice(0, index);\n}\n\n/**\n * Returns the index of the block parameter for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The index of the block parameter for that method, or `undefined` if\n * there is no known block parameter.\n */\nexport function blockTagParamIndex(method: string): number | undefined {\n switch (method) {\n // blockTag is at index 2\n case 'eth_getStorageAt':\n return 2;\n // blockTag is at index 1\n case 'eth_getBalance':\n case 'eth_getCode':\n case 'eth_getTransactionCount':\n case 'eth_call':\n return 1;\n // blockTag is at index 0\n case 'eth_getBlockByNumber':\n return 0;\n // there is no blockTag\n default:\n return undefined;\n }\n}\n\n/**\n * Return the cache type used for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The cache type to use for that method.\n */\nexport function cacheTypeForMethod(method: string): CacheStrategy {\n switch (method) {\n // cache permanently\n case 'web3_clientVersion':\n case 'web3_sha3':\n case 'eth_protocolVersion':\n case 'eth_getBlockTransactionCountByHash':\n case 'eth_getUncleCountByBlockHash':\n case 'eth_getCode':\n case 'eth_getBlockByHash':\n case 'eth_getTransactionByHash':\n case 'eth_getTransactionByBlockHashAndIndex':\n case 'eth_getTransactionReceipt':\n case 'eth_getUncleByBlockHashAndIndex':\n case 'eth_getCompilers':\n case 'eth_compileLLL':\n case 'eth_compileSolidity':\n case 'eth_compileSerpent':\n case 'shh_version':\n case 'test_permaCache':\n return CacheStrategy.Permanent;\n\n // cache until fork\n case 'eth_getBlockByNumber':\n case 'eth_getBlockTransactionCountByNumber':\n case 'eth_getUncleCountByBlockNumber':\n case 'eth_getTransactionByBlockNumberAndIndex':\n case 'eth_getUncleByBlockNumberAndIndex':\n case 'test_forkCache':\n return CacheStrategy.Fork;\n\n // cache for block\n case 'eth_gasPrice':\n case 'eth_blockNumber':\n case 'eth_getBalance':\n case 'eth_getStorageAt':\n case 'eth_getTransactionCount':\n case 'eth_call':\n case 'eth_estimateGas':\n case 'eth_getFilterLogs':\n case 'eth_getLogs':\n case 'test_blockCache':\n return CacheStrategy.Block;\n\n // never cache\n default:\n return CacheStrategy.Never;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.mjs","sourceRoot":"","sources":["../../src/utils/cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,8BAA8B;AAElD,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,CAAC;AAErE;;GAEG;AACH,MAAM,CAAN,IAAY,aAiBX;AAjBD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,8BAAa,CAAA;IACb;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,oCAAmB,CAAA;AACrB,CAAC,EAjBW,aAAa,KAAb,aAAa,QAiBxB;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,yBAAyB,CACvC,OAAuB,EACvB,YAAsB;IAEtB,MAAM,Y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C;QAEjC,mBAAmB;QACnB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,sCAAsC,CAAC;QAC5C,KAAK,gCAAgC,CAAC;QACtC,KAAK,yCAAyC,CAAC;QAC/C,KAAK,mCAAmC,CAAC;QACzC,KAAK,gBAAgB;YACnB,OAAO,aAAa,CAAC,IAAI,CAAC;QAE5B,kBAAkB;QAClB,KAAK,cAAc,CAAC;QACpB,KAAK,iBAAiB,CAAC;QACvB,KAAK,gBAAgB,CAAC;QACtB,KAAK,kBAAkB,CAAC;QACxB,KAAK,yBAAyB,CAAC;QAC/B,KAAK,UAAU,CAAC;QAChB,KAAK,iBAAiB,CAAC;QACvB,KAAK,mBAAmB,CAAC;QACzB,KAAK,aAAa,CAAC;QACnB,KAAK,iBAAiB;YACpB,OAAO,aAAa,CAAC,KAAK,CAAC;QAE7B,cAAc;QACd;YACE,OAAO,aAAa,CAAC,KAAK,CAAC;KAC9B;AACH,CAAC","sourcesContent":["import type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { configure } from 'safe-stable-stringify';\n\nconst stringify = configure({ bigint: false, circularValue: Error });\n\n/**\n * The cache strategy to use for a given method.\n */\nexport enum CacheStrategy {\n /**\n * Cache per-block.\n */\n Block = 'block',\n /**\n * Cache until a chain reorganization occurs.\n */\n Fork = 'fork',\n /**\n * Never cache.\n */\n Never = 'never',\n /**\n * Permanently cache.\n */\n Permanent = 'perma',\n}\n\n/**\n * Return a cache identifier for the given request.\n *\n * This identifier should include any request details that might impact the\n * response, with the exception of the block parameter if the `skipBlockRef`\n * option is set,\n *\n * If the request cannot be cached, this will return `null`.\n *\n * @param request - The JSON-RPC request.\n * @param skipBlockRef - Skip the block parameter when generating the cache\n * identifier.\n * @returns The cache identifier for this request, or `null` if it can't be\n * cached.\n */\nexport function cacheIdentifierForRequest(\n request: JsonRpcRequest,\n skipBlockRef?: boolean,\n): string | null {\n const simpleParams = skipBlockRef\n ? paramsWithoutBlockTag(request)\n : (request.params ?? []);\n if (canCache(request.method)) {\n return `${request.method}:${stringify(simpleParams)}`;\n }\n return null;\n}\n\n/**\n * Return whether a method can be cached or not.\n *\n * @param method - The method to check.\n * @returns Whether the method can be cached.\n */\nexport function canCache(method: string): boolean {\n return cacheTypeForMethod(method) !== CacheStrategy.Never;\n}\n\n/**\n * Return the block parameter for the given request, if it has one.\n *\n * @param request - The JSON-RPC request.\n * @returns The block parameter in the given request, or `undefined` if none was found.\n */\nexport function blockTagForRequest(request: JsonRpcRequest): Json | undefined {\n if (!request.params) {\n return undefined;\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return undefined;\n }\n\n return request.params[index];\n}\n\n/**\n * Return the request parameters without the block parameter.\n *\n * @param request - The JSON-RPC request.\n * @returns The request parameters with the block parameter removed, if one was found.\n */\nfunction paramsWithoutBlockTag(request: JsonRpcRequest): Json {\n if (!request.params) {\n return [];\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return request.params;\n }\n\n // eth_getBlockByNumber has the block tag first, then the optional includeTx? param\n if (request.method === 'eth_getBlockByNumber') {\n return request.params.slice(1);\n }\n return request.params.slice(0, index);\n}\n\n/**\n * Returns the index of the block parameter for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The index of the block parameter for that method, or `undefined` if\n * there is no known block parameter.\n */\nexport function blockTagParamIndex(method: string): number | undefined {\n switch (method) {\n // blockTag is at index 2\n case 'eth_getStorageAt':\n return 2;\n // blockTag is at index 1\n case 'eth_getBalance':\n case 'eth_getCode':\n case 'eth_getTransactionCount':\n case 'eth_call':\n return 1;\n // blockTag is at index 0\n case 'eth_getBlockByNumber':\n return 0;\n // there is no blockTag\n default:\n return undefined;\n }\n}\n\n/**\n * Return the cache type used for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The cache type to use for that method.\n */\nexport function cacheTypeForMethod(method: string): CacheStrategy {\n switch (method) {\n // cache permanently\n case 'web3_clientVersion':\n case 'web3_sha3':\n case 'eth_protocolVersion':\n case 'eth_getBlockTransactionCountByHash':\n case 'eth_getUncleCountByBlockHash':\n case 'eth_getCode':\n case 'eth_getBlockByHash':\n case 'eth_getTransactionByHash':\n case 'eth_getTransactionByBlockHashAndIndex':\n case 'eth_getTransactionReceipt':\n case 'eth_getUncleByBlockHashAndIndex':\n case 'eth_getCompilers':\n case 'eth_compileLLL':\n case 'eth_compileSolidity':\n case 'eth_compileSerpent':\n case 'shh_version':\n case 'test_permaCache':\n return CacheStrategy.Permanent;\n\n // cache until fork\n case 'eth_getBlockByNumber':\n case 'eth_getBlockTransactionCountByNumber':\n case 'eth_getUncleCountByBlockNumber':\n case 'eth_getTransactionByBlockNumberAndIndex':\n case 'eth_getUncleByBlockNumberAndIndex':\n case 'test_forkCache':\n return CacheStrategy.Fork;\n\n // cache for block\n case 'eth_gasPrice':\n case 'eth_blockNumber':\n case 'eth_getBalance':\n case 'eth_getStorageAt':\n case 'eth_getTransactionCount':\n case 'eth_call':\n case 'eth_estimateGas':\n case 'eth_getFilterLogs':\n case 'eth_getLogs':\n case 'test_blockCache':\n return CacheStrategy.Block;\n\n // never cache\n default:\n return CacheStrategy.Never;\n }\n}\n"]}
1
+ {"version":3,"file":"cache.mjs","sourceRoot":"","sources":["../../src/utils/cache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,8BAA8B;AAElD,MAAM,SAAS,GAAG,SAAS,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC,CAAC;AAErE;;GAEG;AACH,MAAM,CAAN,IAAY,aAiBX;AAjBD,WAAY,aAAa;IACvB;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,8BAAa,CAAA;IACb;;OAEG;IACH,gCAAe,CAAA;IACf;;OAEG;IACH,oCAAmB,CAAA;AACrB,CAAC,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AAC;QACjC,KAAK,iCAAiC,CAAC;QACvC,KAAK,kBAAkB,CAAC;QACxB,KAAK,gBAAgB,CAAC;QACtB,KAAK,qBAAqB,CAAC;QAC3B,KAAK,oBAAoB,CAAC;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,iBAAiB;YACpB,OAAO,aAAa,CAAC,SAAS,CAAC;QAEjC,mBAAmB;QACnB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,sCAAsC,CAAC;QAC5C,KAAK,gCAAgC,CAAC;QACtC,KAAK,yCAAyC,CAAC;QAC/C,KAAK,mCAAmC,CAAC;QACzC,KAAK,gBAAgB;YACnB,OAAO,aAAa,CAAC,IAAI,CAAC;QAE5B,kBAAkB;QAClB,KAAK,cAAc,CAAC;QACpB,KAAK,iBAAiB,CAAC;QACvB,KAAK,gBAAgB,CAAC;QACtB,KAAK,kBAAkB,CAAC;QACxB,KAAK,yBAAyB,CAAC;QAC/B,KAAK,UAAU,CAAC;QAChB,KAAK,iBAAiB,CAAC;QACvB,KAAK,mBAAmB,CAAC;QACzB,KAAK,aAAa,CAAC;QACnB,KAAK,iBAAiB;YACpB,OAAO,aAAa,CAAC,KAAK,CAAC;QAE7B,cAAc;QACd;YACE,OAAO,aAAa,CAAC,KAAK,CAAC;IAC/B,CAAC;AACH,CAAC","sourcesContent":["import type { Json, JsonRpcRequest } from '@metamask/utils';\nimport { configure } from 'safe-stable-stringify';\n\nconst stringify = configure({ bigint: false, circularValue: Error });\n\n/**\n * The cache strategy to use for a given method.\n */\nexport enum CacheStrategy {\n /**\n * Cache per-block.\n */\n Block = 'block',\n /**\n * Cache until a chain reorganization occurs.\n */\n Fork = 'fork',\n /**\n * Never cache.\n */\n Never = 'never',\n /**\n * Permanently cache.\n */\n Permanent = 'perma',\n}\n\n/**\n * Return a cache identifier for the given request.\n *\n * This identifier should include any request details that might impact the\n * response, with the exception of the block parameter if the `skipBlockRef`\n * option is set,\n *\n * If the request cannot be cached, this will return `null`.\n *\n * @param request - The JSON-RPC request.\n * @param skipBlockRef - Skip the block parameter when generating the cache\n * identifier.\n * @returns The cache identifier for this request, or `null` if it can't be\n * cached.\n */\nexport function cacheIdentifierForRequest(\n request: JsonRpcRequest,\n skipBlockRef?: boolean,\n): string | null {\n const simpleParams = skipBlockRef\n ? paramsWithoutBlockTag(request)\n : (request.params ?? []);\n if (canCache(request.method)) {\n return `${request.method}:${stringify(simpleParams)}`;\n }\n return null;\n}\n\n/**\n * Return whether a method can be cached or not.\n *\n * @param method - The method to check.\n * @returns Whether the method can be cached.\n */\nexport function canCache(method: string): boolean {\n return cacheTypeForMethod(method) !== CacheStrategy.Never;\n}\n\n/**\n * Return the block parameter for the given request, if it has one.\n *\n * @param request - The JSON-RPC request.\n * @returns The block parameter in the given request, or `undefined` if none was found.\n */\nexport function blockTagForRequest(request: JsonRpcRequest): Json | undefined {\n if (!request.params) {\n return undefined;\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return undefined;\n }\n\n return request.params[index];\n}\n\n/**\n * Return the request parameters without the block parameter.\n *\n * @param request - The JSON-RPC request.\n * @returns The request parameters with the block parameter removed, if one was found.\n */\nfunction paramsWithoutBlockTag(request: JsonRpcRequest): Json {\n if (!request.params) {\n return [];\n }\n const index: number | undefined = blockTagParamIndex(request.method);\n\n // Block tag param not passed.\n if (\n index === undefined ||\n !Array.isArray(request.params) ||\n index >= request.params.length\n ) {\n return request.params;\n }\n\n // eth_getBlockByNumber has the block tag first, then the optional includeTx? param\n if (request.method === 'eth_getBlockByNumber') {\n return request.params.slice(1);\n }\n return request.params.slice(0, index);\n}\n\n/**\n * Returns the index of the block parameter for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The index of the block parameter for that method, or `undefined` if\n * there is no known block parameter.\n */\nexport function blockTagParamIndex(method: string): number | undefined {\n switch (method) {\n // blockTag is at index 2\n case 'eth_getStorageAt':\n return 2;\n // blockTag is at index 1\n case 'eth_getBalance':\n case 'eth_getCode':\n case 'eth_getTransactionCount':\n case 'eth_call':\n return 1;\n // blockTag is at index 0\n case 'eth_getBlockByNumber':\n return 0;\n // there is no blockTag\n default:\n return undefined;\n }\n}\n\n/**\n * Return the cache type used for the given method.\n *\n * @param method - A JSON-RPC method.\n * @returns The cache type to use for that method.\n */\nexport function cacheTypeForMethod(method: string): CacheStrategy {\n switch (method) {\n // cache permanently\n case 'web3_clientVersion':\n case 'web3_sha3':\n case 'eth_protocolVersion':\n case 'eth_getBlockTransactionCountByHash':\n case 'eth_getUncleCountByBlockHash':\n case 'eth_getCode':\n case 'eth_getBlockByHash':\n case 'eth_getTransactionByHash':\n case 'eth_getTransactionByBlockHashAndIndex':\n case 'eth_getTransactionReceipt':\n case 'eth_getUncleByBlockHashAndIndex':\n case 'eth_getCompilers':\n case 'eth_compileLLL':\n case 'eth_compileSolidity':\n case 'eth_compileSerpent':\n case 'shh_version':\n case 'test_permaCache':\n return CacheStrategy.Permanent;\n\n // cache until fork\n case 'eth_getBlockByNumber':\n case 'eth_getBlockTransactionCountByNumber':\n case 'eth_getUncleCountByBlockNumber':\n case 'eth_getTransactionByBlockNumberAndIndex':\n case 'eth_getUncleByBlockNumberAndIndex':\n case 'test_forkCache':\n return CacheStrategy.Fork;\n\n // cache for block\n case 'eth_gasPrice':\n case 'eth_blockNumber':\n case 'eth_getBalance':\n case 'eth_getStorageAt':\n case 'eth_getTransactionCount':\n case 'eth_call':\n case 'eth_estimateGas':\n case 'eth_getFilterLogs':\n case 'eth_getLogs':\n case 'test_blockCache':\n return CacheStrategy.Block;\n\n // never cache\n default:\n return CacheStrategy.Never;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"common.cjs","sourceRoot":"","sources":["../../src/utils/common.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACI,MAAM,uBAAuB,GAAG,CAAC,UAAkB,EAAE,EAAE;IAC5D,IAAI,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE;QACpC,OAAO,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;KACpD;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC;AALW,QAAA,uBAAuB,2BAKlC","sourcesContent":["/**\n * Function to stripe array brackets if string defining the type has it.\n *\n * @param typeString - String defining type from which array brackets are required to be removed.\n * @returns Parameter string with array brackets [] removed.\n */\nexport const stripArrayTypeIfPresent = (typeString: string) => {\n if (typeString?.match(/\\S\\[\\d*\\]$/u)) {\n return typeString.replace(/\\[\\d*\\]$/gu, '').trim();\n }\n return typeString;\n};\n"]}
1
+ {"version":3,"file":"common.cjs","sourceRoot":"","sources":["../../src/utils/common.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACI,MAAM,uBAAuB,GAAG,CAAC,UAAkB,EAAE,EAAE;IAC5D,IAAI,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC;QACrC,OAAO,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACrD,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC;AALW,QAAA,uBAAuB,2BAKlC","sourcesContent":["/**\n * Function to stripe array brackets if string defining the type has it.\n *\n * @param typeString - String defining type from which array brackets are required to be removed.\n * @returns Parameter string with array brackets [] removed.\n */\nexport const stripArrayTypeIfPresent = (typeString: string) => {\n if (typeString?.match(/\\S\\[\\d*\\]$/u)) {\n return typeString.replace(/\\[\\d*\\]$/gu, '').trim();\n }\n return typeString;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"common.mjs","sourceRoot":"","sources":["../../src/utils/common.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,UAAkB,EAAE,EAAE;IAC5D,IAAI,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE;QACpC,OAAO,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;KACpD;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC","sourcesContent":["/**\n * Function to stripe array brackets if string defining the type has it.\n *\n * @param typeString - String defining type from which array brackets are required to be removed.\n * @returns Parameter string with array brackets [] removed.\n */\nexport const stripArrayTypeIfPresent = (typeString: string) => {\n if (typeString?.match(/\\S\\[\\d*\\]$/u)) {\n return typeString.replace(/\\[\\d*\\]$/gu, '').trim();\n }\n return typeString;\n};\n"]}
1
+ {"version":3,"file":"common.mjs","sourceRoot":"","sources":["../../src/utils/common.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,CAAC,UAAkB,EAAE,EAAE;IAC5D,IAAI,UAAU,EAAE,KAAK,CAAC,aAAa,CAAC,EAAE,CAAC;QACrC,OAAO,UAAU,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IACrD,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC,CAAC","sourcesContent":["/**\n * Function to stripe array brackets if string defining the type has it.\n *\n * @param typeString - String defining type from which array brackets are required to be removed.\n * @returns Parameter string with array brackets [] removed.\n */\nexport const stripArrayTypeIfPresent = (typeString: string) => {\n if (typeString?.match(/\\S\\[\\d*\\]$/u)) {\n return typeString.replace(/\\[\\d*\\]$/gu, '').trim();\n }\n return typeString;\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.cjs","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":";;;AAaA;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI;QACF,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;KACvC;IAAC,MAAM;QACN,yDAAyD;QACzD,OAAO,WAAW,CAAC;KACpB;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE;QACtB,OAAO,WAAW,CAAC;KACpB;IAED,IAAI,CAAC,MAAM,CAAC,iBAAiB,GAAG,wBAAwB,CAAC,iBAAiB,CAAC,CAAC;IAE5E,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC;AAlBD,sDAkBC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAwC,CAAC;AACjE,CAAC;AAND,8CAMC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,OAAY;IAC5C,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC5B,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;KAChC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\ntype EIP712Domain = {\n verifyingContract: Hex;\n};\n\ntype SignTypedMessageDataV3V4 = {\n types: Record<string, unknown>;\n domain: EIP712Domain;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * Normalizes the messageData for the eth_signTypedData\n *\n * @param messageData - The messageData to normalize.\n * @returns The normalized messageData.\n */\nexport function normalizeTypedMessage(messageData: string) {\n let data;\n try {\n data = parseTypedMessage(messageData);\n } catch {\n // Ignore normalization errors and pass the message as is\n return messageData;\n }\n\n const { verifyingContract } = data.domain ?? {};\n\n if (!verifyingContract) {\n return messageData;\n }\n\n data.domain.verifyingContract = normalizeContractAddress(verifyingContract);\n\n return JSON.stringify(data);\n}\n\n/**\n * Parses the messageData to obtain the data object for EIP712 normalization\n *\n * @param data - The messageData to parse.\n * @returns The data object for EIP712 normalization.\n */\nexport function parseTypedMessage(data: string) {\n if (typeof data !== 'string') {\n return data;\n }\n\n return JSON.parse(data) as unknown as SignTypedMessageDataV3V4;\n}\n\n/**\n * Normalizes the address to standard hexadecimal format\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\nfunction normalizeContractAddress(address: Hex): Hex {\n if (address.startsWith('0X')) {\n return `0x${address.slice(2)}`;\n }\n return address;\n}\n"]}
1
+ {"version":3,"file":"normalize.cjs","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":";;;AAaA;;;;;GAKG;AACH,SAAgB,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI,CAAC;QACH,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACP,yDAAyD;QACzD,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,iBAAiB,GAAG,wBAAwB,CAAC,iBAAiB,CAAC,CAAC;IAE5E,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC;AAlBD,sDAkBC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAwC,CAAC;AACjE,CAAC;AAND,8CAMC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,OAAY;IAC5C,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IACjC,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\ntype EIP712Domain = {\n verifyingContract: Hex;\n};\n\ntype SignTypedMessageDataV3V4 = {\n types: Record<string, unknown>;\n domain: EIP712Domain;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * Normalizes the messageData for the eth_signTypedData\n *\n * @param messageData - The messageData to normalize.\n * @returns The normalized messageData.\n */\nexport function normalizeTypedMessage(messageData: string) {\n let data;\n try {\n data = parseTypedMessage(messageData);\n } catch {\n // Ignore normalization errors and pass the message as is\n return messageData;\n }\n\n const { verifyingContract } = data.domain ?? {};\n\n if (!verifyingContract) {\n return messageData;\n }\n\n data.domain.verifyingContract = normalizeContractAddress(verifyingContract);\n\n return JSON.stringify(data);\n}\n\n/**\n * Parses the messageData to obtain the data object for EIP712 normalization\n *\n * @param data - The messageData to parse.\n * @returns The data object for EIP712 normalization.\n */\nexport function parseTypedMessage(data: string) {\n if (typeof data !== 'string') {\n return data;\n }\n\n return JSON.parse(data) as unknown as SignTypedMessageDataV3V4;\n}\n\n/**\n * Normalizes the address to standard hexadecimal format\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\nfunction normalizeContractAddress(address: Hex): Hex {\n if (address.startsWith('0X')) {\n return `0x${address.slice(2)}`;\n }\n return address;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"normalize.mjs","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI;QACF,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;KACvC;IAAC,MAAM;QACN,yDAAyD;QACzD,OAAO,WAAW,CAAC;KACpB;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE;QACtB,OAAO,WAAW,CAAC;KACpB;IAED,IAAI,CAAC,MAAM,CAAC,iBAAiB,GAAG,wBAAwB,CAAC,iBAAiB,CAAC,CAAC;IAE5E,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,OAAO,IAAI,CAAC;KACb;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAwC,CAAC;AACjE,CAAC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,OAAY;IAC5C,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC5B,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;KAChC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\ntype EIP712Domain = {\n verifyingContract: Hex;\n};\n\ntype SignTypedMessageDataV3V4 = {\n types: Record<string, unknown>;\n domain: EIP712Domain;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * Normalizes the messageData for the eth_signTypedData\n *\n * @param messageData - The messageData to normalize.\n * @returns The normalized messageData.\n */\nexport function normalizeTypedMessage(messageData: string) {\n let data;\n try {\n data = parseTypedMessage(messageData);\n } catch {\n // Ignore normalization errors and pass the message as is\n return messageData;\n }\n\n const { verifyingContract } = data.domain ?? {};\n\n if (!verifyingContract) {\n return messageData;\n }\n\n data.domain.verifyingContract = normalizeContractAddress(verifyingContract);\n\n return JSON.stringify(data);\n}\n\n/**\n * Parses the messageData to obtain the data object for EIP712 normalization\n *\n * @param data - The messageData to parse.\n * @returns The data object for EIP712 normalization.\n */\nexport function parseTypedMessage(data: string) {\n if (typeof data !== 'string') {\n return data;\n }\n\n return JSON.parse(data) as unknown as SignTypedMessageDataV3V4;\n}\n\n/**\n * Normalizes the address to standard hexadecimal format\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\nfunction normalizeContractAddress(address: Hex): Hex {\n if (address.startsWith('0X')) {\n return `0x${address.slice(2)}`;\n }\n return address;\n}\n"]}
1
+ {"version":3,"file":"normalize.mjs","sourceRoot":"","sources":["../../src/utils/normalize.ts"],"names":[],"mappings":"AAaA;;;;;GAKG;AACH,MAAM,UAAU,qBAAqB,CAAC,WAAmB;IACvD,IAAI,IAAI,CAAC;IACT,IAAI,CAAC;QACH,IAAI,GAAG,iBAAiB,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IAAC,MAAM,CAAC;QACP,yDAAyD;QACzD,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;IAEhD,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,iBAAiB,GAAG,wBAAwB,CAAC,iBAAiB,CAAC,CAAC;IAE5E,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;AAC9B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAwC,CAAC;AACjE,CAAC;AAED;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,OAAY;IAC5C,IAAI,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;IACjC,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\ntype EIP712Domain = {\n verifyingContract: Hex;\n};\n\ntype SignTypedMessageDataV3V4 = {\n types: Record<string, unknown>;\n domain: EIP712Domain;\n primaryType: string;\n message: unknown;\n};\n\n/**\n * Normalizes the messageData for the eth_signTypedData\n *\n * @param messageData - The messageData to normalize.\n * @returns The normalized messageData.\n */\nexport function normalizeTypedMessage(messageData: string) {\n let data;\n try {\n data = parseTypedMessage(messageData);\n } catch {\n // Ignore normalization errors and pass the message as is\n return messageData;\n }\n\n const { verifyingContract } = data.domain ?? {};\n\n if (!verifyingContract) {\n return messageData;\n }\n\n data.domain.verifyingContract = normalizeContractAddress(verifyingContract);\n\n return JSON.stringify(data);\n}\n\n/**\n * Parses the messageData to obtain the data object for EIP712 normalization\n *\n * @param data - The messageData to parse.\n * @returns The data object for EIP712 normalization.\n */\nexport function parseTypedMessage(data: string) {\n if (typeof data !== 'string') {\n return data;\n }\n\n return JSON.parse(data) as unknown as SignTypedMessageDataV3V4;\n}\n\n/**\n * Normalizes the address to standard hexadecimal format\n *\n * @param address - The address to normalize.\n * @returns The normalized address.\n */\nfunction normalizeContractAddress(address: Hex): Hex {\n if (address.startsWith('0X')) {\n return `0x${address.slice(2)}`;\n }\n return address;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,qDAAiE;AAEjE,uDAAiD;AAG1C,KAAK,UAAU,6BAA6B,CACjD,OAAY,EACZ,GAAmB,EACnB,EAAE,WAAW,EAA+D;IAE5E,IACE,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,CAAC,MAAM,GAAG,CAAC;QAClB,gBAAgB,CAAC,OAAO,CAAC,EACzB;QACA,iEAAiE;QACjE,+CAA+C;QAC/C,MAAM,QAAQ,GAAG,MAAM,WAAW,CAAC,GAAG,CAAC,CAAC;QAExC,MAAM,kBAAkB,GAAa,QAAQ,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAC7D,QAAQ,CAAC,WAAW,EAAE,CACvB,CAAC;QAEF,MAAM,iBAAiB,GAAG,OAAO,CAAC,WAAW,EAAS,CAAC;QAEvD,IAAI,kBAAkB,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EAAE;YAClD,OAAO,iBAAiB,CAAC;SAC1B;QAED,MAAM,2BAAc,CAAC,YAAY,EAAE,CAAC;KACrC;IAED,MAAM,sBAAS,CAAC,aAAa,CAAC;QAC5B,OAAO,EAAE,uDAAuD;KACjE,CAAC,CAAC;AACL,CAAC;AA9BD,sEA8BC;AAED,SAAgB,cAAc,CAC5B,KAA2B,EAC3B,MAA0B;IAE1B,MAAM,CAAC,KAAK,CAAC,GAAG,IAAA,sBAAQ,EAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAExC,IAAI,KAAK,EAAE;QACT,MAAM,sBAAS,CAAC,aAAa,CAC3B,qBAAqB,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAC/C,CAAC;KACH;AACH,CAAC;AAXD,wCAWC;AAED,SAAgB,gBAAgB,CAAC,GAAW;IAC1C,0BAA0B;IAC1B,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AACnC,CAAC;AAHD,4CAGC;AAED,SAAS,qBAAqB,CAAC,KAAkB,EAAE,OAAe;IAChE,OAAO,GAAG,OAAO,OAAO,KAAK;SAC1B,QAAQ,EAAE;SACV,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CACxE;SACA,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC","sourcesContent":["import { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex, JsonRpcRequest } from '@metamask/utils';\n\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n req: JsonRpcRequest,\n { getAccounts }: { getAccounts: (req: JsonRpcRequest) => Promise<string[]> },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(req);\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (f) => `${f.path.join(' > ')}${f.path.length ? ' - ' : ''}${f.message}`,\n )\n .join('\\n')}`;\n}\n"]}
1
+ {"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,qDAAiE;AAEjE,uDAAiD;AAG1C,KAAK,UAAU,6BAA6B,CACjD,OAAY,EACZ,GAAmB,EACnB,EAAE,WAAW,EAA+D;IAE5E,IACE,OAAO,OAAO,KAAK,QAAQ;QAC3B,OAAO,CAAC,MAAM,GAAG,CAAC;QAClB,gBAAgB,CAAC,OAAO,CAAC,EACzB,CAAC;QACD,iEAAiE;QACjE,+CAA+C;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E,GAAG,CAAC,CAAC,OAAO,EAAE,CACxE;SACA,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC","sourcesContent":["import { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex, JsonRpcRequest } from '@metamask/utils';\n\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n req: JsonRpcRequest,\n { getAccounts }: { getAccounts: (req: JsonRpcRequest) => Promise<string[]> },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(req);\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (f) => `${f.path.join(' > ')}${f.path.length ? ' - ' : ''}${f.message}`,\n )\n .join('\\n')}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAEjE,OAAO,EAAE,QAAQ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,CACF,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CACxE;SACA,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC","sourcesContent":["import { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex, JsonRpcRequest } from '@metamask/utils';\n\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n req: JsonRpcRequest,\n { getAccounts }: { getAccounts: (req: JsonRpcRequest) => Promise<string[]> },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(req);\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (f) => `${f.path.join(' > ')}${f.path.length ? ' - ' : ''}${f.message}`,\n )\n .join('\\n')}`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IAC1B,OAAO,GAAG,CAAC,MAAM,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,qBAAqB,CAAC,KAAkB,EAAE,OAAe;IAChE,OAAO,GAAG,OAAO,OAAO,KAAK;SAC1B,QAAQ,EAAE;SACV,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,EAAE,CACxE;SACA,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC","sourcesContent":["import { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Struct, StructError } from '@metamask/superstruct';\nimport { validate } from '@metamask/superstruct';\nimport type { Hex, JsonRpcRequest } from '@metamask/utils';\n\nexport async function validateAndNormalizeKeyholder(\n address: Hex,\n req: JsonRpcRequest,\n { getAccounts }: { getAccounts: (req: JsonRpcRequest) => Promise<string[]> },\n): Promise<Hex> {\n if (\n typeof address === 'string' &&\n address.length > 0 &&\n resemblesAddress(address)\n ) {\n // Ensure that an \"unauthorized\" error is thrown if the requester\n // does not have the `eth_accounts` permission.\n const accounts = await getAccounts(req);\n\n const normalizedAccounts: string[] = accounts.map((_address) =>\n _address.toLowerCase(),\n );\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n if (normalizedAccounts.includes(normalizedAddress)) {\n return normalizedAddress;\n }\n\n throw providerErrors.unauthorized();\n }\n\n throw rpcErrors.invalidParams({\n message: `Invalid parameters: must provide an Ethereum address.`,\n });\n}\n\nexport function validateParams<ParamsType>(\n value: unknown | ParamsType,\n struct: Struct<ParamsType>,\n): asserts value is ParamsType {\n const [error] = validate(value, struct);\n\n if (error) {\n throw rpcErrors.invalidParams(\n formatValidationError(error, `Invalid params`),\n );\n }\n}\n\nexport function resemblesAddress(str: string): boolean {\n // hex prefix 2 + 20 bytes\n return str.length === 2 + 20 * 2;\n}\n\nfunction formatValidationError(error: StructError, message: string): string {\n return `${message}\\n\\n${error\n .failures()\n .map(\n (f) => `${f.path.join(' > ')}${f.path.length ? ' - ' : ''}${f.message}`,\n )\n .join('\\n')}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.cjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gEAAkD;AAElD,+DAGmC;AACnC,qDAAiD;AACjD,2CAAoD;AAQpD,6GAGwD;AACxD,yGAGsD;AAEtD,+CAAyD;AACzD,qDAA6E;AAC7E,uDAG4B;AAyE5B,SAAgB,sBAAsB,CAAC,EACrC,WAAW,EACX,qBAAqB,EACrB,0BAA0B,EAC1B,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kCAAkC,EAClC,gCAAgC,GAEX;IACrB,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,IAAA,0CAAwB,EAAC;QAC9B,kBAAkB;QAClB,YAAY,EAAE,IAAA,uCAAqB,EAAC,cAAc,CAAC;QACnD,YAAY,EAAE,IAAA,uCAAqB,EAAC,oBAAoB,CAAC;QAEzD,gBAAgB;QAChB,mBAAmB,EAAE,IAAA,uCAAqB,EAAC,eAAe,CAAC;QAC3D,mBAAmB,EAAE,IAAA,uCAAqB,EAAC,eAAe,CAAC;QAE3D,qBAAqB;QACrB,iBAAiB,EAAE,IAAA,uCAAqB,EAAC,aAAa,CAAC;QACvD,oBAAoB,EAAE,IAAA,uCAAqB,EAAC,eAAe,CAAC;QAC5D,oBAAoB,EAAE,IAAA,uCAAqB,EAAC,eAAe,CAAC;QAC5D,aAAa,EAAE,IAAA,uCAAqB,EAAC,YAAY,CAAC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,CAAC;AAjXD,wDAiXC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,IAAY;IACvC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,IAAA,6BAAiB,EAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;KAChC;IAED,gCAAgC;IAChC,MAAM,QAAQ,GAAG,IAAA,gCAAuB,EAAC,WAAW,CAAC,CAAC;IAEtD,sDAAsD;IACtD,MAAM,mBAAmB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,mBAAmB,EAAE;QACxB,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;KAChC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,IAAY;IAC7C,MAAM,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,EAAE,GAAG,IAAA,6BAAiB,EAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,IAAA,yBAAiB,EAAC,iBAAiB,CAAC,EACrC;QACA,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;KAChC;AACH,CAAC","sourcesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n} from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n Hex,\n} from '@metamask/utils';\n\nimport {\n type ProcessRequestExecutionPermissionsHook,\n walletRequestExecutionPermissions,\n} from './methods/wallet-request-execution-permissions';\nimport {\n type ProcessRevokeExecutionPermissionHook,\n walletRevokeExecutionPermission,\n} from './methods/wallet-revoke-execution-permission';\nimport type { Block } from './types';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n} from './utils/validation';\n\n/*\nexport type TransactionParams = {\n [prop: string]: Json;\n from: string;\n}\n*/\n\n/*\nexport type TransactionParams = JsonRpcParams & {\n from: string;\n}\n*/\n\nexport type TransactionParams = {\n from: string;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (req: JsonRpcRequest) => Promise<string[]>;\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n};\n\nexport function createWalletMiddleware({\n getAccounts,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n}: // }: WalletMiddlewareOptions): JsonRpcMiddleware<string, Block> {\nWalletMiddlewareOptions): JsonRpcMiddleware<any, Block> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware({\n // account lookups\n eth_accounts: createAsyncMiddleware(lookupAccounts),\n eth_coinbase: createAsyncMiddleware(lookupDefaultAccount),\n\n // tx signatures\n eth_sendTransaction: createAsyncMiddleware(sendTransaction),\n eth_signTransaction: createAsyncMiddleware(signTransaction),\n\n // message signatures\n eth_signTypedData: createAsyncMiddleware(signTypedData),\n eth_signTypedData_v3: createAsyncMiddleware(signTypedDataV3),\n eth_signTypedData_v4: createAsyncMiddleware(signTypedDataV4),\n personal_sign: createAsyncMiddleware(personalSign),\n eth_getEncryptionPublicKey: createAsyncMiddleware(encryptionPublicKey),\n eth_decrypt: createAsyncMiddleware(decryptMessage),\n personal_ecRecover: createAsyncMiddleware(personalRecover),\n\n // EIP-7715\n wallet_requestExecutionPermissions: createAsyncMiddleware(\n async (req, res) =>\n walletRequestExecutionPermissions(req, res, {\n processRequestExecutionPermissions,\n }),\n ),\n wallet_revokeExecutionPermission: createAsyncMiddleware(async (req, res) =>\n walletRevokeExecutionPermission(req, res, {\n processRevokeExecutionPermission,\n }),\n ),\n });\n\n //\n // account lookups\n //\n\n async function lookupAccounts(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n res.result = await getAccounts(req);\n }\n\n async function lookupDefaultAccount(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n const accounts = await getAccounts(req);\n res.result = accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n async function sendTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processTransaction(txParams, req);\n }\n\n async function signTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processSignTransaction(txParams, req);\n }\n\n //\n // message signatures\n //\n async function signTypedData(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(params[1], req);\n const version = 'V1';\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n res.result = await processTypedMessage(msgParams, req, version);\n }\n\n async function signTypedDataV3(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n res.result = await processTypedMessageV3(msgParams, req, version);\n }\n\n async function signTypedDataV4(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n res.result = await processTypedMessageV4(msgParams, req, version);\n }\n\n async function personalSign(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n let warning = `The eth_personalSign method requires params ordered `;\n warning += `[message, address]. This was previously handled incorrectly, `;\n warning += `and has been corrected automatically. `;\n warning += `Please switch this param order for smooth behavior in the future.`;\n (res as any).warning = warning;\n\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, req);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n res.result = await processPersonalMessage(msgParams, req);\n }\n\n async function personalRecover(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n res.result = signerAddress;\n }\n\n async function encryptionPublicKey(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n\n res.result = await processEncryptionPublicKey(address, req);\n }\n\n async function decryptMessage(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = req.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(params[1], req);\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n res.result = await processDecryptMessage(msgParams, req);\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param req - The request object.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n req: JsonRpcRequest,\n ): Promise<string> {\n return validateKeyholder(address as Hex, req, { getAccounts });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string) {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string) {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
1
+ {"version":3,"file":"wallet.cjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,gEAAkD;AAElD,+DAGmC;AACnC,qDAAiD;AACjD,2CAAoD;AAQpD,6GAGwD;AACxD,yGAGsD;AAEtD,+CAAyD;AACzD,qDAA6E;AAC7E,uDAG4B;AAyE5B,SAAgB,sBAAsB,CAAC,EACrC,WAAW,EACX,qBAAqB,EACrB,0BAA0B,EAC1B,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kCAAkC,EAClC,gCAAgC,GAEX;IACrB,IAAI,CAAC,WAAW,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AAC;QACzB,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,IAAY;IAC7C,MAAM,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,EAAE,GAAG,IAAA,6BAAiB,EAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,IAAA,yBAAiB,EAAC,iBAAiB,CAAC,EACrC,CAAC;QACD,MAAM,sBAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC","sourcesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n} from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n Hex,\n} from '@metamask/utils';\n\nimport {\n type ProcessRequestExecutionPermissionsHook,\n walletRequestExecutionPermissions,\n} from './methods/wallet-request-execution-permissions';\nimport {\n type ProcessRevokeExecutionPermissionHook,\n walletRevokeExecutionPermission,\n} from './methods/wallet-revoke-execution-permission';\nimport type { Block } from './types';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n} from './utils/validation';\n\n/*\nexport type TransactionParams = {\n [prop: string]: Json;\n from: string;\n}\n*/\n\n/*\nexport type TransactionParams = JsonRpcParams & {\n from: string;\n}\n*/\n\nexport type TransactionParams = {\n from: string;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (req: JsonRpcRequest) => Promise<string[]>;\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n};\n\nexport function createWalletMiddleware({\n getAccounts,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n}: // }: WalletMiddlewareOptions): JsonRpcMiddleware<string, Block> {\nWalletMiddlewareOptions): JsonRpcMiddleware<any, Block> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware({\n // account lookups\n eth_accounts: createAsyncMiddleware(lookupAccounts),\n eth_coinbase: createAsyncMiddleware(lookupDefaultAccount),\n\n // tx signatures\n eth_sendTransaction: createAsyncMiddleware(sendTransaction),\n eth_signTransaction: createAsyncMiddleware(signTransaction),\n\n // message signatures\n eth_signTypedData: createAsyncMiddleware(signTypedData),\n eth_signTypedData_v3: createAsyncMiddleware(signTypedDataV3),\n eth_signTypedData_v4: createAsyncMiddleware(signTypedDataV4),\n personal_sign: createAsyncMiddleware(personalSign),\n eth_getEncryptionPublicKey: createAsyncMiddleware(encryptionPublicKey),\n eth_decrypt: createAsyncMiddleware(decryptMessage),\n personal_ecRecover: createAsyncMiddleware(personalRecover),\n\n // EIP-7715\n wallet_requestExecutionPermissions: createAsyncMiddleware(\n async (req, res) =>\n walletRequestExecutionPermissions(req, res, {\n processRequestExecutionPermissions,\n }),\n ),\n wallet_revokeExecutionPermission: createAsyncMiddleware(async (req, res) =>\n walletRevokeExecutionPermission(req, res, {\n processRevokeExecutionPermission,\n }),\n ),\n });\n\n //\n // account lookups\n //\n\n async function lookupAccounts(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n res.result = await getAccounts(req);\n }\n\n async function lookupDefaultAccount(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n const accounts = await getAccounts(req);\n res.result = accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n async function sendTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processTransaction(txParams, req);\n }\n\n async function signTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processSignTransaction(txParams, req);\n }\n\n //\n // message signatures\n //\n async function signTypedData(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(params[1], req);\n const version = 'V1';\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n res.result = await processTypedMessage(msgParams, req, version);\n }\n\n async function signTypedDataV3(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n res.result = await processTypedMessageV3(msgParams, req, version);\n }\n\n async function signTypedDataV4(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n res.result = await processTypedMessageV4(msgParams, req, version);\n }\n\n async function personalSign(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n let warning = `The eth_personalSign method requires params ordered `;\n warning += `[message, address]. This was previously handled incorrectly, `;\n warning += `and has been corrected automatically. `;\n warning += `Please switch this param order for smooth behavior in the future.`;\n (res as any).warning = warning;\n\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, req);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n res.result = await processPersonalMessage(msgParams, req);\n }\n\n async function personalRecover(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n res.result = signerAddress;\n }\n\n async function encryptionPublicKey(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n\n res.result = await processEncryptionPublicKey(address, req);\n }\n\n async function decryptMessage(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = req.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(params[1], req);\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n res.result = await processDecryptMessage(msgParams, req);\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param req - The request object.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n req: JsonRpcRequest,\n ): Promise<string> {\n return validateKeyholder(address as Hex, req, { getAccounts });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string) {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string) {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"wallet.mjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,+BAA+B;AAElD,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACzB,kCAAkC;AACnC,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,OAAO,EAAE,iBAAiB,EAAE,wBAAwB;AAQpD,OAAO,EAEL,iCAAiC,EAClC,2DAAuD;AACxD,OAAO,EAEL,+BAA+B,EAChC,yDAAqD;AAEtD,OAAO,EAAE,uBAAuB,EAAE,2BAAuB;AACzD,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,8BAA0B;AAC7E,OAAO,EACL,gBAAgB,EAChB,6BAA6B,IAAI,iBAAiB,EACnD,+BAA2B;AAyE5B,MAAM,UAAU,sBAAsB,CAAC,EACrC,WAAW,EACX,qBAAqB,EACrB,0BAA0B,EAC1B,sBAAsB,EACtB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,kCAAkC,EAClC,gCAAgC,GAEX;IACrB,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAED,OAAO,wBAAwB,CAAC;QAC9B,kBAAkB;QAClB,YAAY,EAAE,qB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F,GAAG,CAAC,MAAM,GAAG,MAAM,qBAAqB,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED,EAAE;IACF,UAAU;IACV,EAAE;IAEF;;;;;;;;OAQG;IACH,KAAK,UAAU,6BAA6B,CAC1C,OAAe,EACf,GAAmB;QAEnB,OAAO,iBAAiB,CAAC,OAAc,EAAE,GAAG,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IACjE,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,IAAY;IACvC,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;KAChC;IAED,gCAAgC;IAChC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,WAAW,CAAC,CAAC;IAEtD,sDAAsD;IACtD,MAAM,mBAAmB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,mBAAmB,EAAE;QACxB,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;KAChC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,IAAY;IAC7C,MAAM,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,EACrC;QACA,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;KAChC;AACH,CAAC","sourcesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n} from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n Hex,\n} from '@metamask/utils';\n\nimport {\n type ProcessRequestExecutionPermissionsHook,\n walletRequestExecutionPermissions,\n} from './methods/wallet-request-execution-permissions';\nimport {\n type ProcessRevokeExecutionPermissionHook,\n walletRevokeExecutionPermission,\n} from './methods/wallet-revoke-execution-permission';\nimport type { Block } from './types';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n} from './utils/validation';\n\n/*\nexport type TransactionParams = {\n [prop: string]: Json;\n from: string;\n}\n*/\n\n/*\nexport type TransactionParams = JsonRpcParams & {\n from: string;\n}\n*/\n\nexport type TransactionParams = {\n from: string;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (req: JsonRpcRequest) => Promise<string[]>;\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n};\n\nexport function createWalletMiddleware({\n getAccounts,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n}: // }: WalletMiddlewareOptions): JsonRpcMiddleware<string, Block> {\nWalletMiddlewareOptions): JsonRpcMiddleware<any, Block> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware({\n // account lookups\n eth_accounts: createAsyncMiddleware(lookupAccounts),\n eth_coinbase: createAsyncMiddleware(lookupDefaultAccount),\n\n // tx signatures\n eth_sendTransaction: createAsyncMiddleware(sendTransaction),\n eth_signTransaction: createAsyncMiddleware(signTransaction),\n\n // message signatures\n eth_signTypedData: createAsyncMiddleware(signTypedData),\n eth_signTypedData_v3: createAsyncMiddleware(signTypedDataV3),\n eth_signTypedData_v4: createAsyncMiddleware(signTypedDataV4),\n personal_sign: createAsyncMiddleware(personalSign),\n eth_getEncryptionPublicKey: createAsyncMiddleware(encryptionPublicKey),\n eth_decrypt: createAsyncMiddleware(decryptMessage),\n personal_ecRecover: createAsyncMiddleware(personalRecover),\n\n // EIP-7715\n wallet_requestExecutionPermissions: createAsyncMiddleware(\n async (req, res) =>\n walletRequestExecutionPermissions(req, res, {\n processRequestExecutionPermissions,\n }),\n ),\n wallet_revokeExecutionPermission: createAsyncMiddleware(async (req, res) =>\n walletRevokeExecutionPermission(req, res, {\n processRevokeExecutionPermission,\n }),\n ),\n });\n\n //\n // account lookups\n //\n\n async function lookupAccounts(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n res.result = await getAccounts(req);\n }\n\n async function lookupDefaultAccount(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n const accounts = await getAccounts(req);\n res.result = accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n async function sendTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processTransaction(txParams, req);\n }\n\n async function signTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processSignTransaction(txParams, req);\n }\n\n //\n // message signatures\n //\n async function signTypedData(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(params[1], req);\n const version = 'V1';\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n res.result = await processTypedMessage(msgParams, req, version);\n }\n\n async function signTypedDataV3(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n res.result = await processTypedMessageV3(msgParams, req, version);\n }\n\n async function signTypedDataV4(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n res.result = await processTypedMessageV4(msgParams, req, version);\n }\n\n async function personalSign(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n let warning = `The eth_personalSign method requires params ordered `;\n warning += `[message, address]. This was previously handled incorrectly, `;\n warning += `and has been corrected automatically. `;\n warning += `Please switch this param order for smooth behavior in the future.`;\n (res as any).warning = warning;\n\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, req);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n res.result = await processPersonalMessage(msgParams, req);\n }\n\n async function personalRecover(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n res.result = signerAddress;\n }\n\n async function encryptionPublicKey(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n\n res.result = await processEncryptionPublicKey(address, req);\n }\n\n async function decryptMessage(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = req.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(params[1], req);\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n res.result = await processDecryptMessage(msgParams, req);\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param req - The request object.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n req: JsonRpcRequest,\n ): Promise<string> {\n return validateKeyholder(address as Hex, req, { getAccounts });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string) {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string) {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
1
+ {"version":3,"file":"wallet.mjs","sourceRoot":"","sources":["../src/wallet.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,OAAO,+BAA+B;AAElD,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACzB,kCAAkC;AACnC,OAAO,EAAE,SAAS,EAAE,6BAA6B;AACjD,O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AAW,EAAE,KAAK,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;IAED,gCAAgC;IAChC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,WAAW,CAAC,CAAC;IAEtD,sDAAsD;IACtD,MAAM,mBAAmB,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC5C,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,yBAAyB,CAAC,IAAY;IAC7C,MAAM,EAAE,MAAM,EAAE,EAAE,iBAAiB,EAAE,GAAG,EAAE,EAAE,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvE,sEAAsE;IACtE,iEAAiE;IACjE,IACE,iBAAiB;QAChB,iBAA4B,KAAK,QAAQ;QAC1C,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,EACrC,CAAC;QACD,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC;IACjC,CAAC;AACH,CAAC","sourcesContent":["import * as sigUtil from '@metamask/eth-sig-util';\nimport type { JsonRpcMiddleware } from '@metamask/json-rpc-engine';\nimport {\n createAsyncMiddleware,\n createScaffoldMiddleware,\n} from '@metamask/json-rpc-engine';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { isValidHexAddress } from '@metamask/utils';\nimport type {\n JsonRpcRequest,\n PendingJsonRpcResponse,\n Json,\n Hex,\n} from '@metamask/utils';\n\nimport {\n type ProcessRequestExecutionPermissionsHook,\n walletRequestExecutionPermissions,\n} from './methods/wallet-request-execution-permissions';\nimport {\n type ProcessRevokeExecutionPermissionHook,\n walletRevokeExecutionPermission,\n} from './methods/wallet-revoke-execution-permission';\nimport type { Block } from './types';\nimport { stripArrayTypeIfPresent } from './utils/common';\nimport { normalizeTypedMessage, parseTypedMessage } from './utils/normalize';\nimport {\n resemblesAddress,\n validateAndNormalizeKeyholder as validateKeyholder,\n} from './utils/validation';\n\n/*\nexport type TransactionParams = {\n [prop: string]: Json;\n from: string;\n}\n*/\n\n/*\nexport type TransactionParams = JsonRpcParams & {\n from: string;\n}\n*/\n\nexport type TransactionParams = {\n from: string;\n};\n\nexport type MessageParams = TransactionParams & {\n data: string;\n signatureMethod?: string;\n};\n\nexport type TypedMessageParams = MessageParams & {\n version: string;\n};\n\nexport type TypedMessageV1Params = Omit<TypedMessageParams, 'data'> & {\n data: Record<string, unknown>[];\n};\n\nexport type WalletMiddlewareOptions = {\n getAccounts: (req: JsonRpcRequest) => Promise<string[]>;\n processDecryptMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processEncryptionPublicKey?: (\n address: string,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processPersonalMessage?: (\n msgParams: MessageParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processSignTransaction?: (\n txParams: TransactionParams,\n req: JsonRpcRequest,\n ) => Promise<string>;\n processTypedMessage?: (\n msgParams: TypedMessageV1Params,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV3?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processTypedMessageV4?: (\n msgParams: TypedMessageParams,\n req: JsonRpcRequest,\n version: string,\n ) => Promise<string>;\n processRequestExecutionPermissions?: ProcessRequestExecutionPermissionsHook;\n processRevokeExecutionPermission?: ProcessRevokeExecutionPermissionHook;\n};\n\nexport function createWalletMiddleware({\n getAccounts,\n processDecryptMessage,\n processEncryptionPublicKey,\n processPersonalMessage,\n processTransaction,\n processSignTransaction,\n processTypedMessage,\n processTypedMessageV3,\n processTypedMessageV4,\n processRequestExecutionPermissions,\n processRevokeExecutionPermission,\n}: // }: WalletMiddlewareOptions): JsonRpcMiddleware<string, Block> {\nWalletMiddlewareOptions): JsonRpcMiddleware<any, Block> {\n if (!getAccounts) {\n throw new Error('opts.getAccounts is required');\n }\n\n return createScaffoldMiddleware({\n // account lookups\n eth_accounts: createAsyncMiddleware(lookupAccounts),\n eth_coinbase: createAsyncMiddleware(lookupDefaultAccount),\n\n // tx signatures\n eth_sendTransaction: createAsyncMiddleware(sendTransaction),\n eth_signTransaction: createAsyncMiddleware(signTransaction),\n\n // message signatures\n eth_signTypedData: createAsyncMiddleware(signTypedData),\n eth_signTypedData_v3: createAsyncMiddleware(signTypedDataV3),\n eth_signTypedData_v4: createAsyncMiddleware(signTypedDataV4),\n personal_sign: createAsyncMiddleware(personalSign),\n eth_getEncryptionPublicKey: createAsyncMiddleware(encryptionPublicKey),\n eth_decrypt: createAsyncMiddleware(decryptMessage),\n personal_ecRecover: createAsyncMiddleware(personalRecover),\n\n // EIP-7715\n wallet_requestExecutionPermissions: createAsyncMiddleware(\n async (req, res) =>\n walletRequestExecutionPermissions(req, res, {\n processRequestExecutionPermissions,\n }),\n ),\n wallet_revokeExecutionPermission: createAsyncMiddleware(async (req, res) =>\n walletRevokeExecutionPermission(req, res, {\n processRevokeExecutionPermission,\n }),\n ),\n });\n\n //\n // account lookups\n //\n\n async function lookupAccounts(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n res.result = await getAccounts(req);\n }\n\n async function lookupDefaultAccount(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n const accounts = await getAccounts(req);\n res.result = accounts[0] || null;\n }\n\n //\n // transaction signatures\n //\n\n async function sendTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processTransaction(txParams, req);\n }\n\n async function signTransaction(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processSignTransaction) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params[0] as TransactionParams | undefined;\n const txParams: TransactionParams = {\n ...params,\n from: await validateAndNormalizeKeyholder(params?.from || '', req),\n };\n res.result = await processSignTransaction(txParams, req);\n }\n\n //\n // message signatures\n //\n async function signTypedData(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [\n Record<string, unknown>[],\n string,\n Record<string, string>?,\n ];\n const message = params[0];\n const address = await validateAndNormalizeKeyholder(params[1], req);\n const version = 'V1';\n const extraParams = params[2] || {};\n const msgParams: TypedMessageV1Params = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'eth_signTypedData',\n version,\n };\n\n res.result = await processTypedMessage(msgParams, req, version);\n }\n\n async function signTypedDataV3(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV3) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V3';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v3',\n };\n\n res.result = await processTypedMessageV3(msgParams, req, version);\n }\n\n async function signTypedDataV4(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processTypedMessageV4) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n const message = normalizeTypedMessage(params[1]);\n validatePrimaryType(message);\n validateVerifyingContract(message);\n const version = 'V4';\n const msgParams: TypedMessageParams = {\n data: message,\n from: address,\n version,\n signatureMethod: 'eth_signTypedData_v4',\n };\n\n res.result = await processTypedMessageV4(msgParams, req, version);\n }\n\n async function personalSign(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processPersonalMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string, TransactionParams?];\n\n // process normally\n const firstParam = params[0];\n const secondParam = params[1];\n // non-standard \"extraParams\" to be appended to our \"msgParams\" obj\n const extraParams = params[2] || {};\n\n // We initially incorrectly ordered these parameters.\n // To gracefully respect users who adopted this API early,\n // we are currently gracefully recovering from the wrong param order\n // when it is clearly identifiable.\n //\n // That means when the first param is definitely an address,\n // and the second param is definitely not, but is hex.\n let address: string, message: string;\n if (resemblesAddress(firstParam) && !resemblesAddress(secondParam)) {\n let warning = `The eth_personalSign method requires params ordered `;\n warning += `[message, address]. This was previously handled incorrectly, `;\n warning += `and has been corrected automatically. `;\n warning += `Please switch this param order for smooth behavior in the future.`;\n (res as any).warning = warning;\n\n address = firstParam;\n message = secondParam;\n } else {\n message = firstParam;\n address = secondParam;\n }\n address = await validateAndNormalizeKeyholder(address, req);\n\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: message,\n signatureMethod: 'personal_sign',\n };\n\n res.result = await processPersonalMessage(msgParams, req);\n }\n\n async function personalRecover(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 2)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string, string];\n const message = params[0];\n const signature = params[1];\n const signerAddress = sigUtil.recoverPersonalSignature({\n data: message,\n signature,\n });\n\n res.result = signerAddress;\n }\n\n async function encryptionPublicKey(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processEncryptionPublicKey) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n\n const params = req.params as [string];\n\n const address = await validateAndNormalizeKeyholder(params[0], req);\n\n res.result = await processEncryptionPublicKey(address, req);\n }\n\n async function decryptMessage(\n req: JsonRpcRequest,\n res: PendingJsonRpcResponse,\n ): Promise<void> {\n if (!processDecryptMessage) {\n throw rpcErrors.methodNotSupported();\n }\n if (\n !req?.params ||\n !Array.isArray(req.params) ||\n !(req.params.length >= 1)\n ) {\n throw rpcErrors.invalidInput();\n }\n const params = req.params as [string, string, Record<string, Json>?];\n\n const ciphertext: string = params[0];\n const address: string = await validateAndNormalizeKeyholder(params[1], req);\n const extraParams = params[2] || {};\n const msgParams: MessageParams = {\n ...extraParams,\n from: address,\n data: ciphertext,\n };\n\n res.result = await processDecryptMessage(msgParams, req);\n }\n\n //\n // utility\n //\n\n /**\n * Validates the keyholder address, and returns a normalized (i.e. lowercase)\n * copy of it.\n *\n * @param address - The address to validate and normalize.\n * @param req - The request object.\n * @returns The normalized address, if valid. Otherwise, throws\n * an error\n */\n async function validateAndNormalizeKeyholder(\n address: string,\n req: JsonRpcRequest,\n ): Promise<string> {\n return validateKeyholder(address as Hex, req, { getAccounts });\n }\n}\n\n/**\n * Validates primary of typedSignMessage, to ensure that it's type definition is present in message.\n *\n * @param data - The data passed in typedSign request.\n */\nfunction validatePrimaryType(data: string) {\n const { primaryType, types } = parseTypedMessage(data);\n if (!types) {\n throw rpcErrors.invalidInput();\n }\n\n // Primary type can be an array.\n const baseType = stripArrayTypeIfPresent(primaryType);\n\n // Return if the base type is not defined in the types\n const baseTypeDefinitions = types[baseType];\n if (!baseTypeDefinitions) {\n throw rpcErrors.invalidInput();\n }\n}\n\n/**\n * Validates verifyingContract of typedSignMessage.\n *\n * @param data - The data passed in typedSign request.\n * This function allows the verifyingContract to be either:\n * - A valid hex address\n * - The string \"cosmos\" (as it is hard-coded in some Cosmos ecosystem's EVM adapters)\n * - An empty string\n */\nfunction validateVerifyingContract(data: string) {\n const { domain: { verifyingContract } = {} } = parseTypedMessage(data);\n // Explicit check for cosmos here has been added to address this issue\n // https://github.com/MetaMask/eth-json-rpc-middleware/issues/337\n if (\n verifyingContract &&\n (verifyingContract as string) !== 'cosmos' &&\n !isValidHexAddress(verifyingContract)\n ) {\n throw rpcErrors.invalidInput();\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/eth-json-rpc-middleware",
3
- "version": "21.0.0-preview-ee982ebe",
3
+ "version": "21.0.0-preview-91b0ac79",
4
4
  "description": "Ethereum-related json-rpc-engine middleware",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -44,7 +44,7 @@
44
44
  "lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:dependencies && yarn lint:changelog",
45
45
  "lint:changelog": "auto-changelog validate",
46
46
  "lint:dependencies": "depcheck",
47
- "lint:eslint": "eslint . --cache --ext js,ts",
47
+ "lint:eslint": "eslint . --ext js,ts",
48
48
  "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write && yarn lint:dependencies && yarn lint:changelog",
49
49
  "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
50
50
  "publish:preview": "yarn npm publish --tag preview",
@@ -77,7 +77,7 @@
77
77
  "jest": "^27.5.1",
78
78
  "tsd": "^0.31.2",
79
79
  "typedoc": "^0.24.8",
80
- "typescript": "~5.2.2"
80
+ "typescript": "~5.3.3"
81
81
  },
82
82
  "engines": {
83
83
  "node": "^18.18 || >=20"