@metamask-previews/eth-json-rpc-middleware 21.0.0-preview-468843ab

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.
Files changed (164) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +15 -0
  3. package/README.md +23 -0
  4. package/dist/block-cache.cjs +165 -0
  5. package/dist/block-cache.cjs.map +1 -0
  6. package/dist/block-cache.d.cts +9 -0
  7. package/dist/block-cache.d.cts.map +1 -0
  8. package/dist/block-cache.d.mts +9 -0
  9. package/dist/block-cache.d.mts.map +1 -0
  10. package/dist/block-cache.mjs +161 -0
  11. package/dist/block-cache.mjs.map +1 -0
  12. package/dist/block-ref-rewrite.cjs +33 -0
  13. package/dist/block-ref-rewrite.cjs.map +1 -0
  14. package/dist/block-ref-rewrite.d.cts +9 -0
  15. package/dist/block-ref-rewrite.d.cts.map +1 -0
  16. package/dist/block-ref-rewrite.d.mts +9 -0
  17. package/dist/block-ref-rewrite.d.mts.map +1 -0
  18. package/dist/block-ref-rewrite.mjs +29 -0
  19. package/dist/block-ref-rewrite.mjs.map +1 -0
  20. package/dist/block-ref.cjs +46 -0
  21. package/dist/block-ref.cjs.map +1 -0
  22. package/dist/block-ref.d.cts +11 -0
  23. package/dist/block-ref.d.cts.map +1 -0
  24. package/dist/block-ref.d.mts +11 -0
  25. package/dist/block-ref.d.mts.map +1 -0
  26. package/dist/block-ref.mjs +42 -0
  27. package/dist/block-ref.mjs.map +1 -0
  28. package/dist/block-tracker-inspector.cjs +58 -0
  29. package/dist/block-tracker-inspector.cjs.map +1 -0
  30. package/dist/block-tracker-inspector.d.cts +9 -0
  31. package/dist/block-tracker-inspector.d.cts.map +1 -0
  32. package/dist/block-tracker-inspector.d.mts +9 -0
  33. package/dist/block-tracker-inspector.d.mts.map +1 -0
  34. package/dist/block-tracker-inspector.mjs +54 -0
  35. package/dist/block-tracker-inspector.mjs.map +1 -0
  36. package/dist/fetch.cjs +48 -0
  37. package/dist/fetch.cjs.map +1 -0
  38. package/dist/fetch.d.cts +22 -0
  39. package/dist/fetch.d.cts.map +1 -0
  40. package/dist/fetch.d.mts +22 -0
  41. package/dist/fetch.d.mts.map +1 -0
  42. package/dist/fetch.mjs +44 -0
  43. package/dist/fetch.mjs.map +1 -0
  44. package/dist/index.cjs +28 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.d.cts +12 -0
  47. package/dist/index.d.cts.map +1 -0
  48. package/dist/index.d.mts +12 -0
  49. package/dist/index.d.mts.map +1 -0
  50. package/dist/index.mjs +10 -0
  51. package/dist/index.mjs.map +1 -0
  52. package/dist/inflight-cache.cjs +80 -0
  53. package/dist/inflight-cache.cjs.map +1 -0
  54. package/dist/inflight-cache.d.cts +4 -0
  55. package/dist/inflight-cache.d.cts.map +1 -0
  56. package/dist/inflight-cache.d.mts +4 -0
  57. package/dist/inflight-cache.d.mts.map +1 -0
  58. package/dist/inflight-cache.mjs +76 -0
  59. package/dist/inflight-cache.mjs.map +1 -0
  60. package/dist/logging-utils.cjs +7 -0
  61. package/dist/logging-utils.cjs.map +1 -0
  62. package/dist/logging-utils.d.cts +5 -0
  63. package/dist/logging-utils.d.cts.map +1 -0
  64. package/dist/logging-utils.d.mts +5 -0
  65. package/dist/logging-utils.d.mts.map +1 -0
  66. package/dist/logging-utils.mjs +4 -0
  67. package/dist/logging-utils.mjs.map +1 -0
  68. package/dist/methods/wallet-request-execution-permissions.cjs +41 -0
  69. package/dist/methods/wallet-request-execution-permissions.cjs.map +1 -0
  70. package/dist/methods/wallet-request-execution-permissions.d.cts +131 -0
  71. package/dist/methods/wallet-request-execution-permissions.d.cts.map +1 -0
  72. package/dist/methods/wallet-request-execution-permissions.d.mts +131 -0
  73. package/dist/methods/wallet-request-execution-permissions.d.mts.map +1 -0
  74. package/dist/methods/wallet-request-execution-permissions.mjs +37 -0
  75. package/dist/methods/wallet-request-execution-permissions.mjs.map +1 -0
  76. package/dist/methods/wallet-revoke-execution-permission.cjs +20 -0
  77. package/dist/methods/wallet-revoke-execution-permission.cjs.map +1 -0
  78. package/dist/methods/wallet-revoke-execution-permission.d.cts +13 -0
  79. package/dist/methods/wallet-revoke-execution-permission.d.cts.map +1 -0
  80. package/dist/methods/wallet-revoke-execution-permission.d.mts +13 -0
  81. package/dist/methods/wallet-revoke-execution-permission.d.mts.map +1 -0
  82. package/dist/methods/wallet-revoke-execution-permission.mjs +16 -0
  83. package/dist/methods/wallet-revoke-execution-permission.mjs.map +1 -0
  84. package/dist/providerAsMiddleware.cjs +11 -0
  85. package/dist/providerAsMiddleware.cjs.map +1 -0
  86. package/dist/providerAsMiddleware.d.cts +5 -0
  87. package/dist/providerAsMiddleware.d.cts.map +1 -0
  88. package/dist/providerAsMiddleware.d.mts +5 -0
  89. package/dist/providerAsMiddleware.d.mts.map +1 -0
  90. package/dist/providerAsMiddleware.mjs +7 -0
  91. package/dist/providerAsMiddleware.mjs.map +1 -0
  92. package/dist/retryOnEmpty.cjs +100 -0
  93. package/dist/retryOnEmpty.cjs.map +1 -0
  94. package/dist/retryOnEmpty.d.cts +11 -0
  95. package/dist/retryOnEmpty.d.cts.map +1 -0
  96. package/dist/retryOnEmpty.d.mts +11 -0
  97. package/dist/retryOnEmpty.d.mts.map +1 -0
  98. package/dist/retryOnEmpty.mjs +96 -0
  99. package/dist/retryOnEmpty.mjs.map +1 -0
  100. package/dist/types.cjs +3 -0
  101. package/dist/types.cjs.map +1 -0
  102. package/dist/types.d.cts +25 -0
  103. package/dist/types.d.cts.map +1 -0
  104. package/dist/types.d.mts +25 -0
  105. package/dist/types.d.mts.map +1 -0
  106. package/dist/types.mjs +2 -0
  107. package/dist/types.mjs.map +1 -0
  108. package/dist/utils/cache.cjs +186 -0
  109. package/dist/utils/cache.cjs.map +1 -0
  110. package/dist/utils/cache.d.cts +68 -0
  111. package/dist/utils/cache.d.cts.map +1 -0
  112. package/dist/utils/cache.d.mts +68 -0
  113. package/dist/utils/cache.d.mts.map +1 -0
  114. package/dist/utils/cache.mjs +178 -0
  115. package/dist/utils/cache.mjs.map +1 -0
  116. package/dist/utils/common.cjs +17 -0
  117. package/dist/utils/common.cjs.map +1 -0
  118. package/dist/utils/common.d.cts +8 -0
  119. package/dist/utils/common.d.cts.map +1 -0
  120. package/dist/utils/common.d.mts +8 -0
  121. package/dist/utils/common.d.mts.map +1 -0
  122. package/dist/utils/common.mjs +13 -0
  123. package/dist/utils/common.mjs.map +1 -0
  124. package/dist/utils/error.cjs +12 -0
  125. package/dist/utils/error.cjs.map +1 -0
  126. package/dist/utils/error.d.cts +3 -0
  127. package/dist/utils/error.d.cts.map +1 -0
  128. package/dist/utils/error.d.mts +3 -0
  129. package/dist/utils/error.d.mts.map +1 -0
  130. package/dist/utils/error.mjs +8 -0
  131. package/dist/utils/error.mjs.map +1 -0
  132. package/dist/utils/normalize.cjs +52 -0
  133. package/dist/utils/normalize.cjs.map +1 -0
  134. package/dist/utils/normalize.d.cts +26 -0
  135. package/dist/utils/normalize.d.cts.map +1 -0
  136. package/dist/utils/normalize.d.mts +26 -0
  137. package/dist/utils/normalize.d.mts.map +1 -0
  138. package/dist/utils/normalize.mjs +47 -0
  139. package/dist/utils/normalize.mjs.map +1 -0
  140. package/dist/utils/timeout.cjs +14 -0
  141. package/dist/utils/timeout.cjs.map +1 -0
  142. package/dist/utils/timeout.d.cts +8 -0
  143. package/dist/utils/timeout.d.cts.map +1 -0
  144. package/dist/utils/timeout.d.mts +8 -0
  145. package/dist/utils/timeout.d.mts.map +1 -0
  146. package/dist/utils/timeout.mjs +10 -0
  147. package/dist/utils/timeout.mjs.map +1 -0
  148. package/dist/utils/validation.cjs +43 -0
  149. package/dist/utils/validation.cjs.map +1 -0
  150. package/dist/utils/validation.d.cts +8 -0
  151. package/dist/utils/validation.d.cts.map +1 -0
  152. package/dist/utils/validation.d.mts +8 -0
  153. package/dist/utils/validation.d.mts.map +1 -0
  154. package/dist/utils/validation.mjs +37 -0
  155. package/dist/utils/validation.mjs.map +1 -0
  156. package/dist/wallet.cjs +327 -0
  157. package/dist/wallet.cjs.map +1 -0
  158. package/dist/wallet.d.cts +33 -0
  159. package/dist/wallet.d.cts.map +1 -0
  160. package/dist/wallet.d.mts +33 -0
  161. package/dist/wallet.d.mts.map +1 -0
  162. package/dist/wallet.mjs +300 -0
  163. package/dist/wallet.mjs.map +1 -0
  164. package/package.json +95 -0
@@ -0,0 +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,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,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;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,IAAA,YAAK,EAAC,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;AApDD,4DAoDC","sourcesContent":["import type { PollingBlockTracker } from '@metamask/eth-block-tracker';\nimport type { SafeEventEmitterProvider } 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\ninterface BlockRefMiddlewareOptions {\n blockTracker?: PollingBlockTracker;\n provider?: SafeEventEmitterProvider;\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"]}
@@ -0,0 +1,11 @@
1
+ import type { PollingBlockTracker } from "@metamask/eth-block-tracker";
2
+ import type { SafeEventEmitterProvider } from "@metamask/eth-json-rpc-provider";
3
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
4
+ import type { Json, JsonRpcParams } from "@metamask/utils";
5
+ interface BlockRefMiddlewareOptions {
6
+ blockTracker?: PollingBlockTracker;
7
+ provider?: SafeEventEmitterProvider;
8
+ }
9
+ export declare function createBlockRefMiddleware({ provider, blockTracker, }?: BlockRefMiddlewareOptions): JsonRpcMiddleware<JsonRpcParams, Json>;
10
+ export {};
11
+ //# sourceMappingURL=block-ref.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-ref.d.cts","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oCAAoC;AACvE,OAAO,KAAK,EAAE,wBAAwB,EAAE,wCAAwC;AAChF,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAO3D,UAAU,yBAAyB;IACjC,YAAY,CAAC,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,EAAE,wBAAwB,CAAC;CACrC;AAID,wBAAgB,wBAAwB,CAAC,EACvC,QAAQ,EACR,YAAY,GACb,GAAE,yBAA8B,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAiDzE"}
@@ -0,0 +1,11 @@
1
+ import type { PollingBlockTracker } from "@metamask/eth-block-tracker";
2
+ import type { SafeEventEmitterProvider } from "@metamask/eth-json-rpc-provider";
3
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
4
+ import type { Json, JsonRpcParams } from "@metamask/utils";
5
+ interface BlockRefMiddlewareOptions {
6
+ blockTracker?: PollingBlockTracker;
7
+ provider?: SafeEventEmitterProvider;
8
+ }
9
+ export declare function createBlockRefMiddleware({ provider, blockTracker, }?: BlockRefMiddlewareOptions): JsonRpcMiddleware<JsonRpcParams, Json>;
10
+ export {};
11
+ //# sourceMappingURL=block-ref.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-ref.d.mts","sourceRoot":"","sources":["../src/block-ref.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oCAAoC;AACvE,OAAO,KAAK,EAAE,wBAAwB,EAAE,wCAAwC;AAChF,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAEnE,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,wBAAwB;AAO3D,UAAU,yBAAyB;IACjC,YAAY,CAAC,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,EAAE,wBAAwB,CAAC;CACrC;AAID,wBAAgB,wBAAwB,CAAC,EACvC,QAAQ,EACR,YAAY,GACb,GAAE,yBAA8B,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAiDzE"}
@@ -0,0 +1,42 @@
1
+ import { createAsyncMiddleware } from "@metamask/json-rpc-engine";
2
+ import { klona } from "klona/full";
3
+ import { projectLogger, createModuleLogger } from "./logging-utils.mjs";
4
+ import { blockTagParamIndex } from "./utils/cache.mjs";
5
+ const log = createModuleLogger(projectLogger, 'block-ref');
6
+ export function createBlockRefMiddleware({ provider, blockTracker, } = {}) {
7
+ if (!provider) {
8
+ throw Error('BlockRefMiddleware - mandatory "provider" option is missing.');
9
+ }
10
+ if (!blockTracker) {
11
+ throw Error('BlockRefMiddleware - mandatory "blockTracker" option is missing.');
12
+ }
13
+ return createAsyncMiddleware(async (req, res, next) => {
14
+ const blockRefIndex = blockTagParamIndex(req.method);
15
+ // skip if method does not include blockRef
16
+ if (blockRefIndex === undefined) {
17
+ return next();
18
+ }
19
+ const blockRef = Array.isArray(req.params)
20
+ ? (req.params[blockRefIndex] ?? 'latest')
21
+ : 'latest';
22
+ // skip if not "latest"
23
+ if (blockRef !== 'latest') {
24
+ log('blockRef is not "latest", carrying request forward');
25
+ return next();
26
+ }
27
+ // lookup latest block
28
+ const latestBlockNumber = await blockTracker.getLatestBlock();
29
+ log(`blockRef is "latest", setting param ${blockRefIndex} to latest block ${latestBlockNumber}`);
30
+ // create child request with specific block-ref
31
+ const childRequest = klona(req);
32
+ if (Array.isArray(childRequest.params)) {
33
+ childRequest.params[blockRefIndex] = latestBlockNumber;
34
+ }
35
+ // perform child request
36
+ log('Performing another request %o', childRequest);
37
+ // copy child result onto original response
38
+ res.result = await provider.request(childRequest);
39
+ return undefined;
40
+ });
41
+ }
42
+ //# sourceMappingURL=block-ref.mjs.map
@@ -0,0 +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 { SafeEventEmitterProvider } 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\ninterface BlockRefMiddlewareOptions {\n blockTracker?: PollingBlockTracker;\n provider?: SafeEventEmitterProvider;\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"]}
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createBlockTrackerInspectorMiddleware = void 0;
4
+ const json_rpc_engine_1 = require("@metamask/json-rpc-engine");
5
+ const logging_utils_1 = require("./logging-utils.cjs");
6
+ const log = (0, logging_utils_1.createModuleLogger)(logging_utils_1.projectLogger, 'block-tracker-inspector');
7
+ const futureBlockRefRequests = [
8
+ 'eth_getTransactionByHash',
9
+ 'eth_getTransactionReceipt',
10
+ ];
11
+ /**
12
+ * Determines whether the given object has the given property.
13
+ *
14
+ * @param objectToCheck - The object to check.
15
+ * @param property - The property to look for.
16
+ * @returns Whether the object has the property.
17
+ */
18
+ function hasProperty(objectToCheck, property) {
19
+ return Object.hasOwnProperty.call(objectToCheck, property);
20
+ }
21
+ function getResultBlockNumber(response) {
22
+ const { result } = response;
23
+ if (!result ||
24
+ typeof result !== 'object' ||
25
+ !hasProperty(result, 'blockNumber')) {
26
+ return undefined;
27
+ }
28
+ if (typeof result.blockNumber === 'string') {
29
+ return result.blockNumber;
30
+ }
31
+ return undefined;
32
+ }
33
+ // inspect if response contains a block ref higher than our latest block
34
+ function createBlockTrackerInspectorMiddleware({ blockTracker, }) {
35
+ return (0, json_rpc_engine_1.createAsyncMiddleware)(async (req, res, next) => {
36
+ if (!futureBlockRefRequests.includes(req.method)) {
37
+ return next();
38
+ }
39
+ await next();
40
+ // abort if no result or no block number
41
+ const responseBlockNumber = getResultBlockNumber(res);
42
+ if (!responseBlockNumber) {
43
+ return undefined;
44
+ }
45
+ log('res.result.blockNumber exists, proceeding. res = %o', res);
46
+ // if number is higher, suggest block-tracker check for a new block
47
+ const blockNumber = Number.parseInt(responseBlockNumber, 16);
48
+ // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.
49
+ const currentBlockNumber = Number.parseInt(blockTracker.getCurrentBlock(), 16);
50
+ if (blockNumber > currentBlockNumber) {
51
+ log('blockNumber from response is greater than current block number, refreshing current block number');
52
+ await blockTracker.checkForLatestBlock();
53
+ }
54
+ return undefined;
55
+ });
56
+ }
57
+ exports.createBlockTrackerInspectorMiddleware = createBlockTrackerInspectorMiddleware;
58
+ //# sourceMappingURL=block-tracker-inspector.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-tracker-inspector.cjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":";;;AAEA,+DAAkE;AAOlE,uDAAoE;AAEpE,MAAM,GAAG,GAAG,IAAA,kCAAkB,EAAC,6BAAa,EAAE,yBAAyB,CAAC,CAAC;AACzE,MAAM,sBAAsB,GAAa;IACvC,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAWF;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,aAA4B,EAC5B,QAAkB;IAElB,OAAO,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;AAC7D,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;AAED,wEAAwE;AACxE,SAAgB,qCAAqC,CAAC,EACpD,YAAY,GAC2B;IAIvC,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,wCAAwC;QACxC,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,4FAA4F;QAC5F,MAAM,kBAAkB,GAAW,MAAM,CAAC,QAAQ,CAChD,YAAY,CAAC,eAAe,EAAS,EACrC,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;AAnCD,sFAmCC","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 {\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: string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\ninterface BlockTrackerInspectorMiddlewareOptions {\n blockTracker: PollingBlockTracker;\n}\n\n/**\n * Any type that can be used as the name of an object property.\n */\ntype ValidPropertyType = string | number | symbol;\n\n/**\n * Determines whether the given object has the given property.\n *\n * @param objectToCheck - The object to check.\n * @param property - The property to look for.\n * @returns Whether the object has the property.\n */\nfunction hasProperty<ObjectToCheck, Property extends ValidPropertyType>(\n objectToCheck: ObjectToCheck,\n property: Property,\n): objectToCheck is ObjectToCheck & Record<Property, unknown> {\n return Object.hasOwnProperty.call(objectToCheck, property);\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\n// inspect if response contains a block ref higher than our latest block\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n // abort if no result or no block number\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 // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n const currentBlockNumber: number = Number.parseInt(\n blockTracker.getCurrentBlock() as any,\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"]}
@@ -0,0 +1,9 @@
1
+ import type { PollingBlockTracker } from "@metamask/eth-block-tracker";
2
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
3
+ import type { Json, JsonRpcParams } from "@metamask/utils";
4
+ interface BlockTrackerInspectorMiddlewareOptions {
5
+ blockTracker: PollingBlockTracker;
6
+ }
7
+ export declare function createBlockTrackerInspectorMiddleware({ blockTracker, }: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<JsonRpcParams, Json>;
8
+ export {};
9
+ //# sourceMappingURL=block-tracker-inspector.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-tracker-inspector.d.cts","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oCAAoC;AACvE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAEnE,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EAEd,wBAAwB;AAUzB,UAAU,sCAAsC;IAC9C,YAAY,EAAE,mBAAmB,CAAC;CACnC;AAwCD,wBAAgB,qCAAqC,CAAC,EACpD,YAAY,GACb,EAAE,sCAAsC,GAAG,iBAAiB,CAC3D,aAAa,EACb,IAAI,CACL,CA8BA"}
@@ -0,0 +1,9 @@
1
+ import type { PollingBlockTracker } from "@metamask/eth-block-tracker";
2
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
3
+ import type { Json, JsonRpcParams } from "@metamask/utils";
4
+ interface BlockTrackerInspectorMiddlewareOptions {
5
+ blockTracker: PollingBlockTracker;
6
+ }
7
+ export declare function createBlockTrackerInspectorMiddleware({ blockTracker, }: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<JsonRpcParams, Json>;
8
+ export {};
9
+ //# sourceMappingURL=block-tracker-inspector.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-tracker-inspector.d.mts","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,oCAAoC;AACvE,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAEnE,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EAEd,wBAAwB;AAUzB,UAAU,sCAAsC;IAC9C,YAAY,EAAE,mBAAmB,CAAC;CACnC;AAwCD,wBAAgB,qCAAqC,CAAC,EACpD,YAAY,GACb,EAAE,sCAAsC,GAAG,iBAAiB,CAC3D,aAAa,EACb,IAAI,CACL,CA8BA"}
@@ -0,0 +1,54 @@
1
+ import { createAsyncMiddleware } from "@metamask/json-rpc-engine";
2
+ import { projectLogger, createModuleLogger } from "./logging-utils.mjs";
3
+ const log = createModuleLogger(projectLogger, 'block-tracker-inspector');
4
+ const futureBlockRefRequests = [
5
+ 'eth_getTransactionByHash',
6
+ 'eth_getTransactionReceipt',
7
+ ];
8
+ /**
9
+ * Determines whether the given object has the given property.
10
+ *
11
+ * @param objectToCheck - The object to check.
12
+ * @param property - The property to look for.
13
+ * @returns Whether the object has the property.
14
+ */
15
+ function hasProperty(objectToCheck, property) {
16
+ return Object.hasOwnProperty.call(objectToCheck, property);
17
+ }
18
+ function getResultBlockNumber(response) {
19
+ const { result } = response;
20
+ if (!result ||
21
+ typeof result !== 'object' ||
22
+ !hasProperty(result, 'blockNumber')) {
23
+ return undefined;
24
+ }
25
+ if (typeof result.blockNumber === 'string') {
26
+ return result.blockNumber;
27
+ }
28
+ return undefined;
29
+ }
30
+ // inspect if response contains a block ref higher than our latest block
31
+ export function createBlockTrackerInspectorMiddleware({ blockTracker, }) {
32
+ return createAsyncMiddleware(async (req, res, next) => {
33
+ if (!futureBlockRefRequests.includes(req.method)) {
34
+ return next();
35
+ }
36
+ await next();
37
+ // abort if no result or no block number
38
+ const responseBlockNumber = getResultBlockNumber(res);
39
+ if (!responseBlockNumber) {
40
+ return undefined;
41
+ }
42
+ log('res.result.blockNumber exists, proceeding. res = %o', res);
43
+ // if number is higher, suggest block-tracker check for a new block
44
+ const blockNumber = Number.parseInt(responseBlockNumber, 16);
45
+ // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.
46
+ const currentBlockNumber = Number.parseInt(blockTracker.getCurrentBlock(), 16);
47
+ if (blockNumber > currentBlockNumber) {
48
+ log('blockNumber from response is greater than current block number, refreshing current block number');
49
+ await blockTracker.checkForLatestBlock();
50
+ }
51
+ return undefined;
52
+ });
53
+ }
54
+ //# sourceMappingURL=block-tracker-inspector.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"block-tracker-inspector.mjs","sourceRoot":"","sources":["../src/block-tracker-inspector.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,kCAAkC;AAOlE,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,4BAAwB;AAEpE,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,yBAAyB,CAAC,CAAC;AACzE,MAAM,sBAAsB,GAAa;IACvC,0BAA0B;IAC1B,2BAA2B;CAC5B,CAAC;AAWF;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,aAA4B,EAC5B,QAAkB;IAElB,OAAO,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;AAC7D,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;AAED,wEAAwE;AACxE,MAAM,UAAU,qCAAqC,CAAC,EACpD,YAAY,GAC2B;IAIvC,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,wCAAwC;QACxC,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,4FAA4F;QAC5F,MAAM,kBAAkB,GAAW,MAAM,CAAC,QAAQ,CAChD,YAAY,CAAC,eAAe,EAAS,EACrC,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","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 {\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: string[] = [\n 'eth_getTransactionByHash',\n 'eth_getTransactionReceipt',\n];\n\ninterface BlockTrackerInspectorMiddlewareOptions {\n blockTracker: PollingBlockTracker;\n}\n\n/**\n * Any type that can be used as the name of an object property.\n */\ntype ValidPropertyType = string | number | symbol;\n\n/**\n * Determines whether the given object has the given property.\n *\n * @param objectToCheck - The object to check.\n * @param property - The property to look for.\n * @returns Whether the object has the property.\n */\nfunction hasProperty<ObjectToCheck, Property extends ValidPropertyType>(\n objectToCheck: ObjectToCheck,\n property: Property,\n): objectToCheck is ObjectToCheck & Record<Property, unknown> {\n return Object.hasOwnProperty.call(objectToCheck, property);\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\n// inspect if response contains a block ref higher than our latest block\nexport function createBlockTrackerInspectorMiddleware({\n blockTracker,\n}: BlockTrackerInspectorMiddlewareOptions): JsonRpcMiddleware<\n JsonRpcParams,\n Json\n> {\n return createAsyncMiddleware(async (req, res, next) => {\n if (!futureBlockRefRequests.includes(req.method)) {\n return next();\n }\n await next();\n\n // abort if no result or no block number\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 // Typecast: If getCurrentBlock returns null, currentBlockNumber will be NaN, which is fine.\n const currentBlockNumber: number = Number.parseInt(\n blockTracker.getCurrentBlock() as any,\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"]}
package/dist/fetch.cjs ADDED
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createFetchMiddleware = void 0;
4
+ const json_rpc_engine_1 = require("@metamask/json-rpc-engine");
5
+ const rpc_errors_1 = require("@metamask/rpc-errors");
6
+ /**
7
+ * Creates middleware for sending a JSON-RPC request through the given RPC
8
+ * service.
9
+ *
10
+ * @param args - The arguments to this function.
11
+ * @param args.rpcService - The RPC service to use.
12
+ * @param args.options - Options.
13
+ * @param args.options.originHttpHeaderKey - If provided, the origin field for
14
+ * each JSON-RPC request will be attached to each outgoing fetch request under
15
+ * this header.
16
+ * @returns The fetch middleware.
17
+ */
18
+ function createFetchMiddleware({ rpcService, options = {}, }) {
19
+ return (0, json_rpc_engine_1.createAsyncMiddleware)(async (req, res) => {
20
+ const headers = 'originHttpHeaderKey' in options &&
21
+ options.originHttpHeaderKey !== undefined &&
22
+ req.origin !== undefined
23
+ ? { [options.originHttpHeaderKey]: req.origin }
24
+ : {};
25
+ const jsonRpcResponse = await rpcService.request({
26
+ id: req.id,
27
+ jsonrpc: req.jsonrpc,
28
+ method: req.method,
29
+ params: req.params,
30
+ }, {
31
+ headers,
32
+ });
33
+ // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is
34
+ // strictly a JSON-RPC error response as per
35
+ // <https://www.jsonrpc.org/specification#error_object> to account for
36
+ // Ganache returning error objects with extra properties such as `name`
37
+ if ('error' in jsonRpcResponse) {
38
+ throw rpc_errors_1.rpcErrors.internal({
39
+ data: jsonRpcResponse.error,
40
+ });
41
+ }
42
+ // Discard the `id` and `jsonrpc` fields in the response body
43
+ // (the JSON-RPC engine will fill those in)
44
+ res.result = jsonRpcResponse.result;
45
+ });
46
+ }
47
+ exports.createFetchMiddleware = createFetchMiddleware;
48
+ //# sourceMappingURL=fetch.cjs.map
@@ -0,0 +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"]}
@@ -0,0 +1,22 @@
1
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
2
+ import type { Json, JsonRpcParams } from "@metamask/utils";
3
+ import type { AbstractRpcServiceLike } from "./types.cjs";
4
+ /**
5
+ * Creates middleware for sending a JSON-RPC request through the given RPC
6
+ * service.
7
+ *
8
+ * @param args - The arguments to this function.
9
+ * @param args.rpcService - The RPC service to use.
10
+ * @param args.options - Options.
11
+ * @param args.options.originHttpHeaderKey - If provided, the origin field for
12
+ * each JSON-RPC request will be attached to each outgoing fetch request under
13
+ * this header.
14
+ * @returns The fetch middleware.
15
+ */
16
+ export declare function createFetchMiddleware({ rpcService, options, }: {
17
+ rpcService: AbstractRpcServiceLike;
18
+ options?: {
19
+ originHttpHeaderKey?: string;
20
+ };
21
+ }): JsonRpcMiddleware<JsonRpcParams, Json>;
22
+ //# sourceMappingURL=fetch.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAGnE,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAkB,wBAAwB;AAE3E,OAAO,KAAK,EAAE,sBAAsB,EAAE,oBAAgB;AAWtD;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAY,GACb,EAAE;IACD,UAAU,EAAE,sBAAsB,CAAC;IACnC,OAAO,CAAC,EAAE;QACR,mBAAmB,CAAC,EAAE,MAAM,CAAC;KAC9B,CAAC;CACH,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAqCzC"}
@@ -0,0 +1,22 @@
1
+ import type { JsonRpcMiddleware } from "@metamask/json-rpc-engine";
2
+ import type { Json, JsonRpcParams } from "@metamask/utils";
3
+ import type { AbstractRpcServiceLike } from "./types.mjs";
4
+ /**
5
+ * Creates middleware for sending a JSON-RPC request through the given RPC
6
+ * service.
7
+ *
8
+ * @param args - The arguments to this function.
9
+ * @param args.rpcService - The RPC service to use.
10
+ * @param args.options - Options.
11
+ * @param args.options.originHttpHeaderKey - If provided, the origin field for
12
+ * each JSON-RPC request will be attached to each outgoing fetch request under
13
+ * this header.
14
+ * @returns The fetch middleware.
15
+ */
16
+ export declare function createFetchMiddleware({ rpcService, options, }: {
17
+ rpcService: AbstractRpcServiceLike;
18
+ options?: {
19
+ originHttpHeaderKey?: string;
20
+ };
21
+ }): JsonRpcMiddleware<JsonRpcParams, Json>;
22
+ //# sourceMappingURL=fetch.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.mts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,kCAAkC;AAGnE,OAAO,KAAK,EAAE,IAAI,EAAE,aAAa,EAAkB,wBAAwB;AAE3E,OAAO,KAAK,EAAE,sBAAsB,EAAE,oBAAgB;AAWtD;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,UAAU,EACV,OAAY,GACb,EAAE;IACD,UAAU,EAAE,sBAAsB,CAAC;IACnC,OAAO,CAAC,EAAE;QACR,mBAAmB,CAAC,EAAE,MAAM,CAAC;KAC9B,CAAC;CACH,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAqCzC"}
package/dist/fetch.mjs ADDED
@@ -0,0 +1,44 @@
1
+ import { createAsyncMiddleware } from "@metamask/json-rpc-engine";
2
+ import { rpcErrors } from "@metamask/rpc-errors";
3
+ /**
4
+ * Creates middleware for sending a JSON-RPC request through the given RPC
5
+ * service.
6
+ *
7
+ * @param args - The arguments to this function.
8
+ * @param args.rpcService - The RPC service to use.
9
+ * @param args.options - Options.
10
+ * @param args.options.originHttpHeaderKey - If provided, the origin field for
11
+ * each JSON-RPC request will be attached to each outgoing fetch request under
12
+ * this header.
13
+ * @returns The fetch middleware.
14
+ */
15
+ export function createFetchMiddleware({ rpcService, options = {}, }) {
16
+ return createAsyncMiddleware(async (req, res) => {
17
+ const headers = 'originHttpHeaderKey' in options &&
18
+ options.originHttpHeaderKey !== undefined &&
19
+ req.origin !== undefined
20
+ ? { [options.originHttpHeaderKey]: req.origin }
21
+ : {};
22
+ const jsonRpcResponse = await rpcService.request({
23
+ id: req.id,
24
+ jsonrpc: req.jsonrpc,
25
+ method: req.method,
26
+ params: req.params,
27
+ }, {
28
+ headers,
29
+ });
30
+ // NOTE: We intentionally do not test to see if `jsonRpcResponse.error` is
31
+ // strictly a JSON-RPC error response as per
32
+ // <https://www.jsonrpc.org/specification#error_object> to account for
33
+ // Ganache returning error objects with extra properties such as `name`
34
+ if ('error' in jsonRpcResponse) {
35
+ throw rpcErrors.internal({
36
+ data: jsonRpcResponse.error,
37
+ });
38
+ }
39
+ // Discard the `id` and `jsonrpc` fields in the response body
40
+ // (the JSON-RPC engine will fill those in)
41
+ res.result = jsonRpcResponse.result;
42
+ });
43
+ }
44
+ //# sourceMappingURL=fetch.mjs.map
@@ -0,0 +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"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.createFetchMiddleware = void 0;
18
+ __exportStar(require("./block-cache.cjs"), exports);
19
+ __exportStar(require("./block-ref-rewrite.cjs"), exports);
20
+ __exportStar(require("./block-ref.cjs"), exports);
21
+ __exportStar(require("./block-tracker-inspector.cjs"), exports);
22
+ var fetch_1 = require("./fetch.cjs");
23
+ Object.defineProperty(exports, "createFetchMiddleware", { enumerable: true, get: function () { return fetch_1.createFetchMiddleware; } });
24
+ __exportStar(require("./inflight-cache.cjs"), exports);
25
+ __exportStar(require("./providerAsMiddleware.cjs"), exports);
26
+ __exportStar(require("./retryOnEmpty.cjs"), exports);
27
+ __exportStar(require("./wallet.cjs"), exports);
28
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oDAA8B;AAC9B,0DAAoC;AACpC,kDAA4B;AAC5B,gEAA0C;AAC1C,qCAAgD;AAAvC,8GAAA,qBAAqB,OAAA;AAC9B,uDAAiC;AAWjC,6DAAuC;AACvC,qDAA+B;AAC/B,+CAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport * from './wallet';\n"]}
@@ -0,0 +1,12 @@
1
+ export * from "./block-cache.cjs";
2
+ export * from "./block-ref-rewrite.cjs";
3
+ export * from "./block-ref.cjs";
4
+ export * from "./block-tracker-inspector.cjs";
5
+ export { createFetchMiddleware } from "./fetch.cjs";
6
+ export * from "./inflight-cache.cjs";
7
+ export type { RequestExecutionPermissionsRequestParams, RequestExecutionPermissionsResult, ProcessRequestExecutionPermissionsHook, } from "./methods/wallet-request-execution-permissions.cjs";
8
+ export type { ProcessRevokeExecutionPermissionHook, RevokeExecutionPermissionRequestParams, RevokeExecutionPermissionResult, } from "./methods/wallet-revoke-execution-permission.cjs";
9
+ export * from "./providerAsMiddleware.cjs";
10
+ export * from "./retryOnEmpty.cjs";
11
+ export * from "./wallet.cjs";
12
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB"}
@@ -0,0 +1,12 @@
1
+ export * from "./block-cache.mjs";
2
+ export * from "./block-ref-rewrite.mjs";
3
+ export * from "./block-ref.mjs";
4
+ export * from "./block-tracker-inspector.mjs";
5
+ export { createFetchMiddleware } from "./fetch.mjs";
6
+ export * from "./inflight-cache.mjs";
7
+ export type { RequestExecutionPermissionsRequestParams, RequestExecutionPermissionsResult, ProcessRequestExecutionPermissionsHook, } from "./methods/wallet-request-execution-permissions.mjs";
8
+ export type { ProcessRevokeExecutionPermissionHook, RevokeExecutionPermissionRequestParams, RevokeExecutionPermissionResult, } from "./methods/wallet-revoke-execution-permission.mjs";
9
+ export * from "./providerAsMiddleware.mjs";
10
+ export * from "./retryOnEmpty.mjs";
11
+ export * from "./wallet.mjs";
12
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AACjC,YAAY,EACV,wCAAwC,EACxC,iCAAiC,EACjC,sCAAsC,GACvC,2DAAuD;AACxD,YAAY,EACV,oCAAoC,EACpC,sCAAsC,EACtC,+BAA+B,GAChC,yDAAqD;AACtD,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,10 @@
1
+ export * from "./block-cache.mjs";
2
+ export * from "./block-ref-rewrite.mjs";
3
+ export * from "./block-ref.mjs";
4
+ export * from "./block-tracker-inspector.mjs";
5
+ export { createFetchMiddleware } from "./fetch.mjs";
6
+ export * from "./inflight-cache.mjs";
7
+ export * from "./providerAsMiddleware.mjs";
8
+ export * from "./retryOnEmpty.mjs";
9
+ export * from "./wallet.mjs";
10
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kCAA8B;AAC9B,wCAAoC;AACpC,gCAA4B;AAC5B,8CAA0C;AAC1C,OAAO,EAAE,qBAAqB,EAAE,oBAAgB;AAChD,qCAAiC;AAWjC,2CAAuC;AACvC,mCAA+B;AAC/B,6BAAyB","sourcesContent":["export * from './block-cache';\nexport * from './block-ref-rewrite';\nexport * from './block-ref';\nexport * from './block-tracker-inspector';\nexport { createFetchMiddleware } from './fetch';\nexport * from './inflight-cache';\nexport type {\n RequestExecutionPermissionsRequestParams,\n RequestExecutionPermissionsResult,\n ProcessRequestExecutionPermissionsHook,\n} from './methods/wallet-request-execution-permissions';\nexport type {\n ProcessRevokeExecutionPermissionHook,\n RevokeExecutionPermissionRequestParams,\n RevokeExecutionPermissionResult,\n} from './methods/wallet-revoke-execution-permission';\nexport * from './providerAsMiddleware';\nexport * from './retryOnEmpty';\nexport * from './wallet';\n"]}
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createInflightCacheMiddleware = void 0;
4
+ const json_rpc_engine_1 = require("@metamask/json-rpc-engine");
5
+ const full_1 = require("klona/full");
6
+ const logging_utils_1 = require("./logging-utils.cjs");
7
+ const cache_1 = require("./utils/cache.cjs");
8
+ const log = (0, logging_utils_1.createModuleLogger)(logging_utils_1.projectLogger, 'inflight-cache');
9
+ function createInflightCacheMiddleware() {
10
+ const inflightRequests = {};
11
+ return (0, json_rpc_engine_1.createAsyncMiddleware)(async (req, res, next) => {
12
+ // allow cach to be skipped if so specified
13
+ if (req.skipCache) {
14
+ return next();
15
+ }
16
+ // get cacheId, if cacheable
17
+ const cacheId = (0, cache_1.cacheIdentifierForRequest)(req);
18
+ // if not cacheable, skip
19
+ if (!cacheId) {
20
+ log('Request is not cacheable, proceeding. req = %o', req);
21
+ return next();
22
+ }
23
+ // check for matching requests
24
+ let activeRequestHandlers = inflightRequests[cacheId];
25
+ // if found, wait for the active request to be handled
26
+ if (activeRequestHandlers) {
27
+ // setup the response listener and wait for it to be called
28
+ // it will handle copying the result and request fields
29
+ log('Running %i handler(s) for request %o', activeRequestHandlers.length, req);
30
+ await createActiveRequestHandler(res, activeRequestHandlers);
31
+ return undefined;
32
+ }
33
+ // setup response handler array for subsequent requests
34
+ activeRequestHandlers = [];
35
+ inflightRequests[cacheId] = activeRequestHandlers;
36
+ // allow request to be handled normally
37
+ log('Carrying original request forward %o', req);
38
+ await next();
39
+ // clear inflight requests
40
+ delete inflightRequests[cacheId];
41
+ // schedule activeRequestHandlers to be handled
42
+ log('Running %i collected handler(s) for request %o', activeRequestHandlers.length, req);
43
+ handleActiveRequest(res, activeRequestHandlers);
44
+ // complete
45
+ return undefined;
46
+ });
47
+ async function createActiveRequestHandler(res, activeRequestHandlers) {
48
+ const { resolve, promise } = deferredPromise();
49
+ activeRequestHandlers.push((handledRes) => {
50
+ // append a copy of the result and error to the response
51
+ res.result = (0, full_1.klona)(handledRes.result);
52
+ res.error = (0, full_1.klona)(handledRes.error);
53
+ resolve();
54
+ });
55
+ return promise;
56
+ }
57
+ function handleActiveRequest(res, activeRequestHandlers) {
58
+ // use setTimeout so we can resolve our original request first
59
+ setTimeout(() => {
60
+ activeRequestHandlers.forEach((handler) => {
61
+ try {
62
+ handler(res);
63
+ }
64
+ catch (err) {
65
+ // catch error so all requests are handled correctly
66
+ console.error(err);
67
+ }
68
+ });
69
+ });
70
+ }
71
+ }
72
+ exports.createInflightCacheMiddleware = createInflightCacheMiddleware;
73
+ function deferredPromise() {
74
+ let resolve;
75
+ const promise = new Promise((_resolve) => {
76
+ resolve = _resolve;
77
+ });
78
+ return { resolve, promise };
79
+ }
80
+ //# sourceMappingURL=inflight-cache.cjs.map
@@ -0,0 +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;QAC7D,2CAA2C;QAC3C,IAAI,GAAG,CAAC,SAAS,EAAE;YACjB,OAAO,IAAI,EAAE,CAAC;SACf;QACD,4BAA4B;QAC5B,MAAM,OAAO,GAAkB,IAAA,iCAAyB,EAAC,GAAG,CAAC,CAAC;QAC9D,yBAAyB;QACzB,IAAI,CAAC,OAAO,EAAE;YACZ,GAAG,CAAC,gDAAgD,EAAE,GAAG,CAAC,CAAC;YAC3D,OAAO,IAAI,EAAE,CAAC;SACf;QACD,8BAA8B;QAC9B,IAAI,qBAAqB,GAAsB,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACzE,sDAAsD;QACtD,IAAI,qBAAqB,EAAE;YACzB,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;SAClB;QACD,uDAAuD;QACvD,qBAAqB,GAAG,EAAE,CAAC;QAC3B,gBAAgB,CAAC,OAAO,CAAC,GAAG,qBAAqB,CAAC;QAClD,uCAAuC;QACvC,GAAG,CAAC,sCAAsC,EAAE,GAAG,CAAC,CAAC;QACjD,MAAM,IAAI,EAAE,CAAC;QAEb,0BAA0B;QAC1B,OAAO,gBAAgB,CAAC,OAAO,CAAC,CAAC;QACjC,+CAA+C;QAC/C,GAAG,CACD,gDAAgD,EAChD,qBAAqB,CAAC,MAAM,EAC5B,GAAG,CACJ,CAAC;QACF,mBAAmB,CAAC,GAAG,EAAE,qBAAqB,CAAC,CAAC;QAChD,WAAW;QACX,OAAO,SAAS,CAAC;IACnB,CAAC,CACF,CAAC;IAEF,KAAK,UAAU,0BAA0B,CACvC,GAA2B,EAC3B,qBAAwC;QAExC,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,eAAe,EAAE,CAAC;QAC/C,qBAAqB,CAAC,IAAI,CAAC,CAAC,UAAkC,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;\ninterface 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"]}