@metamask/snaps-execution-environments 6.0.1 → 6.1.0

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 (74) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/webview/bundle.js +4 -4
  6. package/dist/browserify/worker-executor/bundle.js +5 -5
  7. package/dist/browserify/worker-pool/bundle.js +4 -4
  8. package/dist/{chunk-2WJGRNAZ.mjs → chunk-25NO4DV3.mjs} +2 -2
  9. package/dist/{chunk-VZLDGGRV.js → chunk-3WB3F2YZ.js} +15 -14
  10. package/dist/chunk-3WB3F2YZ.js.map +1 -0
  11. package/dist/{chunk-WMFXOR4Z.js → chunk-46LW37FK.js} +1 -2
  12. package/dist/chunk-46LW37FK.js.map +1 -0
  13. package/dist/{chunk-WDXE7PNC.js → chunk-6BIY3C7R.js} +3 -3
  14. package/dist/{chunk-WWDMY3F7.js → chunk-7XGKFXJC.js} +3 -3
  15. package/dist/{chunk-F76EJNOI.mjs → chunk-A2OHIW6W.mjs} +2 -2
  16. package/dist/{chunk-RVEFZW4H.mjs → chunk-AHI4GXXW.mjs} +2 -2
  17. package/dist/{chunk-MPITURZG.js → chunk-D5MFZNSR.js} +3 -3
  18. package/dist/{chunk-RJIOCM6W.mjs → chunk-EAUN7JNP.mjs} +2 -2
  19. package/dist/{chunk-NOS7REGG.mjs → chunk-HL2TTKF3.mjs} +1 -2
  20. package/dist/chunk-HL2TTKF3.mjs.map +1 -0
  21. package/dist/{chunk-LJYFGK2B.js → chunk-HXKBUIYS.js} +8 -8
  22. package/dist/{chunk-NYAH3BJI.mjs → chunk-JZXQOM5D.mjs} +2 -2
  23. package/dist/{chunk-UGQV3NZQ.mjs → chunk-LDKTUN73.mjs} +2 -2
  24. package/dist/{chunk-RYZWYBI2.mjs → chunk-LWOSNHG7.mjs} +4 -3
  25. package/dist/{chunk-RYZWYBI2.mjs.map → chunk-LWOSNHG7.mjs.map} +1 -1
  26. package/dist/{chunk-MD6BQLEH.js → chunk-PNJDTF5G.js} +3 -3
  27. package/dist/{chunk-C3F64ZFC.js → chunk-VQQA5JPU.js} +3 -3
  28. package/dist/{chunk-C2QZZAHQ.js → chunk-VZ5ZAQW5.js} +3 -3
  29. package/dist/{chunk-FSJV5VS7.mjs → chunk-XPCW7TKM.mjs} +2 -2
  30. package/dist/common/BaseSnapExecutor.js +6 -6
  31. package/dist/common/BaseSnapExecutor.mjs +5 -5
  32. package/dist/common/endowments/commonEndowmentFactory.js +4 -4
  33. package/dist/common/endowments/commonEndowmentFactory.mjs +3 -3
  34. package/dist/common/endowments/index.js +5 -5
  35. package/dist/common/endowments/index.mjs +4 -4
  36. package/dist/common/endowments/network.js +3 -3
  37. package/dist/common/endowments/network.mjs +2 -2
  38. package/dist/common/utils.js +2 -2
  39. package/dist/common/utils.mjs +1 -1
  40. package/dist/iframe/IFrameSnapExecutor.js +7 -7
  41. package/dist/iframe/IFrameSnapExecutor.mjs +6 -6
  42. package/dist/iframe/index.js +7 -7
  43. package/dist/iframe/index.mjs +6 -6
  44. package/dist/node-process/ChildProcessSnapExecutor.js +7 -7
  45. package/dist/node-process/ChildProcessSnapExecutor.mjs +6 -6
  46. package/dist/node-process/index.js +7 -7
  47. package/dist/node-process/index.mjs +6 -6
  48. package/dist/node-thread/ThreadSnapExecutor.js +7 -7
  49. package/dist/node-thread/ThreadSnapExecutor.mjs +6 -6
  50. package/dist/node-thread/index.js +7 -7
  51. package/dist/node-thread/index.mjs +6 -6
  52. package/dist/tsconfig.build.tsbuildinfo +1 -1
  53. package/dist/webworker/executor/WebWorkerSnapExecutor.js +7 -7
  54. package/dist/webworker/executor/WebWorkerSnapExecutor.mjs +6 -6
  55. package/dist/webworker/executor/index.js +7 -7
  56. package/dist/webworker/executor/index.mjs +6 -6
  57. package/package.json +4 -4
  58. package/dist/chunk-NOS7REGG.mjs.map +0 -1
  59. package/dist/chunk-VZLDGGRV.js.map +0 -1
  60. package/dist/chunk-WMFXOR4Z.js.map +0 -1
  61. /package/dist/{chunk-2WJGRNAZ.mjs.map → chunk-25NO4DV3.mjs.map} +0 -0
  62. /package/dist/{chunk-WDXE7PNC.js.map → chunk-6BIY3C7R.js.map} +0 -0
  63. /package/dist/{chunk-WWDMY3F7.js.map → chunk-7XGKFXJC.js.map} +0 -0
  64. /package/dist/{chunk-F76EJNOI.mjs.map → chunk-A2OHIW6W.mjs.map} +0 -0
  65. /package/dist/{chunk-RVEFZW4H.mjs.map → chunk-AHI4GXXW.mjs.map} +0 -0
  66. /package/dist/{chunk-MPITURZG.js.map → chunk-D5MFZNSR.js.map} +0 -0
  67. /package/dist/{chunk-RJIOCM6W.mjs.map → chunk-EAUN7JNP.mjs.map} +0 -0
  68. /package/dist/{chunk-LJYFGK2B.js.map → chunk-HXKBUIYS.js.map} +0 -0
  69. /package/dist/{chunk-NYAH3BJI.mjs.map → chunk-JZXQOM5D.mjs.map} +0 -0
  70. /package/dist/{chunk-UGQV3NZQ.mjs.map → chunk-LDKTUN73.mjs.map} +0 -0
  71. /package/dist/{chunk-MD6BQLEH.js.map → chunk-PNJDTF5G.js.map} +0 -0
  72. /package/dist/{chunk-C3F64ZFC.js.map → chunk-VQQA5JPU.js.map} +0 -0
  73. /package/dist/{chunk-C2QZZAHQ.js.map → chunk-VZ5ZAQW5.js.map} +0 -0
  74. /package/dist/{chunk-FSJV5VS7.mjs.map → chunk-XPCW7TKM.mjs.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BaseSnapExecutor
3
- } from "./chunk-RYZWYBI2.mjs";
3
+ } from "./chunk-LWOSNHG7.mjs";
4
4
  import {
5
5
  log
6
6
  } from "./chunk-5DEV3QQU.mjs";
@@ -30,4 +30,4 @@ var ThreadSnapExecutor = class _ThreadSnapExecutor extends BaseSnapExecutor {
30
30
  export {
31
31
  ThreadSnapExecutor
32
32
  };
33
- //# sourceMappingURL=chunk-2WJGRNAZ.mjs.map
33
+ //# sourceMappingURL=chunk-25NO4DV3.mjs.map
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkC2QZZAHQjs = require('./chunk-C2QZZAHQ.js');
3
+ var _chunkVZ5ZAQW5js = require('./chunk-VZ5ZAQW5.js');
4
4
 
5
5
 
6
6
 
@@ -8,7 +8,7 @@ var _chunkC2QZZAHQjs = require('./chunk-C2QZZAHQ.js');
8
8
 
9
9
 
10
10
 
11
- var _chunkWMFXOR4Zjs = require('./chunk-WMFXOR4Z.js');
11
+ var _chunk46LW37FKjs = require('./chunk-46LW37FK.js');
12
12
 
13
13
 
14
14
  var _chunkZ7BOREC4js = require('./chunk-Z7BOREC4.js');
@@ -245,7 +245,7 @@ var BaseSnapExecutor = class {
245
245
  const ethereum = this.createEIP1193Provider(provider);
246
246
  const snapModule = { exports: {} };
247
247
  try {
248
- const { endowments, teardown: endowmentTeardown } = _chunkC2QZZAHQjs.createEndowments.call(void 0, {
248
+ const { endowments, teardown: endowmentTeardown } = _chunkVZ5ZAQW5js.createEndowments.call(void 0, {
249
249
  snap,
250
250
  ethereum,
251
251
  snapId,
@@ -305,6 +305,7 @@ var BaseSnapExecutor = class {
305
305
  }
306
306
  return acc;
307
307
  }, {});
308
+ _utils.assert.call(void 0, Object.keys(data.exports).length > 0, "Snap has no valid exports.");
308
309
  }
309
310
  /**
310
311
  * Instantiates a snap API object (i.e. `globalThis.snap`).
@@ -315,9 +316,9 @@ var BaseSnapExecutor = class {
315
316
  createSnapGlobal(provider) {
316
317
  const originalRequest = provider.request.bind(provider);
317
318
  const request = async (args) => {
318
- const sanitizedArgs = _chunkWMFXOR4Zjs.sanitizeRequestArguments.call(void 0, args);
319
- _chunkWMFXOR4Zjs.assertSnapOutboundRequest.call(void 0, sanitizedArgs);
320
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
319
+ const sanitizedArgs = _chunk46LW37FKjs.sanitizeRequestArguments.call(void 0, args);
320
+ _chunk46LW37FKjs.assertSnapOutboundRequest.call(void 0, sanitizedArgs);
321
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
321
322
  (async () => {
322
323
  await _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _notify, notify_fn).call(this, {
323
324
  method: "OutboundRequest",
@@ -335,7 +336,7 @@ var BaseSnapExecutor = class {
335
336
  this
336
337
  );
337
338
  };
338
- const snapGlobalProxy = _chunkWMFXOR4Zjs.proxyStreamProvider.call(void 0, request);
339
+ const snapGlobalProxy = _chunk46LW37FKjs.proxyStreamProvider.call(void 0, request);
339
340
  return harden(snapGlobalProxy);
340
341
  }
341
342
  /**
@@ -347,9 +348,9 @@ var BaseSnapExecutor = class {
347
348
  createEIP1193Provider(provider) {
348
349
  const originalRequest = provider.request.bind(provider);
349
350
  const request = async (args) => {
350
- const sanitizedArgs = _chunkWMFXOR4Zjs.sanitizeRequestArguments.call(void 0, args);
351
- _chunkWMFXOR4Zjs.assertEthereumOutboundRequest.call(void 0, sanitizedArgs);
352
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
351
+ const sanitizedArgs = _chunk46LW37FKjs.sanitizeRequestArguments.call(void 0, args);
352
+ _chunk46LW37FKjs.assertEthereumOutboundRequest.call(void 0, sanitizedArgs);
353
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
353
354
  (async () => {
354
355
  await _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _notify, notify_fn).call(this, {
355
356
  method: "OutboundRequest",
@@ -367,7 +368,7 @@ var BaseSnapExecutor = class {
367
368
  this
368
369
  );
369
370
  };
370
- const streamProviderProxy = _chunkWMFXOR4Zjs.proxyStreamProvider.call(void 0, request);
371
+ const streamProviderProxy = _chunk46LW37FKjs.proxyStreamProvider.call(void 0, request);
371
372
  return harden(streamProviderProxy);
372
373
  }
373
374
  /**
@@ -434,7 +435,7 @@ write_fn = async function(chunk) {
434
435
  };
435
436
  _notify = new WeakSet();
436
437
  notify_fn = async function(notification) {
437
- if (!_chunkWMFXOR4Zjs.isValidResponse.call(void 0, notification)) {
438
+ if (!_chunk46LW37FKjs.isValidResponse.call(void 0, notification)) {
438
439
  throw _rpcerrors.rpcErrors.internal(
439
440
  "JSON-RPC notifications must be JSON serializable objects smaller than 64 MB."
440
441
  );
@@ -446,7 +447,7 @@ notify_fn = async function(notification) {
446
447
  };
447
448
  _respond = new WeakSet();
448
449
  respond_fn = async function(id, response) {
449
- if (!_chunkWMFXOR4Zjs.isValidResponse.call(void 0, response)) {
450
+ if (!_chunk46LW37FKjs.isValidResponse.call(void 0, response)) {
450
451
  await _chunkEXN2TFDJjs.__privateMethod.call(void 0, this, _write, write_fn).call(this, {
451
452
  error: _rpcerrors.serializeError.call(void 0,
452
453
  _rpcerrors.rpcErrors.internal(
@@ -468,4 +469,4 @@ respond_fn = async function(id, response) {
468
469
 
469
470
 
470
471
  exports.BaseSnapExecutor = BaseSnapExecutor;
471
- //# sourceMappingURL=chunk-VZLDGGRV.js.map
472
+ //# sourceMappingURL=chunk-3WB3F2YZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,+BAA+B;AAExC,SAAS,sBAAsB;AAC/B,SAAS,YAAY,WAAW,sBAAsB;AAEtD,SAAS,oBAAoB;AAM7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,UAAU,UAAU;AAiC7B,IAAM,gBAAgB;AAAA,EACpB,MAAM,WAAW,IAAI;AAAA,EACrB,SAAS;AACX;AAEA,IAAM,iBAAiB,UACpB,SAAe;AAAA,EACd,SAAS;AACX,CA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K,mBAAmB,IAAI,cAAc;AAI1C,aAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,GAAG,WAAW,CAAC;AAAA,IACrD,SAAS,OAAO;AACd,YAAM,IAAI,iBAAiB,KAAK;AAAA,IAClC,UAAE;AACA,WAAK,mBAAmB,OAAO,cAAc;AAE7C,UAAI,KAAK,mBAAmB,SAAS,GAAG;AACtC,aAAK,gBAAgB;AACrB,cAAM,KAAK,aAAa;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;AAzTQ;AAAA,WAAM,eAAC,OAAa;AACxB,SAAO,IAAI,QAAc,CAAC,SAAS,WAAW;AAC5C,SAAK,cAAc,MAAM,OAAO,CAAC,UAAU;AACzC,UAAI,OAAO;AACT,eAAO,KAAK;AACZ;AAAA,MACF;AACA,cAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AACH;AAEM;AAAA,YAAO,eAAC,cAAoD;AAChE,MAAI,CAAC,gBAAgB,YAAY,GAAG;AAClC,UAAM,UAAU;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAEA,QAAM,sBAAK,kBAAL,WAAY;AAAA,IAChB,GAAG;AAAA,IACH,SAAS;AAAA,EACX;AACF;AAEM;AAAA,aAAQ,eAAC,IAAe,UAAmC;AAC/D,MAAI,CAAC,gBAAgB,QAAQ,GAAG;AAG9B,UAAM,sBAAK,kBAAL,WAAY;AAAA,MAChB,OAAO;AAAA,QACL,UAAU;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX;AACA;AAAA,EACF;AAEA,QAAM,sBAAK,kBAAL,WAAY;AAAA,IAChB,GAAG;AAAA,IACH;AAAA,IACA,SAAS;AAAA,EACX;AACF","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/dist/StreamProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { validate, is } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
@@ -57,7 +57,6 @@ var BLOCKED_RPC_METHODS = Object.freeze([
57
57
  "wallet_requestPermissions",
58
58
  "wallet_revokePermissions",
59
59
  // We disallow all of these confirmations for now, since the screens are not ready for Snaps.
60
- "eth_sendRawTransaction",
61
60
  "eth_sendTransaction",
62
61
  "eth_sign",
63
62
  "eth_signTypedData",
@@ -142,4 +141,4 @@ function isValidResponse(response) {
142
141
 
143
142
 
144
143
  exports.withTeardown = withTeardown; exports.proxyStreamProvider = proxyStreamProvider; exports.BLOCKED_RPC_METHODS = BLOCKED_RPC_METHODS; exports.assertSnapOutboundRequest = assertSnapOutboundRequest; exports.assertEthereumOutboundRequest = assertEthereumOutboundRequest; exports.sanitizeRequestArguments = sanitizeRequestArguments; exports.isValidResponse = isValidResponse;
145
- //# sourceMappingURL=chunk-WMFXOR4Z.js.map
144
+ //# sourceMappingURL=chunk-46LW37FK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/utils.ts"],"names":[],"mappings":";;;;;AACA,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,IAAM,yBAAyB;AAY/B,eAAsB,aACpB,iBACA,aACe;AACf,QAAM,aAAa,YAAY;AAC/B,SAAO,IAAI,QAAc,CAAC,SAAS,WAAW;AAC5C,oBACG,KAAK,CAAC,UAAU;AACf,UAAI,YAAY,iBAAiB,YAAY;AAC3C,gBAAQ,KAAK;AAAA,MACf,OAAO;AACL;AAAA,UACE;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC,EACA,MAAM,CAAC,WAAW;AACjB,UAAI,YAAY,iBAAiB,YAAY;AAC3C,eAAO,MAAM;AAAA,MACf,OAAO;AACL;AAAA,UACE;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACL,CAAC;AACH;AASO,SAAS,oBAAoB,SAAkC;AAGpE,QAAM,QAAQ,IAAI;AAAA,IAChB,CAAC;AAAA,IACD;AAAA,MACE,IAAI,SAAiB,MAAuB;AAC1C,eAAO,OAAO,SAAS,YAAY,CAAC,SAAS,EAAE,SAAS,IAAI;AAAA,MAC9D;AAAA,MACA,IAAI,SAAS,MAA4B;AACvC,YAAI,SAAS,WAAW;AACtB,iBAAO;AAAA,QACT;AAEA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAC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GAAG;AACvB,WAAO;AAAA,EACT;AAEA,MAAI;AAEF,UAAM,OAAO,YAAY,QAAQ;AACjC,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,WAAO;AAAA,EACT;AACF","sourcesContent":["import type { StreamProvider, RequestArguments } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n assert,\n assertStruct,\n getJsonSize,\n getSafeJson,\n isObject,\n JsonStruct,\n} from '@metamask/utils';\n\nimport { log } from '../logging';\n\n// 64 MB - we chose this number because it is the size limit for postMessage\n// between the extension and the dapp enforced by Chrome.\nconst MAX_RESPONSE_JSON_SIZE = 64_000_000;\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that only allows access to a `request` function.\n * This is useful for replacing StreamProvider with an attenuated version.\n *\n * @param request - Custom attenuated request function.\n * @returns Proxy that mimics a StreamProvider instance.\n */\nexport function proxyStreamProvider(request: unknown): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n 'wallet_revokePermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n rpcErrors.methodNotSupported,\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n\n/**\n * Check if the input is a valid response.\n *\n * @param response - The response.\n * @returns True if the response is valid, otherwise false.\n */\nexport function isValidResponse(response: Record<string, unknown>) {\n if (!isObject(response)) {\n return false;\n }\n\n try {\n // If the JSON is invalid this will throw and we should return false.\n const size = getJsonSize(response);\n return size < MAX_RESPONSE_JSON_SIZE;\n } catch {\n return false;\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkVZLDGGRVjs = require('./chunk-VZLDGGRV.js');
3
+ var _chunk3WB3F2YZjs = require('./chunk-3WB3F2YZ.js');
4
4
 
5
5
 
6
6
  var _chunkZ7BOREC4js = require('./chunk-Z7BOREC4.js');
@@ -10,7 +10,7 @@ var _objectmultiplex = require('@metamask/object-multiplex'); var _objectmultipl
10
10
  var _postmessagestream = require('@metamask/post-message-stream');
11
11
  var _snapsutils = require('@metamask/snaps-utils');
12
12
  var _readablestream = require('readable-stream');
13
- var IFrameSnapExecutor = class _IFrameSnapExecutor extends _chunkVZLDGGRVjs.BaseSnapExecutor {
13
+ var IFrameSnapExecutor = class _IFrameSnapExecutor extends _chunk3WB3F2YZjs.BaseSnapExecutor {
14
14
  /**
15
15
  * Initialize the IFrameSnapExecutor. This creates a post message stream from
16
16
  * and to the parent window, for two-way communication with the iframe.
@@ -42,4 +42,4 @@ var IFrameSnapExecutor = class _IFrameSnapExecutor extends _chunkVZLDGGRVjs.Base
42
42
 
43
43
 
44
44
  exports.IFrameSnapExecutor = IFrameSnapExecutor;
45
- //# sourceMappingURL=chunk-WDXE7PNC.js.map
45
+ //# sourceMappingURL=chunk-6BIY3C7R.js.map
@@ -6,7 +6,7 @@ var _chunkHKHW6TTXjs = require('./chunk-HKHW6TTX.js');
6
6
  var _chunkMS2LQQYHjs = require('./chunk-MS2LQQYH.js');
7
7
 
8
8
 
9
- var _chunkLJYFGK2Bjs = require('./chunk-LJYFGK2B.js');
9
+ var _chunkHXKBUIYSjs = require('./chunk-HXKBUIYS.js');
10
10
 
11
11
 
12
12
  var _chunkFOEAIF5Ujs = require('./chunk-FOEAIF5U.js');
@@ -57,7 +57,7 @@ var buildCommonEndowments = () => {
57
57
  _chunkHGLRZZ56js.crypto_default,
58
58
  _chunkHKHW6TTXjs.interval_default,
59
59
  _chunkMS2LQQYHjs.math_default,
60
- _chunkLJYFGK2Bjs.network_default,
60
+ _chunkHXKBUIYSjs.network_default,
61
61
  _chunkB3JZNNZDjs.timeout_default,
62
62
  _chunkFOEAIF5Ujs.textDecoder_default,
63
63
  _chunkLO5ORVRCjs.textEncoder_default,
@@ -83,4 +83,4 @@ var commonEndowmentFactory_default = buildCommonEndowments;
83
83
 
84
84
 
85
85
  exports.commonEndowmentFactory_default = commonEndowmentFactory_default;
86
- //# sourceMappingURL=chunk-WWDMY3F7.js.map
86
+ //# sourceMappingURL=chunk-7XGKFXJC.js.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-BCBKEUCG.mjs";
7
7
  import {
8
8
  network_default
9
- } from "./chunk-FSJV5VS7.mjs";
9
+ } from "./chunk-XPCW7TKM.mjs";
10
10
  import {
11
11
  textDecoder_default
12
12
  } from "./chunk-53ZULHPK.mjs";
@@ -83,4 +83,4 @@ var commonEndowmentFactory_default = buildCommonEndowments;
83
83
  export {
84
84
  commonEndowmentFactory_default
85
85
  };
86
- //# sourceMappingURL=chunk-F76EJNOI.mjs.map
86
+ //# sourceMappingURL=chunk-A2OHIW6W.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BaseSnapExecutor
3
- } from "./chunk-RYZWYBI2.mjs";
3
+ } from "./chunk-LWOSNHG7.mjs";
4
4
  import {
5
5
  log
6
6
  } from "./chunk-5DEV3QQU.mjs";
@@ -37,4 +37,4 @@ var WebWorkerSnapExecutor = class _WebWorkerSnapExecutor extends BaseSnapExecuto
37
37
  export {
38
38
  WebWorkerSnapExecutor
39
39
  };
40
- //# sourceMappingURL=chunk-RVEFZW4H.mjs.map
40
+ //# sourceMappingURL=chunk-AHI4GXXW.mjs.map
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkVZLDGGRVjs = require('./chunk-VZLDGGRV.js');
3
+ var _chunk3WB3F2YZjs = require('./chunk-3WB3F2YZ.js');
4
4
 
5
5
 
6
6
  var _chunkZ7BOREC4js = require('./chunk-Z7BOREC4.js');
@@ -10,7 +10,7 @@ var _objectmultiplex = require('@metamask/object-multiplex'); var _objectmultipl
10
10
  var _postmessagestream = require('@metamask/post-message-stream');
11
11
  var _snapsutils = require('@metamask/snaps-utils');
12
12
  var _readablestream = require('readable-stream');
13
- var ChildProcessSnapExecutor = class _ChildProcessSnapExecutor extends _chunkVZLDGGRVjs.BaseSnapExecutor {
13
+ var ChildProcessSnapExecutor = class _ChildProcessSnapExecutor extends _chunk3WB3F2YZjs.BaseSnapExecutor {
14
14
  static initialize() {
15
15
  _chunkZ7BOREC4js.log.call(void 0, "Worker: Connecting to parent.");
16
16
  const parentStream = new (0, _postmessagestream.ProcessMessageStream)();
@@ -30,4 +30,4 @@ var ChildProcessSnapExecutor = class _ChildProcessSnapExecutor extends _chunkVZL
30
30
 
31
31
 
32
32
  exports.ChildProcessSnapExecutor = ChildProcessSnapExecutor;
33
- //# sourceMappingURL=chunk-MPITURZG.js.map
33
+ //# sourceMappingURL=chunk-D5MFZNSR.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  commonEndowmentFactory_default
3
- } from "./chunk-F76EJNOI.mjs";
3
+ } from "./chunk-A2OHIW6W.mjs";
4
4
  import {
5
5
  rootRealmGlobal
6
6
  } from "./chunk-IX5S3V47.mjs";
@@ -64,4 +64,4 @@ function createEndowments({
64
64
  export {
65
65
  createEndowments
66
66
  };
67
- //# sourceMappingURL=chunk-RJIOCM6W.mjs.map
67
+ //# sourceMappingURL=chunk-EAUN7JNP.mjs.map
@@ -57,7 +57,6 @@ var BLOCKED_RPC_METHODS = Object.freeze([
57
57
  "wallet_requestPermissions",
58
58
  "wallet_revokePermissions",
59
59
  // We disallow all of these confirmations for now, since the screens are not ready for Snaps.
60
- "eth_sendRawTransaction",
61
60
  "eth_sendTransaction",
62
61
  "eth_sign",
63
62
  "eth_signTypedData",
@@ -142,4 +141,4 @@ export {
142
141
  sanitizeRequestArguments,
143
142
  isValidResponse
144
143
  };
145
- //# sourceMappingURL=chunk-NOS7REGG.mjs.map
144
+ //# sourceMappingURL=chunk-HL2TTKF3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider, RequestArguments } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport {\n assert,\n assertStruct,\n getJsonSize,\n getSafeJson,\n isObject,\n JsonStruct,\n} from '@metamask/utils';\n\nimport { log } from '../logging';\n\n// 64 MB - we chose this number because it is the size limit for postMessage\n// between the extension and the dapp enforced by Chrome.\nconst MAX_RESPONSE_JSON_SIZE = 64_000_000;\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that only allows access to a `request` function.\n * This is useful for replacing StreamProvider with an attenuated version.\n *\n * @param request - Custom attenuated request function.\n * @returns Proxy that mimics a StreamProvider instance.\n */\nexport function proxyStreamProvider(request: unknown): StreamProvider {\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n 'wallet_revokePermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n rpcErrors.methodNotSupported,\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n\n/**\n * Check if the input is a valid response.\n *\n * @param response - The response.\n * @returns True if the response is valid, otherwise false.\n */\nexport function isValidResponse(response: Record<string, unknown>) {\n if (!isObject(response)) {\n return false;\n }\n\n try {\n // If the JSON is invalid this will throw and we should return false.\n const size = getJsonSize(response);\n return size < MAX_RESPONSE_JSON_SIZE;\n } catch {\n return false;\n }\n}\n"],"mapp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AQ,OAAO;AAAA,IACvD;AAAA,IACA,UAAU;AAAA,EACZ;AACA;AAAA,IACE,CAAC,oBAAoB,SAAS,KAAK,MAAM;AAAA,IACzC,UAAU,eAAe;AAAA,MACvB,MAAM;AAAA,QACJ,QAAQ,KAAK;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;AAOO,SAAS,8BAA8B,MAAwB;AAEpE;AAAA,IACE,CAAC,OAAO,UAAU,WAAW,KAAK,KAAK,QAAQ,OAAO;AAAA,IACtD,UAAU,eAAe;AAAA,MACvB,MAAM;AAAA,QACJ,QAAQ,KAAK;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AACA;AAAA,IACE,CAAC,oBAAoB,SAAS,KAAK,MAAM;AAAA,IACzC,UAAU,eAAe;AAAA,MACvB,MAAM;AAAA,QACJ,QAAQ,KAAK;AAAA,MACf;AAAA,IACF,CAAC;AAAA,EACH;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;AAQO,SAAS,yBAAyB,OAAkC;AAGzE,QAAM,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAC7C,SAAO,YAAY,IAAI;AACzB;AAQO,SAAS,gBAAgB,UAAmC;AACjE,MAAI,CAAC,SAAS,QAAQ,GAAG;AACvB,WAAO;AAAA,EACT;AAEA,MAAI;AAEF,UAAM,OAAO,YAAY,QAAQ;AACjC,WAAO,OAAO;AAAA,EAChB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkWMFXOR4Zjs = require('./chunk-WMFXOR4Z.js');
3
+ var _chunk46LW37FKjs = require('./chunk-46LW37FK.js');
4
4
 
5
5
 
6
6
 
@@ -49,7 +49,7 @@ var _ResponseWrapper = class _ResponseWrapper {
49
49
  return _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _ogResponse).url;
50
50
  }
51
51
  async text() {
52
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
52
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
53
53
  (async () => {
54
54
  await _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _onStart).call(this);
55
55
  try {
@@ -62,7 +62,7 @@ var _ResponseWrapper = class _ResponseWrapper {
62
62
  );
63
63
  }
64
64
  async arrayBuffer() {
65
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
65
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
66
66
  (async () => {
67
67
  await _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _onStart).call(this);
68
68
  try {
@@ -75,7 +75,7 @@ var _ResponseWrapper = class _ResponseWrapper {
75
75
  );
76
76
  }
77
77
  async blob() {
78
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
78
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
79
79
  (async () => {
80
80
  await _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _onStart).call(this);
81
81
  try {
@@ -97,7 +97,7 @@ var _ResponseWrapper = class _ResponseWrapper {
97
97
  );
98
98
  }
99
99
  async formData() {
100
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
100
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
101
101
  (async () => {
102
102
  await _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _onStart).call(this);
103
103
  try {
@@ -110,7 +110,7 @@ var _ResponseWrapper = class _ResponseWrapper {
110
110
  );
111
111
  }
112
112
  async json() {
113
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
113
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
114
114
  (async () => {
115
115
  await _chunkEXN2TFDJjs.__privateGet.call(void 0, this, _onStart).call(this);
116
116
  try {
@@ -170,7 +170,7 @@ var createNetwork = ({ notify } = {}) => {
170
170
  };
171
171
  let res;
172
172
  let openFetchConnection;
173
- return await _chunkWMFXOR4Zjs.withTeardown.call(void 0,
173
+ return await _chunk46LW37FKjs.withTeardown.call(void 0,
174
174
  (async () => {
175
175
  try {
176
176
  await notify({
@@ -259,4 +259,4 @@ var network_default = endowmentModule;
259
259
 
260
260
 
261
261
  exports.network_default = network_default;
262
- //# sourceMappingURL=chunk-LJYFGK2B.js.map
262
+ //# sourceMappingURL=chunk-HXKBUIYS.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BaseSnapExecutor
3
- } from "./chunk-RYZWYBI2.mjs";
3
+ } from "./chunk-LWOSNHG7.mjs";
4
4
  import {
5
5
  log
6
6
  } from "./chunk-5DEV3QQU.mjs";
@@ -30,4 +30,4 @@ var ChildProcessSnapExecutor = class _ChildProcessSnapExecutor extends BaseSnapE
30
30
  export {
31
31
  ChildProcessSnapExecutor
32
32
  };
33
- //# sourceMappingURL=chunk-NYAH3BJI.mjs.map
33
+ //# sourceMappingURL=chunk-JZXQOM5D.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BaseSnapExecutor
3
- } from "./chunk-RYZWYBI2.mjs";
3
+ } from "./chunk-LWOSNHG7.mjs";
4
4
  import {
5
5
  log
6
6
  } from "./chunk-5DEV3QQU.mjs";
@@ -42,4 +42,4 @@ var IFrameSnapExecutor = class _IFrameSnapExecutor extends BaseSnapExecutor {
42
42
  export {
43
43
  IFrameSnapExecutor
44
44
  };
45
- //# sourceMappingURL=chunk-UGQV3NZQ.mjs.map
45
+ //# sourceMappingURL=chunk-LDKTUN73.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createEndowments
3
- } from "./chunk-RJIOCM6W.mjs";
3
+ } from "./chunk-EAUN7JNP.mjs";
4
4
  import {
5
5
  assertEthereumOutboundRequest,
6
6
  assertSnapOutboundRequest,
@@ -8,7 +8,7 @@ import {
8
8
  proxyStreamProvider,
9
9
  sanitizeRequestArguments,
10
10
  withTeardown
11
- } from "./chunk-NOS7REGG.mjs";
11
+ } from "./chunk-HL2TTKF3.mjs";
12
12
  import {
13
13
  log
14
14
  } from "./chunk-5DEV3QQU.mjs";
@@ -305,6 +305,7 @@ var BaseSnapExecutor = class {
305
305
  }
306
306
  return acc;
307
307
  }, {});
308
+ assert(Object.keys(data.exports).length > 0, "Snap has no valid exports.");
308
309
  }
309
310
  /**
310
311
  * Instantiates a snap API object (i.e. `globalThis.snap`).
@@ -468,4 +469,4 @@ respond_fn = async function(id, response) {
468
469
  export {
469
470
  BaseSnapExecutor
470
471
  };
471
- //# sourceMappingURL=chunk-RYZWYBI2.mjs.map
472
+ //# sourceMappingURL=chunk-LWOSNHG7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/dist/StreamProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { validate, is } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,+BAA+B;AAExC,SAAS,sBAAsB;AAC/B,SAAS,YAAY,WAAW,sBAAsB;AAEtD,SAAS,oBAAoB;AAM7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,UAAU,UAAU;AAiC7B,IAAM,gBAAgB;AAAA,EACpB,MAAM,WAAW,IAAI;AAAA,EACrB,SAAS;AACX;AAEA,IAAM,iBAAiB,UACpB,SAAe;AAAA,EACd,SAAS;AACX,CAAC,EACA,UAAU;AAeb,IAAM,gCAAgC;AAAA,EACpC,MAAM;AAAA,IACJ,QAAQ;AAAA,IACR,QAAQ,CAAC;AAAA,EACX;AAAA,EACA,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,QAAQ,CAAC,UAAU,cAAc,YAAY;AAAA,EAC/C;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ,CAAC;AAAA,EACX;AAAA,EACA,SAAS;AAAA,IACP,QAAQ;AAAA,IACR,QAAQ,CAAC,UAAU,WAAW,UAAU,SAAS;AAAA,EACnD;AACF;AA7GA;AAqHO,IAAM,mBAAN,MAAuB;AAAA,EAelB,YAAY,eAAuB,WAAmB;AA8JhE;AAAA;AA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A,EACH,CAAC;AACH;AAEM;AAAA,YAAO,eAAC,cAAoD;AAChE,MAAI,CAAC,gBAAgB,YAAY,GAAG;AAClC,UAAM,UAAU;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAEA,QAAM,sBAAK,kBAAL,WAAY;AAAA,IAChB,GAAG;AAAA,IACH,SAAS;AAAA,EACX;AACF;AAEM;AAAA,aAAQ,eAAC,IAAe,UAAmC;AAC/D,MAAI,CAAC,gBAAgB,QAAQ,GAAG;AAG9B,UAAM,sBAAK,kBAAL,WAAY;AAAA,MAChB,OAAO;AAAA,QACL,UAAU;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAAA,MACA;AAAA,MACA,SAAS;AAAA,IACX;AACA;AAAA,EACF;AAEA,QAAM,sBAAK,kBAAL,WAAY;AAAA,IAChB,GAAG;AAAA,IACH;AAAA,IACA,SAAS;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/common/BaseSnapExecutor.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/dist/StreamProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\nimport { validate, is } from 'superstruct';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,+BAA+B;AAExC,SAAS,sBAAsB;AAC/B,SAAS,YAAY,WAAW,sBAAsB;AAEtD,SAAS,oBAAoB;AAM7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,UAAU,UAAU;AAiC7B,IAAM,gBAAgB;AAAA,EACpB,MAAM,WAAW,IAAI;AAAA,EACrB,SAAS;AACX;AAEA,IAAM,iBAAiB,UACpB,SAAe;AAAA,EACd,SAAS;AACX,CAAC,EACA,UAAU;AAeb,IAAM,gCAAgC;AAAA,EACpC,MAAM;AAAA,IACJ,QAAQ;AAAA,IACR,QAAQ,CAAC;AAAA,EACX;AAAA,EACA,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,QAAQ,CAAC,UAAU,cAAc,YAAY;AAAA,EAC/C;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,IACR,QAAQ,CAAC;AAAA,EACX;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