@metamask/snaps-controllers 1.0.2 → 2.0.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.
- package/CHANGELOG.md +31 -562
- package/dist/cjs/cronjob/CronjobController.js +294 -0
- package/dist/cjs/cronjob/CronjobController.js.map +1 -0
- package/dist/cjs/cronjob/index.js +20 -0
- package/dist/cjs/cronjob/index.js.map +1 -0
- package/dist/cjs/fsm.js +69 -0
- package/dist/cjs/fsm.js.map +1 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/logging.js +15 -0
- package/dist/cjs/logging.js.map +1 -0
- package/dist/cjs/services/AbstractExecutionService.js +390 -0
- package/dist/cjs/services/AbstractExecutionService.js.map +1 -0
- package/dist/cjs/services/ExecutionService.js +7 -0
- package/dist/cjs/services/ExecutionService.js.map +1 -0
- package/dist/cjs/services/ProxyPostMessageStream.js +116 -0
- package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -0
- package/dist/cjs/services/browser.js +32 -0
- package/dist/cjs/services/browser.js.map +1 -0
- package/dist/cjs/services/iframe/IframeExecutionService.js +54 -0
- package/dist/cjs/services/iframe/IframeExecutionService.js.map +1 -0
- package/dist/cjs/services/iframe/index.js +20 -0
- package/dist/cjs/services/iframe/index.js.map +1 -0
- package/dist/cjs/services/index.js +32 -0
- package/dist/cjs/services/index.js.map +1 -0
- package/dist/cjs/services/node/NodeProcessExecutionService.js +30 -0
- package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -0
- package/dist/cjs/services/node/NodeThreadExecutionService.js +30 -0
- package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -0
- package/dist/cjs/services/node/index.js +21 -0
- package/dist/cjs/services/node/index.js.map +1 -0
- package/dist/cjs/services/offscreen/OffscreenExecutionService.js +159 -0
- package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -0
- package/dist/cjs/services/offscreen/index.js +20 -0
- package/dist/cjs/services/offscreen/index.js.map +1 -0
- package/dist/cjs/services/webworker/WebWorkerExecutionService.js +148 -0
- package/dist/cjs/services/webworker/WebWorkerExecutionService.js.map +1 -0
- package/dist/cjs/services/webworker/index.js +20 -0
- package/dist/cjs/services/webworker/index.js.map +1 -0
- package/dist/cjs/snaps/RequestQueue.js +63 -0
- package/dist/cjs/snaps/RequestQueue.js.map +1 -0
- package/dist/cjs/snaps/SnapController.js +1736 -0
- package/dist/cjs/snaps/SnapController.js.map +1 -0
- package/dist/cjs/snaps/Timer.js +117 -0
- package/dist/cjs/snaps/Timer.js.map +1 -0
- package/dist/cjs/snaps/endowments/cronjob.js +100 -0
- package/dist/cjs/snaps/endowments/cronjob.js.map +1 -0
- package/dist/cjs/snaps/endowments/enum.js +24 -0
- package/dist/cjs/snaps/endowments/enum.js.map +1 -0
- package/dist/cjs/snaps/endowments/ethereum-provider.js +43 -0
- package/dist/cjs/snaps/endowments/ethereum-provider.js.map +1 -0
- package/dist/cjs/snaps/endowments/index.js +90 -0
- package/dist/cjs/snaps/endowments/index.js.map +1 -0
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js +37 -0
- package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/cjs/snaps/endowments/long-running.js +38 -0
- package/dist/cjs/snaps/endowments/long-running.js.map +1 -0
- package/dist/cjs/snaps/endowments/name-lookup.js +106 -0
- package/dist/cjs/snaps/endowments/name-lookup.js.map +1 -0
- package/dist/cjs/snaps/endowments/network-access.js +44 -0
- package/dist/cjs/snaps/endowments/network-access.js.map +1 -0
- package/dist/cjs/snaps/endowments/rpc.js +99 -0
- package/dist/cjs/snaps/endowments/rpc.js.map +1 -0
- package/dist/cjs/snaps/endowments/transaction-insight.js +106 -0
- package/dist/cjs/snaps/endowments/transaction-insight.js.map +1 -0
- package/dist/cjs/snaps/endowments/web-assembly.js +42 -0
- package/dist/cjs/snaps/endowments/web-assembly.js.map +1 -0
- package/dist/cjs/snaps/index.js +25 -0
- package/dist/cjs/snaps/index.js.map +1 -0
- package/dist/cjs/snaps/location/http.js +106 -0
- package/dist/cjs/snaps/location/http.js.map +1 -0
- package/dist/cjs/snaps/location/index.js +23 -0
- package/dist/cjs/snaps/location/index.js.map +1 -0
- package/dist/cjs/snaps/location/local.js +93 -0
- package/dist/cjs/snaps/location/local.js.map +1 -0
- package/dist/cjs/snaps/location/location.js +34 -0
- package/dist/cjs/snaps/location/location.js.map +1 -0
- package/dist/cjs/snaps/location/npm.js +293 -0
- package/dist/cjs/snaps/location/npm.js.map +1 -0
- package/dist/cjs/snaps/permissions.js +61 -0
- package/dist/cjs/snaps/permissions.js.map +1 -0
- package/dist/cjs/snaps/registry/index.js +21 -0
- package/dist/cjs/snaps/registry/index.js.map +1 -0
- package/dist/cjs/snaps/registry/json.js +277 -0
- package/dist/cjs/snaps/registry/json.js.map +1 -0
- package/dist/cjs/snaps/registry/registry.js +18 -0
- package/dist/cjs/snaps/registry/registry.js.map +1 -0
- package/dist/cjs/snaps/selectors.js +13 -0
- package/dist/cjs/snaps/selectors.js.map +1 -0
- package/dist/cjs/utils.js +70 -0
- package/dist/cjs/utils.js.map +1 -0
- package/dist/esm/cronjob/CronjobController.js +279 -0
- package/dist/esm/cronjob/CronjobController.js.map +1 -0
- package/dist/esm/cronjob/index.js +3 -0
- package/dist/esm/cronjob/index.js.map +1 -0
- package/dist/esm/fsm.js +70 -0
- package/dist/esm/fsm.js.map +1 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/logging.js +10 -0
- package/dist/esm/logging.js.map +1 -0
- package/dist/esm/services/AbstractExecutionService.js +373 -0
- package/dist/esm/services/AbstractExecutionService.js.map +1 -0
- package/dist/esm/services/ExecutionService.js +4 -0
- package/dist/esm/services/ExecutionService.js.map +1 -0
- package/dist/esm/services/ProxyPostMessageStream.js +109 -0
- package/dist/esm/services/ProxyPostMessageStream.js.map +1 -0
- package/dist/esm/services/browser.js +9 -0
- package/dist/esm/services/browser.js.map +1 -0
- package/dist/esm/services/iframe/IframeExecutionService.js +44 -0
- package/dist/esm/services/iframe/IframeExecutionService.js.map +1 -0
- package/dist/esm/services/iframe/index.js +3 -0
- package/dist/esm/services/iframe/index.js.map +1 -0
- package/dist/esm/services/index.js +9 -0
- package/dist/esm/services/index.js.map +1 -0
- package/dist/esm/services/node/NodeProcessExecutionService.js +20 -0
- package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -0
- package/dist/esm/services/node/NodeThreadExecutionService.js +21 -0
- package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -0
- package/dist/esm/services/node/index.js +4 -0
- package/dist/esm/services/node/index.js.map +1 -0
- package/dist/esm/services/offscreen/OffscreenExecutionService.js +149 -0
- package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -0
- package/dist/esm/services/offscreen/index.js +3 -0
- package/dist/esm/services/offscreen/index.js.map +1 -0
- package/dist/esm/services/webworker/WebWorkerExecutionService.js +130 -0
- package/dist/esm/services/webworker/WebWorkerExecutionService.js.map +1 -0
- package/dist/esm/services/webworker/index.js +3 -0
- package/dist/esm/services/webworker/index.js.map +1 -0
- package/dist/esm/snaps/RequestQueue.js +53 -0
- package/dist/esm/snaps/RequestQueue.js.map +1 -0
- package/dist/esm/snaps/SnapController.js +1715 -0
- package/dist/esm/snaps/SnapController.js.map +1 -0
- package/dist/esm/snaps/Timer.js +107 -0
- package/dist/esm/snaps/Timer.js.map +1 -0
- package/dist/esm/snaps/endowments/cronjob.js +99 -0
- package/dist/esm/snaps/endowments/cronjob.js.map +1 -0
- package/dist/esm/snaps/endowments/enum.js +14 -0
- package/dist/esm/snaps/endowments/enum.js.map +1 -0
- package/dist/esm/snaps/endowments/ethereum-provider.js +33 -0
- package/dist/esm/snaps/endowments/ethereum-provider.js.map +1 -0
- package/dist/esm/snaps/endowments/index.js +47 -0
- package/dist/esm/snaps/endowments/index.js.map +1 -0
- package/dist/esm/snaps/endowments/lifecycle-hooks.js +27 -0
- package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +1 -0
- package/dist/esm/snaps/endowments/long-running.js +28 -0
- package/dist/esm/snaps/endowments/long-running.js.map +1 -0
- package/dist/esm/snaps/endowments/name-lookup.js +98 -0
- package/dist/esm/snaps/endowments/name-lookup.js.map +1 -0
- package/dist/esm/snaps/endowments/network-access.js +34 -0
- package/dist/esm/snaps/endowments/network-access.js.map +1 -0
- package/dist/esm/snaps/endowments/rpc.js +88 -0
- package/dist/esm/snaps/endowments/rpc.js.map +1 -0
- package/dist/esm/snaps/endowments/transaction-insight.js +99 -0
- package/dist/esm/snaps/endowments/transaction-insight.js.map +1 -0
- package/dist/esm/snaps/endowments/web-assembly.js +32 -0
- package/dist/esm/snaps/endowments/web-assembly.js.map +1 -0
- package/dist/esm/snaps/index.js +8 -0
- package/dist/esm/snaps/index.js.map +1 -0
- package/dist/{snaps → esm/snaps}/location/http.js +52 -31
- package/dist/esm/snaps/location/http.js.map +1 -0
- package/dist/esm/snaps/location/index.js +6 -0
- package/dist/esm/snaps/location/index.js.map +1 -0
- package/dist/esm/snaps/location/local.js +83 -0
- package/dist/esm/snaps/location/local.js.map +1 -0
- package/dist/esm/snaps/location/location.js +30 -0
- package/dist/esm/snaps/location/location.js.map +1 -0
- package/dist/{snaps → esm/snaps}/location/npm.js +143 -117
- package/dist/esm/snaps/location/npm.js.map +1 -0
- package/dist/esm/snaps/permissions.js +50 -0
- package/dist/esm/snaps/permissions.js.map +1 -0
- package/dist/esm/snaps/registry/index.js +4 -0
- package/dist/esm/snaps/registry/index.js.map +1 -0
- package/dist/esm/snaps/registry/json.js +267 -0
- package/dist/esm/snaps/registry/json.js.map +1 -0
- package/dist/esm/snaps/registry/registry.js +8 -0
- package/dist/esm/snaps/registry/registry.js.map +1 -0
- package/dist/esm/snaps/selectors.js +3 -0
- package/dist/esm/snaps/selectors.js.map +1 -0
- package/dist/{utils.js → esm/utils.js} +21 -30
- package/dist/esm/utils.js.map +1 -0
- package/dist/{cronjob → types/cronjob}/CronjobController.d.ts +12 -11
- package/dist/{fsm.d.ts → types/fsm.d.ts} +1 -1
- package/dist/{index.d.ts → types/index.d.ts} +0 -1
- package/dist/{services → types/services}/AbstractExecutionService.d.ts +4 -4
- package/dist/{services → types/services}/ExecutionService.d.ts +3 -3
- package/dist/{services/offscreen/OffscreenPostMessageStream.d.ts → types/services/ProxyPostMessageStream.d.ts} +10 -10
- package/dist/{services → types/services}/browser.d.ts +2 -0
- package/dist/{services → types/services}/iframe/IframeExecutionService.d.ts +3 -2
- package/dist/{services → types/services}/index.d.ts +2 -0
- package/dist/{services → types/services}/node/NodeProcessExecutionService.d.ts +4 -3
- package/dist/{services → types/services}/node/NodeThreadExecutionService.d.ts +3 -2
- package/dist/{services → types/services}/offscreen/OffscreenExecutionService.d.ts +4 -3
- package/dist/types/services/offscreen/index.d.ts +1 -0
- package/dist/types/services/webworker/WebWorkerExecutionService.d.ts +45 -0
- package/dist/types/services/webworker/index.d.ts +1 -0
- package/dist/{snaps → types/snaps}/SnapController.d.ts +78 -39
- package/dist/{snaps → types/snaps}/endowments/cronjob.d.ts +5 -3
- package/dist/{snaps → types/snaps}/endowments/enum.d.ts +3 -2
- package/dist/{snaps → types/snaps}/endowments/ethereum-provider.d.ts +2 -1
- package/dist/{snaps → types/snaps}/endowments/index.d.ts +23 -14
- package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +15 -0
- package/dist/{snaps → types/snaps}/endowments/long-running.d.ts +2 -1
- package/dist/types/snaps/endowments/name-lookup.d.ts +38 -0
- package/dist/{snaps → types/snaps}/endowments/network-access.d.ts +2 -1
- package/dist/{snaps → types/snaps}/endowments/rpc.d.ts +5 -3
- package/dist/{snaps → types/snaps}/endowments/transaction-insight.d.ts +3 -2
- package/dist/{snaps → types/snaps}/endowments/web-assembly.d.ts +2 -1
- package/dist/{snaps → types/snaps}/index.d.ts +2 -0
- package/dist/{snaps → types/snaps}/location/http.d.ts +3 -2
- package/dist/{snaps → types/snaps}/location/local.d.ts +3 -3
- package/dist/{snaps → types/snaps}/location/location.d.ts +2 -2
- package/dist/types/snaps/location/npm.d.ts +49 -0
- package/dist/types/snaps/permissions.d.ts +16 -0
- package/dist/{snaps → types/snaps}/registry/json.d.ts +5 -4
- package/dist/{snaps → types/snaps}/registry/registry.d.ts +5 -5
- package/dist/types/snaps/selectors.d.ts +2 -0
- package/dist/{utils.d.ts → types/utils.d.ts} +14 -14
- package/package.json +55 -45
- package/dist/cronjob/CronjobController.js +0 -248
- package/dist/cronjob/CronjobController.js.map +0 -1
- package/dist/cronjob/index.js +0 -18
- package/dist/cronjob/index.js.map +0 -1
- package/dist/fsm.js +0 -75
- package/dist/fsm.js.map +0 -1
- package/dist/index.js +0 -22
- package/dist/index.js.map +0 -1
- package/dist/logging.js +0 -13
- package/dist/logging.js.map +0 -1
- package/dist/multichain/MultiChainController.d.ts +0 -137
- package/dist/multichain/MultiChainController.js +0 -339
- package/dist/multichain/MultiChainController.js.map +0 -1
- package/dist/multichain/index.d.ts +0 -3
- package/dist/multichain/index.js +0 -20
- package/dist/multichain/index.js.map +0 -1
- package/dist/multichain/matching.d.ts +0 -9
- package/dist/multichain/matching.js +0 -57
- package/dist/multichain/matching.js.map +0 -1
- package/dist/multichain/middleware.d.ts +0 -14
- package/dist/multichain/middleware.js +0 -42
- package/dist/multichain/middleware.js.map +0 -1
- package/dist/services/AbstractExecutionService.js +0 -318
- package/dist/services/AbstractExecutionService.js.map +0 -1
- package/dist/services/ExecutionService.js +0 -4
- package/dist/services/ExecutionService.js.map +0 -1
- package/dist/services/browser.js +0 -22
- package/dist/services/browser.js.map +0 -1
- package/dist/services/iframe/IframeExecutionService.js +0 -30
- package/dist/services/iframe/IframeExecutionService.js.map +0 -1
- package/dist/services/iframe/index.js +0 -18
- package/dist/services/iframe/index.js.map +0 -1
- package/dist/services/index.js +0 -22
- package/dist/services/index.js.map +0 -1
- package/dist/services/node/NodeProcessExecutionService.js +0 -18
- package/dist/services/node/NodeProcessExecutionService.js.map +0 -1
- package/dist/services/node/NodeThreadExecutionService.js +0 -19
- package/dist/services/node/NodeThreadExecutionService.js.map +0 -1
- package/dist/services/node/index.js +0 -19
- package/dist/services/node/index.js.map +0 -1
- package/dist/services/offscreen/OffscreenExecutionService.js +0 -100
- package/dist/services/offscreen/OffscreenExecutionService.js.map +0 -1
- package/dist/services/offscreen/OffscreenPostMessageStream.js +0 -66
- package/dist/services/offscreen/OffscreenPostMessageStream.js.map +0 -1
- package/dist/services/offscreen/index.d.ts +0 -2
- package/dist/services/offscreen/index.js +0 -19
- package/dist/services/offscreen/index.js.map +0 -1
- package/dist/snaps/RequestQueue.js +0 -44
- package/dist/snaps/RequestQueue.js.map +0 -1
- package/dist/snaps/SnapController.js +0 -1478
- package/dist/snaps/SnapController.js.map +0 -1
- package/dist/snaps/Timer.js +0 -86
- package/dist/snaps/Timer.js.map +0 -1
- package/dist/snaps/endowments/cronjob.js +0 -105
- package/dist/snaps/endowments/cronjob.js.map +0 -1
- package/dist/snaps/endowments/enum.js +0 -15
- package/dist/snaps/endowments/enum.js.map +0 -1
- package/dist/snaps/endowments/ethereum-provider.js +0 -32
- package/dist/snaps/endowments/ethereum-provider.js.map +0 -1
- package/dist/snaps/endowments/index.js +0 -60
- package/dist/snaps/endowments/index.js.map +0 -1
- package/dist/snaps/endowments/keyring.d.ts +0 -40
- package/dist/snaps/endowments/keyring.js +0 -103
- package/dist/snaps/endowments/keyring.js.map +0 -1
- package/dist/snaps/endowments/long-running.js +0 -29
- package/dist/snaps/endowments/long-running.js.map +0 -1
- package/dist/snaps/endowments/network-access.js +0 -30
- package/dist/snaps/endowments/network-access.js.map +0 -1
- package/dist/snaps/endowments/rpc.js +0 -92
- package/dist/snaps/endowments/rpc.js.map +0 -1
- package/dist/snaps/endowments/transaction-insight.js +0 -106
- package/dist/snaps/endowments/transaction-insight.js.map +0 -1
- package/dist/snaps/endowments/web-assembly.js +0 -31
- package/dist/snaps/endowments/web-assembly.js.map +0 -1
- package/dist/snaps/index.js +0 -21
- package/dist/snaps/index.js.map +0 -1
- package/dist/snaps/location/http.js.map +0 -1
- package/dist/snaps/location/index.js +0 -21
- package/dist/snaps/location/index.js.map +0 -1
- package/dist/snaps/location/local.js +0 -51
- package/dist/snaps/location/local.js.map +0 -1
- package/dist/snaps/location/location.js +0 -34
- package/dist/snaps/location/location.js.map +0 -1
- package/dist/snaps/location/npm.d.ts +0 -28
- package/dist/snaps/location/npm.js.map +0 -1
- package/dist/snaps/registry/index.js +0 -19
- package/dist/snaps/registry/index.js.map +0 -1
- package/dist/snaps/registry/json.js +0 -197
- package/dist/snaps/registry/json.js.map +0 -1
- package/dist/snaps/registry/registry.js +0 -11
- package/dist/snaps/registry/registry.js.map +0 -1
- package/dist/snaps/selectors.d.ts +0 -2
- package/dist/snaps/selectors.js +0 -6
- package/dist/snaps/selectors.js.map +0 -1
- package/dist/utils.js.map +0 -1
- /package/dist/{cronjob → types/cronjob}/index.d.ts +0 -0
- /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
- /package/dist/{services → types/services}/iframe/index.d.ts +0 -0
- /package/dist/{services → types/services}/node/index.d.ts +0 -0
- /package/dist/{snaps → types/snaps}/RequestQueue.d.ts +0 -0
- /package/dist/{snaps → types/snaps}/Timer.d.ts +0 -0
- /package/dist/{snaps → types/snaps}/location/index.d.ts +0 -0
- /package/dist/{snaps → types/snaps}/registry/index.d.ts +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MultiChainController.js","sourceRoot":"","sources":["../../src/multichain/MultiChainController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAGmC;AAOnC,uDAAmE;AACnE,uDAmB+B;AAC/B,2CAAsD;AACtD,mCAAgC;AAEhC,oCAOkB;AAClB,yDAAyE;AACzE,yCAAsD;AAEtD,MAAM,cAAc,GAAG,sBAAsB,CAAC;AAE9C,MAAM,YAAY,GAA8B;IAC9C,QAAQ,EAAE,EAAE;CACb,CAAC;AAyCF,uEAAuE;AACvE,MAAa,oB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AAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YAEjD,GAAG,CAAC,WAAW,CAAC,GAAG,MAAM,CAAC;YAE1B,OAAO,GAAG,CAAC;QACb,CAAC,EAAE,EAAE,CAAC,CAAC;IACT,CAAC;IAED;;;;;;;;;OASG;IACK,KAAK,CAAC,gBAAgB,CAC5B,MAAc,EACd,gBAGC;QAID,oCAAoC;QACpC,MAAM,EAAE,GAAG,IAAA,eAAM,GAAE,CAAC;QACpB,MAAM,gBAAgB,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CACvD,+BAA+B,EAC/B;YACE,MAAM;YACN,EAAE;YACF,IAAI,EAAE,oBAAoB;YAC1B,WAAW,EAAE;gBACX,gBAAgB;aACjB;SACF,EACD,IAAI,CACL,CAA0E,CAAC;QAE5E,oEAAoE;QACpE,8BAA8B;QAC9B,4EAA4E;QAC5E,0EAA0E;QAC1E,4EAA4E;QAE5E,MAAM,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAGhE,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE;YACZ,IAAI,IAAI,KAAK,IAAI,EAAE;gBACjB,GAAG,CAAC,wCAA0B,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;aACnD;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAE,CAAC,wCAA0B,CAAC,EAAE,EAAE,EAAE,CACrC,CAAC;QAEF,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,uCAAuC,EAAE;YACjE,mBAAmB;YACnB,OAAO,EAAE,EAAE,MAAM,EAAE;SACpB,CAAC,CAAC;QAEH,OAAO,gBAAgB,CAAC;IAC1B,CAAC;CACF;AA9dD,oDA8dC","sourcesContent":["import { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseControllerV2 as BaseController,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n GetPermissions,\n GrantPermissions,\n HasPermission,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { WALLET_SNAP_PERMISSION_KEY } from '@metamask/rpc-methods';\nimport {\n SnapKeyring,\n parseAccountId,\n AccountId,\n parseChainId,\n ChainId,\n ConnectArguments,\n isSnapPermitted,\n HandlerType,\n NamespaceId,\n RequestArguments,\n RequestNamespace,\n Session,\n TruncatedSnap,\n SnapId,\n SessionNamespace,\n isAccountIdArray,\n Namespaces,\n logError,\n} from '@metamask/snaps-utils';\nimport { hasProperty, assert } from '@metamask/utils';\nimport { nanoid } from 'nanoid';\n\nimport {\n GetAllSnaps,\n HandleSnapRequest,\n IncrementActiveReferences,\n DecrementActiveReferences,\n SnapEndowments,\n getRunnableSnaps,\n} from '../snaps';\nimport { getKeyringCaveatNamespaces } from '../snaps/endowments/keyring';\nimport { findMatchingKeyringSnaps } from './matching';\n\nconst controllerName = 'MultiChainController';\n\nconst defaultState: MultiChainControllerState = {\n sessions: {},\n};\n\ntype AllowedActions =\n | GetAllSnaps\n | IncrementActiveReferences\n | DecrementActiveReferences\n | HandleSnapRequest\n | GetPermissions\n | HasPermission\n | AddApprovalRequest\n | GrantPermissions;\n\ntype MultiChainControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\ntype SessionData = {\n origin: string;\n requestedNamespaces: Record<NamespaceId, RequestNamespace>;\n providedNamespaces: Record<NamespaceId, RequestNamespace>;\n handlingSnaps: Record<NamespaceId, SnapId>;\n};\n\ntype MultiChainControllerState = {\n sessions: { [origin: string]: SessionData };\n};\n\ntype Notify = (\n origin: string,\n data: { method: string; params?: Record<string, unknown> },\n) => Promise<void>;\n\ntype MultiChainControllerArgs = {\n notify: Notify;\n messenger: MultiChainControllerMessenger;\n};\n\n// TODO(ritave): Support for legacy ethereum operations, not just snaps\nexport class MultiChainController extends BaseController<\n typeof controllerName,\n MultiChainControllerState,\n MultiChainControllerMessenger\n> {\n readonly #notify: Notify;\n\n /**\n * Construct a new {@link MultiChainController} instance.\n *\n * @param args - The arguments to construct the controller with.\n * @param args.messenger - The controller messenger to use.\n * @param args.notify - A function that should handle JSON-RPC notifications.\n */\n constructor({ messenger, notify }: MultiChainControllerArgs) {\n super({\n messenger,\n metadata: {\n sessions: { persist: false, anonymous: false },\n },\n name: controllerName,\n state: defaultState,\n });\n\n this.#notify = notify;\n }\n\n /**\n * Get an open session for the given origin.\n *\n * @param origin - The origin to get the session for.\n * @returns The session, if it exists, or `undefined` otherwise.\n */\n getSession(origin: string): SessionData | undefined {\n return this.state.sessions[origin];\n }\n\n /**\n * Close a session for the given origin.\n *\n * @param origin - The origin to close the session for.\n * @throws If the session does not exist.\n */\n async closeSession(origin: string): Promise<void> {\n const session = this.getSession(origin);\n assert(session, 'No session to close.');\n\n await this.#notify(origin, {\n method: 'multichainHack_metamask_disconnect',\n });\n\n this.update((state) => {\n delete state.sessions[origin];\n });\n\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:decrementActiveReferences',\n snapId,\n ),\n ),\n );\n }\n\n /**\n * Handles a new connection from the given origin. This will create a new\n * session, and close any existing session for the origin.\n *\n * @param origin - The origin to create the session for.\n * @param connection - The connection arguments.\n * @param connection.requiredNamespaces - The namespaces that the origin\n * requires.\n * @returns The session that was created.\n */\n async onConnect(\n origin: string,\n connection: ConnectArguments,\n ): Promise<Session> {\n const existingSession = this.getSession(origin);\n if (existingSession) {\n await this.closeSession(origin);\n }\n\n const snaps = this.messagingSystem.call('SnapController:getAll');\n const filteredSnaps = getRunnableSnaps(snaps);\n\n // Get available namespaces supported by currently installed Snaps.\n const availableNamespaces = Object.fromEntries(\n await Promise.all(\n filteredSnaps.map(async (snap) => [\n snap.id,\n await this.snapToNamespaces(snap),\n ]),\n ),\n );\n\n // The magical matching algorithm specified in SIP-2.\n const namespaceToSnaps = findMatchingKeyringSnaps(\n connection.requiredNamespaces,\n availableNamespaces,\n );\n\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n );\n\n assert(\n permissions !== undefined,\n `${origin} does not have any permissions.`,\n );\n\n // Find namespaces that can be satisfied with existing approved Snaps.\n const approvedNamespacesAndSnaps = Object.entries(namespaceToSnaps).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [namespace, snapIds]) => {\n const approvedSnaps = snapIds.filter((snapId) =>\n isSnapPermitted(permissions, snapId),\n );\n\n if (approvedSnaps.length > 0) {\n acc[namespace] = approvedSnaps;\n }\n return acc;\n }, {});\n\n // If we either don't have a snap to handle a namespace or we have multiple we have conflicts\n const hasConflicts = Object.keys(namespaceToSnaps).some(\n (namespace) =>\n !hasProperty(approvedNamespacesAndSnaps, namespace) ||\n approvedNamespacesAndSnaps[namespace]?.length > 1,\n );\n\n // Use already approved snaps if they satisfy the requested namespaces.\n const filteredNamespacesAndSnaps = hasConflicts\n ? namespaceToSnaps\n : approvedNamespacesAndSnaps;\n\n // Fetch possible accounts from snaps.\n const possibleAccounts = await this.namespacesToAccounts(\n origin,\n filteredNamespacesAndSnaps,\n connection.requiredNamespaces,\n );\n\n // For now we fail here if no namespaces could be matched to a snap.\n // We don't fail if at least one namespace is matched to a snap.\n // TODO: Decide whether this is what we want\n assert(\n Object.values(possibleAccounts).some(\n (possibleAccount) => possibleAccount.length > 0,\n ),\n 'No installed snaps found for any requested namespace.',\n );\n\n // If currently installed Snaps / configuration doesn't solve request, we\n // need to show a prompt. This is handled by `resolveConflicts`.\n const resolvedAccounts = hasConflicts\n ? await this.resolveConflicts(origin, possibleAccounts)\n : Object.fromEntries(\n Object.entries(possibleAccounts).map(\n ([namespace, snapAndAccounts]) => [\n namespace,\n snapAndAccounts[0] ?? null,\n ],\n ),\n );\n\n // Aggregate information about session namespaces.\n const providedNamespaces = Object.entries(\n connection.requiredNamespaces,\n ).reduce<Record<NamespaceId, SessionNamespace>>(\n (acc, [namespaceId, namespace]) => {\n const accounts = resolvedAccounts[namespaceId]?.accounts;\n if (accounts) {\n acc[namespaceId] = {\n accounts,\n chains: namespace.chains,\n events: namespace.events,\n methods: namespace.methods,\n };\n }\n return acc;\n },\n {},\n );\n\n // Collect information about handler Snaps for each namespace.\n const handlingSnaps = Object.entries(resolvedAccounts).reduce<\n Record<NamespaceId, SnapId>\n >((acc, [namespaceId, accountsAndSnap]) => {\n if (accountsAndSnap) {\n acc[namespaceId] = accountsAndSnap.snapId;\n }\n return acc;\n }, {});\n\n const session: SessionData = {\n origin,\n requestedNamespaces: connection.requiredNamespaces,\n providedNamespaces,\n handlingSnaps,\n };\n\n // Makes sure used Snaps aren't killed while they are serving the session.\n await Promise.all(\n Object.values(session.handlingSnaps).map((snapId) =>\n this.messagingSystem.call(\n 'SnapController:incrementActiveReferences',\n snapId,\n ),\n ),\n );\n\n this.update((state) => {\n state.sessions[origin] = session;\n });\n\n return { namespaces: providedNamespaces };\n }\n\n /**\n * Handle an incoming multichain request from the given origin. This will\n * forward the request to the appropriate Snap, and return the response.\n *\n * @param origin - The origin to handle the request for.\n * @param data - The request data.\n * @param data.chainId - The chain ID for the request.\n * @param data.request - The request arguments, i.e., the method and params.\n * @returns The response from the Snap.\n * @throws If the session does not exist, or the session does not provide the\n * requested namespace.\n */\n async onRequest(\n origin: string,\n data: { chainId: ChainId; request: RequestArguments },\n ): Promise<unknown> {\n const session = this.getSession(origin);\n assert(session, `Session for \"${origin}\" doesn't exist.`);\n\n const { namespace } = parseChainId(data.chainId);\n const sessionNamespace = session.providedNamespaces[namespace];\n assert(\n session.providedNamespaces[namespace]?.chains.includes(data.chainId),\n `Session for \"${origin}\" is not connected to \"${data.chainId}\" chain.`,\n );\n\n const { method } = data.request;\n assert(\n sessionNamespace?.methods?.includes(method),\n `Session for \"${origin}\" does not support ${method}`,\n );\n\n const snapId = session.handlingSnaps[namespace];\n assert(snapId !== undefined);\n\n // TODO: Get permission for origin connecting to snap, or get user approval.\n // In the future this is where we should prompt for this permission.\n // In this iteration, we will grant this permission in `onConnect`.\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n origin,\n );\n\n assert(\n permissions !== undefined,\n `${origin} does not have any permissions.`,\n );\n\n assert(\n isSnapPermitted(permissions, snapId),\n `${origin} does not have permission to communicate with ${snapId}.`,\n );\n\n return this.snapRequest({\n snapId,\n origin,\n method: 'handleRequest',\n args: data,\n });\n }\n\n /**\n * Send a request to the given Snap. This calls the given method with the\n * given arguments on the keyring class in the given Snap.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.origin - The origin of the request.\n * @param options.method - The request method.\n * @param options.args - The request params.\n * @returns The response from the Snap.\n */\n private async snapRequest({\n snapId,\n origin,\n method,\n args,\n }: {\n snapId: SnapId;\n origin: string;\n method: keyof SnapKeyring;\n args?: unknown;\n }) {\n return this.messagingSystem.call('SnapController:handleRequest', {\n snapId,\n origin,\n handler: HandlerType.SnapKeyring,\n request: { method, params: args ? [args] : [] },\n });\n }\n\n /**\n * Get the accounts exposed by the Snap's keyring.\n *\n * This also verifies that the accounts returned by the snap are valid CAIP-10\n * account IDs.\n *\n * @param origin - The origin of the request.\n * @param snapId - The ID of the Snap to get the accounts from.\n * @returns The accounts, or `null` if the Snap does not have any accounts, or\n * the accounts are invalid (i.e., not valid CAIP-10 account IDs).\n */\n private async getSnapAccounts(\n origin: string,\n snapId: SnapId,\n ): Promise<AccountId[] | null> {\n try {\n const result = await this.snapRequest({\n snapId,\n origin,\n method: 'getAccounts',\n });\n\n if (isAccountIdArray(result)) {\n return result;\n }\n } catch (error) {\n // Ignore errors for now\n logError(error);\n }\n\n return null;\n }\n\n /**\n * Get the namespaces for the given Snap, as described in the Snap's manifest.\n *\n * @param snap - The Snap to get the namespaces for.\n * @returns The namespaces, or `null` if the Snap does not have any\n * namespaces.\n */\n private snapToNamespaces(snap: TruncatedSnap): Namespaces | null {\n const permissions = this.messagingSystem.call(\n 'PermissionController:getPermissions',\n snap.id,\n );\n\n const keyringPermission = permissions?.[SnapEndowments.Keyring];\n return getKeyringCaveatNamespaces(keyringPermission);\n }\n\n /**\n * Maps from an object of namespace IDs and Snap IDs, and an object of\n * namespace IDs and requested namespaces, to an object of namespace IDs and\n * resolved accounts, with the Snap ID providing the accounts.\n *\n * @param origin - The origin of the request.\n * @param namespacesAndSnaps - An object of namespace IDs and Snap IDs\n * providing the namespace.\n * @param requestedNamespaces - An object of namespace IDs and requested\n * namespaces.\n * @returns An object of namespace IDs and resolved accounts, with the Snap ID\n * providing the accounts.\n */\n private async namespacesToAccounts(\n origin: string,\n namespacesAndSnaps: Record<NamespaceId, SnapId[]>,\n requestedNamespaces: Record<NamespaceId, RequestNamespace>,\n ): Promise<Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>> {\n const dedupedSnaps = [\n ...new Set(Object.values(namespacesAndSnaps).flat()),\n ] as SnapId[];\n\n const allAccounts = await dedupedSnaps.reduce<\n Promise<Record<string, AccountId[]>>\n >(async (previousPromise, snapId) => {\n const result = await this.getSnapAccounts(origin, snapId);\n const acc = await previousPromise;\n if (result) {\n acc[snapId] = result;\n }\n return acc;\n }, Promise.resolve({}));\n\n return Object.keys(namespacesAndSnaps).reduce<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] }[]>\n >((acc, namespaceId) => {\n const { chains } = requestedNamespaces[namespaceId];\n\n const accountInAnyRequestedChain = (account: AccountId) => {\n const { chainId: parsedChainId } = parseAccountId(account);\n return chains.some((chainId) => chainId === parsedChainId);\n };\n\n const result = Object.entries(allAccounts)\n .map(([snapId, accounts]) => ({\n snapId,\n accounts: accounts.filter(accountInAnyRequestedChain),\n }))\n .filter(({ accounts }) => accounts.length > 0);\n\n acc[namespaceId] = result;\n\n return acc;\n }, {});\n }\n\n /**\n * If multiple Snap IDs are provided for a namespace, this method will\n * determine which Snap ID to use for the namespace, by showing the user a\n * prompt.\n *\n * @param origin - The origin of the request.\n * @param possibleAccounts - An object containing the accounts provided by\n * each Snap ID for each namespace.\n * @returns An object containing the Snap ID to use for each namespace.\n */\n private async resolveConflicts(\n origin: string,\n possibleAccounts: Record<\n NamespaceId,\n { snapId: SnapId; accounts: AccountId[] }[]\n >,\n ): Promise<\n Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>\n > {\n // Get user approval for connection.\n const id = nanoid();\n const resolvedAccounts = (await this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n origin,\n id,\n type: 'multichain_connect',\n requestData: {\n possibleAccounts,\n },\n },\n true,\n )) as Record<NamespaceId, { snapId: SnapId; accounts: AccountId[] } | null>;\n\n // TODO: In the future, use another permission here to not give full\n // permission after handshake.\n // Instead we should give origin only a read-only access to list of accounts\n // without allowing provider.request() talking to a snap before additional\n // user approval. The additional approval would be requested in `onRequest`.\n\n const approvedPermissions = Object.values(resolvedAccounts).reduce<\n Record<string, Record<string, Partial<PermissionConstraint>>>\n >(\n (acc, curr) => {\n if (curr !== null) {\n acc[WALLET_SNAP_PERMISSION_KEY][curr.snapId] = {};\n }\n return acc;\n },\n { [WALLET_SNAP_PERMISSION_KEY]: {} },\n );\n\n this.messagingSystem.call('PermissionController:grantPermissions', {\n approvedPermissions,\n subject: { origin },\n });\n\n return resolvedAccounts;\n }\n}\n"]}
|
package/dist/multichain/index.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
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
|
-
__exportStar(require("./matching"), exports);
|
|
18
|
-
__exportStar(require("./middleware"), exports);
|
|
19
|
-
__exportStar(require("./MultiChainController"), exports);
|
|
20
|
-
//# sourceMappingURL=index.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/multichain/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAA2B;AAC3B,+CAA6B;AAC7B,yDAAuC","sourcesContent":["export * from './matching';\nexport * from './middleware';\nexport * from './MultiChainController';\n"]}
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { ConnectArguments, NamespaceId, SnapId, Namespace } from '@metamask/snaps-utils';
|
|
2
|
-
/**
|
|
3
|
-
* Finds a keyring snap for each namespace implements at a minimum the requested functionality.
|
|
4
|
-
*
|
|
5
|
-
* @param requestedNamespaces - The requested namespaces.
|
|
6
|
-
* @param snaps - All snaps and their exposed keyring namespaces.
|
|
7
|
-
* @returns A mapping between namespaces and snap ids.
|
|
8
|
-
*/
|
|
9
|
-
export declare function findMatchingKeyringSnaps(requestedNamespaces: ConnectArguments['requiredNamespaces'], snaps: Record<SnapId, Record<NamespaceId, Namespace> | null>): Record<NamespaceId, SnapId[]>;
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.findMatchingKeyringSnaps = void 0;
|
|
4
|
-
/**
|
|
5
|
-
* Finds a keyring snap for each namespace implements at a minimum the requested functionality.
|
|
6
|
-
*
|
|
7
|
-
* @param requestedNamespaces - The requested namespaces.
|
|
8
|
-
* @param snaps - All snaps and their exposed keyring namespaces.
|
|
9
|
-
* @returns A mapping between namespaces and snap ids.
|
|
10
|
-
*/
|
|
11
|
-
function findMatchingKeyringSnaps(requestedNamespaces, snaps) {
|
|
12
|
-
const snapEntries = Object.entries(snaps);
|
|
13
|
-
return Object.entries(requestedNamespaces).reduce((acc, [requestedNamespaceId, currentRequestedNamespace]) => {
|
|
14
|
-
const matchedSnaps = snapEntries
|
|
15
|
-
.filter(([, namespaces]) => {
|
|
16
|
-
const potentialMatch = namespaces?.[requestedNamespaceId];
|
|
17
|
-
return (potentialMatch !== undefined &&
|
|
18
|
-
matchNamespace(currentRequestedNamespace, potentialMatch));
|
|
19
|
-
})
|
|
20
|
-
.map(([snapId]) => snapId);
|
|
21
|
-
acc[requestedNamespaceId] = matchedSnaps;
|
|
22
|
-
return acc;
|
|
23
|
-
}, {});
|
|
24
|
-
}
|
|
25
|
-
exports.findMatchingKeyringSnaps = findMatchingKeyringSnaps;
|
|
26
|
-
/**
|
|
27
|
-
* Determines whether a keyring namespace is a match given a potential match and the requested namespace.
|
|
28
|
-
*
|
|
29
|
-
* This function assumes that the namespace ID has already been matched.
|
|
30
|
-
*
|
|
31
|
-
* @param requestedNamespace - The requested namespace information.
|
|
32
|
-
* @param potentialMatchNamespace - The potential match.
|
|
33
|
-
* @returns True if the potentially matching namespace is a match.
|
|
34
|
-
*/
|
|
35
|
-
function matchNamespace(requestedNamespace, potentialMatchNamespace) {
|
|
36
|
-
if (!requestedNamespace.chains.every((requestedChain) => potentialMatchNamespace.chains.some((potentialMatchChain) => potentialMatchChain.id === requestedChain))) {
|
|
37
|
-
return false;
|
|
38
|
-
}
|
|
39
|
-
if (!isSubset(requestedNamespace.events ?? [], potentialMatchNamespace.events ?? [])) {
|
|
40
|
-
return false;
|
|
41
|
-
}
|
|
42
|
-
if (!isSubset(requestedNamespace.methods ?? [], potentialMatchNamespace.methods ?? [])) {
|
|
43
|
-
return false;
|
|
44
|
-
}
|
|
45
|
-
return true;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Determines whether an array is a subset of another array.
|
|
49
|
-
*
|
|
50
|
-
* @param potentialSubset - The potential subset.
|
|
51
|
-
* @param array - The other array.
|
|
52
|
-
* @returns True if the first argument is a subset of second argument.
|
|
53
|
-
*/
|
|
54
|
-
function isSubset(potentialSubset, array) {
|
|
55
|
-
return potentialSubset.every((item) => array.includes(item));
|
|
56
|
-
}
|
|
57
|
-
//# sourceMappingURL=matching.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"matching.js","sourceRoot":"","sources":["../../src/multichain/matching.ts"],"names":[],"mappings":";;;AAOA;;;;;;GAMG;AACH,SAAgB,wBAAwB,CACtC,mBAA2D,EAC3D,KAA4D;IAE5D,MAAM,WAAW,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAC1C,OAAO,MAAM,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAE/C,CAAC,GAAG,EAAE,CAAC,oBAAoB,EAAE,yBAAyB,CAAC,EAAE,EAAE;QAC3D,MAAM,YAAY,GAAG,WAAW;aAC7B,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,EAAE,EAAE;YACzB,MAAM,cAAc,GAAG,UAAU,EAAE,CAAC,oBAAoB,CAAC,CAAC;YAC1D,OAAO,CACL,cAAc,KAAK,SAAS;gBAC5B,cAAc,CAAC,yBAAyB,EAAE,cAAc,CAAC,CAC1D,CAAC;QACJ,CAAC,CAAC;aACD,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;QAC7B,GAAG,CAAC,oBAAoB,CAAC,GAAG,YAAY,CAAC;QACzC,OAAO,GAAG,CAAC;IACb,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC;AApBD,4DAoBC;AAED;;;;;;;;GAQG;AACH,SAAS,cAAc,CACrB,kBAAuE,EACvE,uBAAkC;IAElC,IACE,CAAC,kBAAkB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,cAAc,EAAE,EAAE,CAClD,uBAAuB,CAAC,MAAM,CAAC,IAAI,CACjC,CAAC,mBAAmB,EAAE,EAAE,CAAC,mBAAmB,CAAC,EAAE,KAAK,cAAc,CACnE,CACF,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,IACE,CAAC,QAAQ,CACP,kBAAkB,CAAC,MAAM,IAAI,EAAE,EAC/B,uBAAuB,CAAC,MAAM,IAAI,EAAE,CACrC,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,IACE,CAAC,QAAQ,CACP,kBAAkB,CAAC,OAAO,IAAI,EAAE,EAChC,uBAAuB,CAAC,OAAO,IAAI,EAAE,CACtC,EACD;QACA,OAAO,KAAK,CAAC;KACd;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;GAMG;AACH,SAAS,QAAQ,CAAI,eAAoB,EAAE,KAAU;IACnD,OAAO,eAAe,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAC/D,CAAC","sourcesContent":["import {\n ConnectArguments,\n NamespaceId,\n SnapId,\n Namespace,\n} from '@metamask/snaps-utils';\n\n/**\n * Finds a keyring snap for each namespace implements at a minimum the requested functionality.\n *\n * @param requestedNamespaces - The requested namespaces.\n * @param snaps - All snaps and their exposed keyring namespaces.\n * @returns A mapping between namespaces and snap ids.\n */\nexport function findMatchingKeyringSnaps(\n requestedNamespaces: ConnectArguments['requiredNamespaces'],\n snaps: Record<SnapId, Record<NamespaceId, Namespace> | null>,\n): Record<NamespaceId, SnapId[]> {\n const snapEntries = Object.entries(snaps);\n return Object.entries(requestedNamespaces).reduce<\n Record<NamespaceId, SnapId[]>\n >((acc, [requestedNamespaceId, currentRequestedNamespace]) => {\n const matchedSnaps = snapEntries\n .filter(([, namespaces]) => {\n const potentialMatch = namespaces?.[requestedNamespaceId];\n return (\n potentialMatch !== undefined &&\n matchNamespace(currentRequestedNamespace, potentialMatch)\n );\n })\n .map(([snapId]) => snapId);\n acc[requestedNamespaceId] = matchedSnaps;\n return acc;\n }, {});\n}\n\n/**\n * Determines whether a keyring namespace is a match given a potential match and the requested namespace.\n *\n * This function assumes that the namespace ID has already been matched.\n *\n * @param requestedNamespace - The requested namespace information.\n * @param potentialMatchNamespace - The potential match.\n * @returns True if the potentially matching namespace is a match.\n */\nfunction matchNamespace(\n requestedNamespace: ConnectArguments['requiredNamespaces'][NamespaceId],\n potentialMatchNamespace: Namespace,\n) {\n if (\n !requestedNamespace.chains.every((requestedChain) =>\n potentialMatchNamespace.chains.some(\n (potentialMatchChain) => potentialMatchChain.id === requestedChain,\n ),\n )\n ) {\n return false;\n }\n\n if (\n !isSubset(\n requestedNamespace.events ?? [],\n potentialMatchNamespace.events ?? [],\n )\n ) {\n return false;\n }\n\n if (\n !isSubset(\n requestedNamespace.methods ?? [],\n potentialMatchNamespace.methods ?? [],\n )\n ) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Determines whether an array is a subset of another array.\n *\n * @param potentialSubset - The potential subset.\n * @param array - The other array.\n * @returns True if the first argument is a subset of second argument.\n */\nfunction isSubset<T>(potentialSubset: T[], array: T[]) {\n return potentialSubset.every((item) => array.includes(item));\n}\n"]}
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { ConnectArguments, Session, MultiChainRequest } from '@metamask/snaps-utils';
|
|
2
|
-
import { JsonRpcMiddleware, JsonRpcRequest } from 'json-rpc-engine';
|
|
3
|
-
/**
|
|
4
|
-
* Creates a middleware that handles requests to the multichain controller.
|
|
5
|
-
*
|
|
6
|
-
* @param hooks - The hooks required by the middleware.
|
|
7
|
-
* @param hooks.onConnect - The onConnect hook.
|
|
8
|
-
* @param hooks.onRequest - The onRequest hook.
|
|
9
|
-
* @returns The middleware.
|
|
10
|
-
*/
|
|
11
|
-
export declare function createMultiChainMiddleware({ onConnect, onRequest, }: {
|
|
12
|
-
onConnect: (origin: string, requestedNamespaces: ConnectArguments) => Promise<Session>;
|
|
13
|
-
onRequest: (origin: string, data: MultiChainRequest) => Promise<unknown>;
|
|
14
|
-
}): JsonRpcMiddleware<Omit<JsonRpcRequest<unknown>, 'id' | 'jsonrpc'>, any>;
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createMultiChainMiddleware = void 0;
|
|
4
|
-
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
5
|
-
const utils_1 = require("@metamask/utils");
|
|
6
|
-
const json_rpc_engine_1 = require("json-rpc-engine");
|
|
7
|
-
/**
|
|
8
|
-
* Creates a middleware that handles requests to the multichain controller.
|
|
9
|
-
*
|
|
10
|
-
* @param hooks - The hooks required by the middleware.
|
|
11
|
-
* @param hooks.onConnect - The onConnect hook.
|
|
12
|
-
* @param hooks.onRequest - The onRequest hook.
|
|
13
|
-
* @returns The middleware.
|
|
14
|
-
*/
|
|
15
|
-
function createMultiChainMiddleware({ onConnect, onRequest, }) {
|
|
16
|
-
return (0, json_rpc_engine_1.createAsyncMiddleware)(async function middleware(req, res, next) {
|
|
17
|
-
// This is added by other middleware
|
|
18
|
-
const { origin, params: unwrapped } = req;
|
|
19
|
-
if (req.method !== 'wallet_multiChainRequestHack') {
|
|
20
|
-
await next();
|
|
21
|
-
return;
|
|
22
|
-
}
|
|
23
|
-
(0, utils_1.assert)(unwrapped !== undefined, `Invalid params for ${req.method}`);
|
|
24
|
-
switch (unwrapped.method) {
|
|
25
|
-
case 'caip_request': {
|
|
26
|
-
(0, snaps_utils_1.assertIsMultiChainRequest)(unwrapped.params);
|
|
27
|
-
res.result = await onRequest(origin, unwrapped.params);
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
case 'metamask_handshake': {
|
|
31
|
-
(0, snaps_utils_1.assertIsConnectArguments)(unwrapped.params);
|
|
32
|
-
res.result = await onConnect(origin, unwrapped.params);
|
|
33
|
-
return;
|
|
34
|
-
}
|
|
35
|
-
default: {
|
|
36
|
-
await next();
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
exports.createMultiChainMiddleware = createMultiChainMiddleware;
|
|
42
|
-
//# sourceMappingURL=middleware.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/multichain/middleware.ts"],"names":[],"mappings":";;;AAAA,uDAM+B;AAC/B,2CAAyC;AACzC,qDAIyB;AAEzB;;;;;;;GAOG;AACH,SAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,SAAS,GAOV;IACC,OAAO,IAAA,uCAAqB,EAAC,KAAK,UAAU,UAAU,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI;QACnE,oCAAoC;QACpC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,GAEhB,CAAC;QACvB,IAAI,GAAG,CAAC,MAAM,KAAK,8BAA8B,EAAE;YACjD,MAAM,IAAI,EAAE,CAAC;YACb,OAAO;SACR;QAED,IAAA,cAAM,EAAC,SAAS,KAAK,SAAS,EAAE,sBAAsB,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;QAEpE,QAAQ,SAAS,CAAC,MAAM,EAAE;YACxB,KAAK,cAAc,CAAC,CAAC;gBACnB,IAAA,uCAAyB,EAAC,SAAS,CAAC,MAAM,CAAC,CAAC;gBAC5C,GAAG,CAAC,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;gBACvD,OAAO;aACR;YAED,KAAK,oBAAoB,CAAC,CAAC;gBACzB,IAAA,sCAAwB,EAAC,SAAS,CAAC,MAAM,CAAC,CAAC;gBAC3C,GAAG,CAAC,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;gBACvD,OAAO;aACR;YAED,OAAO,CAAC,CAAC;gBACP,MAAM,IAAI,EAAE,CAAC;aACd;SACF;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAxCD,gEAwCC","sourcesContent":["import {\n assertIsConnectArguments,\n assertIsMultiChainRequest,\n ConnectArguments,\n Session,\n MultiChainRequest,\n} from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\nimport {\n createAsyncMiddleware,\n JsonRpcMiddleware,\n JsonRpcRequest,\n} from 'json-rpc-engine';\n\n/**\n * Creates a middleware that handles requests to the multichain controller.\n *\n * @param hooks - The hooks required by the middleware.\n * @param hooks.onConnect - The onConnect hook.\n * @param hooks.onRequest - The onRequest hook.\n * @returns The middleware.\n */\nexport function createMultiChainMiddleware({\n onConnect,\n onRequest,\n}: {\n onConnect: (\n origin: string,\n requestedNamespaces: ConnectArguments,\n ) => Promise<Session>;\n onRequest: (origin: string, data: MultiChainRequest) => Promise<unknown>;\n}): JsonRpcMiddleware<Omit<JsonRpcRequest<unknown>, 'id' | 'jsonrpc'>, any> {\n return createAsyncMiddleware(async function middleware(req, res, next) {\n // This is added by other middleware\n const { origin, params: unwrapped } = req as JsonRpcRequest<\n JsonRpcRequest<unknown>\n > & { origin: string };\n if (req.method !== 'wallet_multiChainRequestHack') {\n await next();\n return;\n }\n\n assert(unwrapped !== undefined, `Invalid params for ${req.method}`);\n\n switch (unwrapped.method) {\n case 'caip_request': {\n assertIsMultiChainRequest(unwrapped.params);\n res.result = await onRequest(origin, unwrapped.params);\n return;\n }\n\n case 'metamask_handshake': {\n assertIsConnectArguments(unwrapped.params);\n res.result = await onConnect(origin, unwrapped.params);\n return;\n }\n\n default: {\n await next();\n }\n }\n });\n}\n"]}
|
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
-
};
|
|
8
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
-
};
|
|
13
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
-
};
|
|
16
|
-
var _AbstractExecutionService_instances, _AbstractExecutionService_snapRpcHooks, _AbstractExecutionService_snapToJobMap, _AbstractExecutionService_jobToSnapMap, _AbstractExecutionService_messenger, _AbstractExecutionService_terminationTimeout, _AbstractExecutionService_removeSnapHooks, _AbstractExecutionService_createSnapHooks, _AbstractExecutionService_getJobForSnap, _AbstractExecutionService_getSnapForJob, _AbstractExecutionService_mapSnapAndJob, _AbstractExecutionService_removeSnapAndJobMapping;
|
|
17
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.setupMultiplex = exports.AbstractExecutionService = void 0;
|
|
19
|
-
const object_multiplex_1 = __importDefault(require("@metamask/object-multiplex"));
|
|
20
|
-
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
21
|
-
const utils_1 = require("@metamask/utils");
|
|
22
|
-
const json_rpc_engine_1 = require("json-rpc-engine");
|
|
23
|
-
const json_rpc_middleware_stream_1 = require("json-rpc-middleware-stream");
|
|
24
|
-
const nanoid_1 = require("nanoid");
|
|
25
|
-
const pump_1 = __importDefault(require("pump"));
|
|
26
|
-
const logging_1 = require("../logging");
|
|
27
|
-
const utils_2 = require("../utils");
|
|
28
|
-
const controllerName = 'ExecutionService';
|
|
29
|
-
class AbstractExecutionService {
|
|
30
|
-
constructor({ setupSnapProvider, messenger, terminationTimeout = utils_1.Duration.Second, }) {
|
|
31
|
-
_AbstractExecutionService_instances.add(this);
|
|
32
|
-
_AbstractExecutionService_snapRpcHooks.set(this, void 0);
|
|
33
|
-
_AbstractExecutionService_snapToJobMap.set(this, void 0);
|
|
34
|
-
_AbstractExecutionService_jobToSnapMap.set(this, void 0);
|
|
35
|
-
_AbstractExecutionService_messenger.set(this, void 0);
|
|
36
|
-
_AbstractExecutionService_terminationTimeout.set(this, void 0);
|
|
37
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_snapRpcHooks, new Map(), "f");
|
|
38
|
-
this.jobs = new Map();
|
|
39
|
-
this.setupSnapProvider = setupSnapProvider;
|
|
40
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_snapToJobMap, new Map(), "f");
|
|
41
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_jobToSnapMap, new Map(), "f");
|
|
42
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_messenger, messenger, "f");
|
|
43
|
-
__classPrivateFieldSet(this, _AbstractExecutionService_terminationTimeout, terminationTimeout, "f");
|
|
44
|
-
this.registerMessageHandlers();
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Constructor helper for registering the controller's messaging system
|
|
48
|
-
* actions.
|
|
49
|
-
*/
|
|
50
|
-
registerMessageHandlers() {
|
|
51
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:handleRpcRequest`, async (snapId, options) => this.handleRpcRequest(snapId, options));
|
|
52
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:executeSnap`, async (snapData) => this.executeSnap(snapData));
|
|
53
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateSnap`, async (snapId) => this.terminateSnap(snapId));
|
|
54
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").registerActionHandler(`${controllerName}:terminateAllSnaps`, async () => this.terminateAllSnaps());
|
|
55
|
-
}
|
|
56
|
-
/**
|
|
57
|
-
* Terminates the job with the specified ID and deletes all its associated
|
|
58
|
-
* data. Any subsequent messages targeting the job will fail with an error.
|
|
59
|
-
* Throws an error if the specified job does not exist, or if termination
|
|
60
|
-
* fails unexpectedly.
|
|
61
|
-
*
|
|
62
|
-
* @param jobId - The id of the job to be terminated.
|
|
63
|
-
*/
|
|
64
|
-
async terminate(jobId) {
|
|
65
|
-
const jobWrapper = this.jobs.get(jobId);
|
|
66
|
-
if (!jobWrapper) {
|
|
67
|
-
throw new Error(`Job with id "${jobId}" not found.`);
|
|
68
|
-
}
|
|
69
|
-
// Ping worker and tell it to run teardown, continue with termination if it takes too long
|
|
70
|
-
const result = await (0, utils_2.withTimeout)(this.command(jobId, {
|
|
71
|
-
jsonrpc: '2.0',
|
|
72
|
-
method: 'terminate',
|
|
73
|
-
params: [],
|
|
74
|
-
id: (0, nanoid_1.nanoid)(),
|
|
75
|
-
}), __classPrivateFieldGet(this, _AbstractExecutionService_terminationTimeout, "f"));
|
|
76
|
-
if (result === utils_2.hasTimedOut || result !== 'OK') {
|
|
77
|
-
// We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and
|
|
78
|
-
// hogging down the whole JS process.
|
|
79
|
-
// TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour
|
|
80
|
-
// doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same
|
|
81
|
-
// JS process.
|
|
82
|
-
(0, snaps_utils_1.logError)(`Job "${jobId}" failed to terminate gracefully.`, result);
|
|
83
|
-
}
|
|
84
|
-
Object.values(jobWrapper.streams).forEach((stream) => {
|
|
85
|
-
try {
|
|
86
|
-
!stream.destroyed && stream.destroy();
|
|
87
|
-
stream.removeAllListeners();
|
|
88
|
-
}
|
|
89
|
-
catch (error) {
|
|
90
|
-
(0, snaps_utils_1.logError)('Error while destroying stream', error);
|
|
91
|
-
}
|
|
92
|
-
});
|
|
93
|
-
this.terminateJob(jobWrapper);
|
|
94
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapAndJobMapping).call(this, jobId);
|
|
95
|
-
this.jobs.delete(jobId);
|
|
96
|
-
(0, logging_1.log)(`Job "${jobId}" terminated.`);
|
|
97
|
-
}
|
|
98
|
-
/**
|
|
99
|
-
* Initiates a job for a snap.
|
|
100
|
-
*
|
|
101
|
-
* Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
|
|
102
|
-
*
|
|
103
|
-
* @returns Information regarding the created job.
|
|
104
|
-
*/
|
|
105
|
-
async initJob() {
|
|
106
|
-
const jobId = (0, nanoid_1.nanoid)();
|
|
107
|
-
const { streams, worker } = await this.initStreams(jobId);
|
|
108
|
-
const rpcEngine = new json_rpc_engine_1.JsonRpcEngine();
|
|
109
|
-
const jsonRpcConnection = (0, json_rpc_middleware_stream_1.createStreamMiddleware)();
|
|
110
|
-
(0, pump_1.default)(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);
|
|
111
|
-
rpcEngine.push(jsonRpcConnection.middleware);
|
|
112
|
-
const envMetadata = {
|
|
113
|
-
id: jobId,
|
|
114
|
-
streams,
|
|
115
|
-
rpcEngine,
|
|
116
|
-
worker,
|
|
117
|
-
};
|
|
118
|
-
this.jobs.set(jobId, envMetadata);
|
|
119
|
-
return envMetadata;
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Sets up the streams for an initiated job.
|
|
123
|
-
*
|
|
124
|
-
* Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
|
|
125
|
-
*
|
|
126
|
-
* @param jobId - The id of the job.
|
|
127
|
-
* @returns The streams to communicate with the worker and the worker itself.
|
|
128
|
-
*/
|
|
129
|
-
async initStreams(jobId) {
|
|
130
|
-
const { worker, stream: envStream } = await this.initEnvStream(jobId);
|
|
131
|
-
// Typecast justification: stream type mismatch
|
|
132
|
-
const mux = setupMultiplex(envStream, `Job: "${jobId}"`);
|
|
133
|
-
const commandStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.COMMAND);
|
|
134
|
-
// Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.
|
|
135
|
-
// Also keep track of outbound request/responses
|
|
136
|
-
const notificationHandler = (message) => {
|
|
137
|
-
if (!(0, utils_1.isJsonRpcNotification)(message)) {
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
141
|
-
const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
|
|
142
|
-
if (message.method === 'OutboundRequest') {
|
|
143
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundRequest', snapId);
|
|
144
|
-
}
|
|
145
|
-
else if (message.method === 'OutboundResponse') {
|
|
146
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:outboundResponse', snapId);
|
|
147
|
-
}
|
|
148
|
-
else if (message.method === 'UnhandledError') {
|
|
149
|
-
if ((0, utils_1.isObject)(message.params) && message.params.error) {
|
|
150
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_messenger, "f").publish('ExecutionService:unhandledError', snapId, message.params.error);
|
|
151
|
-
commandStream.removeListener('data', notificationHandler);
|
|
152
|
-
}
|
|
153
|
-
else {
|
|
154
|
-
(0, snaps_utils_1.logError)(new Error(`Received malformed "${message.method}" command stream notification.`));
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
else {
|
|
158
|
-
(0, snaps_utils_1.logError)(new Error(`Received unexpected command stream notification "${message.method}".`));
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
commandStream.on('data', notificationHandler);
|
|
162
|
-
const rpcStream = mux.createStream(snaps_utils_1.SNAP_STREAM_NAMES.JSON_RPC);
|
|
163
|
-
// Typecast: stream type mismatch
|
|
164
|
-
return {
|
|
165
|
-
streams: {
|
|
166
|
-
command: commandStream,
|
|
167
|
-
rpc: rpcStream,
|
|
168
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
169
|
-
_connection: envStream,
|
|
170
|
-
},
|
|
171
|
-
worker,
|
|
172
|
-
};
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Terminates the Snap with the specified ID. May throw an error if
|
|
176
|
-
* termination unexpectedly fails, but will not fail if no job for the snap
|
|
177
|
-
* with the specified ID is found.
|
|
178
|
-
*
|
|
179
|
-
* @param snapId - The ID of the snap to terminate.
|
|
180
|
-
*/
|
|
181
|
-
async terminateSnap(snapId) {
|
|
182
|
-
const jobId = __classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").get(snapId);
|
|
183
|
-
if (jobId) {
|
|
184
|
-
await this.terminate(jobId);
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
async terminateAllSnaps() {
|
|
188
|
-
await Promise.all([...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)));
|
|
189
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").clear();
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Gets the RPC request handler for the given snap.
|
|
193
|
-
*
|
|
194
|
-
* @param snapId - The id of the Snap whose message handler to get.
|
|
195
|
-
* @returns The RPC request handler for the snap.
|
|
196
|
-
*/
|
|
197
|
-
getRpcRequestHandler(snapId) {
|
|
198
|
-
return __classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").get(snapId);
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Initializes and executes a snap, setting up the communication channels to the snap etc.
|
|
202
|
-
*
|
|
203
|
-
* Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.
|
|
204
|
-
*
|
|
205
|
-
* @param snapData - Data needed for Snap execution.
|
|
206
|
-
* @returns A string `OK` if execution succeeded.
|
|
207
|
-
* @throws If the execution service returns an error.
|
|
208
|
-
*/
|
|
209
|
-
async executeSnap(snapData) {
|
|
210
|
-
if (__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").has(snapData.snapId)) {
|
|
211
|
-
throw new Error(`Snap "${snapData.snapId}" is already being executed.`);
|
|
212
|
-
}
|
|
213
|
-
const job = await this.initJob();
|
|
214
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_mapSnapAndJob).call(this, snapData.snapId, job.id);
|
|
215
|
-
// Ping the worker to ensure that it started up
|
|
216
|
-
await this.command(job.id, {
|
|
217
|
-
jsonrpc: '2.0',
|
|
218
|
-
method: 'ping',
|
|
219
|
-
id: (0, nanoid_1.nanoid)(),
|
|
220
|
-
});
|
|
221
|
-
const rpcStream = job.streams.rpc;
|
|
222
|
-
this.setupSnapProvider(snapData.snapId, rpcStream);
|
|
223
|
-
const result = await this.command(job.id, {
|
|
224
|
-
jsonrpc: '2.0',
|
|
225
|
-
method: 'executeSnap',
|
|
226
|
-
params: snapData,
|
|
227
|
-
id: (0, nanoid_1.nanoid)(),
|
|
228
|
-
});
|
|
229
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_createSnapHooks).call(this, snapData.snapId, job.id);
|
|
230
|
-
return result;
|
|
231
|
-
}
|
|
232
|
-
// Cannot be hash private yet because of tests.
|
|
233
|
-
async command(jobId, message) {
|
|
234
|
-
if (typeof message !== 'object') {
|
|
235
|
-
throw new Error('Must send object.');
|
|
236
|
-
}
|
|
237
|
-
const job = this.jobs.get(jobId);
|
|
238
|
-
if (!job) {
|
|
239
|
-
throw new Error(`Job with id "${jobId}" not found.`);
|
|
240
|
-
}
|
|
241
|
-
(0, logging_1.log)('Parent: Sending Command', message);
|
|
242
|
-
const response = await job.rpcEngine.handle(message);
|
|
243
|
-
if (response.error) {
|
|
244
|
-
throw new Error(response.error.message);
|
|
245
|
-
}
|
|
246
|
-
return response.result;
|
|
247
|
-
}
|
|
248
|
-
/**
|
|
249
|
-
* Handle RPC request.
|
|
250
|
-
*
|
|
251
|
-
* @param snapId - The ID of the recipient snap.
|
|
252
|
-
* @param options - Bag of options to pass to the RPC handler.
|
|
253
|
-
* @returns Promise that can handle the request.
|
|
254
|
-
*/
|
|
255
|
-
async handleRpcRequest(snapId, options) {
|
|
256
|
-
const rpcRequestHandler = await this.getRpcRequestHandler(snapId);
|
|
257
|
-
if (!rpcRequestHandler) {
|
|
258
|
-
throw new Error(`Snap execution service returned no RPC handler for running snap "${snapId}".`);
|
|
259
|
-
}
|
|
260
|
-
return rpcRequestHandler(options);
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
exports.AbstractExecutionService = AbstractExecutionService;
|
|
264
|
-
_AbstractExecutionService_snapRpcHooks = new WeakMap(), _AbstractExecutionService_snapToJobMap = new WeakMap(), _AbstractExecutionService_jobToSnapMap = new WeakMap(), _AbstractExecutionService_messenger = new WeakMap(), _AbstractExecutionService_terminationTimeout = new WeakMap(), _AbstractExecutionService_instances = new WeakSet(), _AbstractExecutionService_removeSnapHooks = function _AbstractExecutionService_removeSnapHooks(snapId) {
|
|
265
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").delete(snapId);
|
|
266
|
-
}, _AbstractExecutionService_createSnapHooks = function _AbstractExecutionService_createSnapHooks(snapId, workerId) {
|
|
267
|
-
const rpcHook = async ({ origin, handler, request }) => {
|
|
268
|
-
return await this.command(workerId, {
|
|
269
|
-
id: (0, nanoid_1.nanoid)(),
|
|
270
|
-
jsonrpc: '2.0',
|
|
271
|
-
method: 'snapRpc',
|
|
272
|
-
params: {
|
|
273
|
-
origin,
|
|
274
|
-
handler,
|
|
275
|
-
request,
|
|
276
|
-
target: snapId,
|
|
277
|
-
},
|
|
278
|
-
});
|
|
279
|
-
};
|
|
280
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapRpcHooks, "f").set(snapId, rpcHook);
|
|
281
|
-
}, _AbstractExecutionService_getJobForSnap = function _AbstractExecutionService_getJobForSnap(snapId) {
|
|
282
|
-
return __classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").get(snapId);
|
|
283
|
-
}, _AbstractExecutionService_getSnapForJob = function _AbstractExecutionService_getSnapForJob(jobId) {
|
|
284
|
-
return __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
|
|
285
|
-
}, _AbstractExecutionService_mapSnapAndJob = function _AbstractExecutionService_mapSnapAndJob(snapId, jobId) {
|
|
286
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").set(snapId, jobId);
|
|
287
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").set(jobId, snapId);
|
|
288
|
-
}, _AbstractExecutionService_removeSnapAndJobMapping = function _AbstractExecutionService_removeSnapAndJobMapping(jobId) {
|
|
289
|
-
const snapId = __classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").get(jobId);
|
|
290
|
-
if (!snapId) {
|
|
291
|
-
throw new Error(`job: "${jobId}" has no mapped snap.`);
|
|
292
|
-
}
|
|
293
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_jobToSnapMap, "f").delete(jobId);
|
|
294
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_snapToJobMap, "f").delete(snapId);
|
|
295
|
-
__classPrivateFieldGet(this, _AbstractExecutionService_instances, "m", _AbstractExecutionService_removeSnapHooks).call(this, snapId);
|
|
296
|
-
};
|
|
297
|
-
/**
|
|
298
|
-
* Sets up stream multiplexing for the given stream.
|
|
299
|
-
*
|
|
300
|
-
* @param connectionStream - The stream to mux.
|
|
301
|
-
* @param streamName - The name of the stream, for identification in errors.
|
|
302
|
-
* @returns The multiplexed stream.
|
|
303
|
-
*/
|
|
304
|
-
function setupMultiplex(connectionStream, streamName) {
|
|
305
|
-
const mux = new object_multiplex_1.default();
|
|
306
|
-
(0, pump_1.default)(connectionStream,
|
|
307
|
-
// Typecast: stream type mismatch
|
|
308
|
-
mux, connectionStream, (error) => {
|
|
309
|
-
if (error) {
|
|
310
|
-
streamName
|
|
311
|
-
? (0, snaps_utils_1.logError)(`"${streamName}" stream failure.`, error)
|
|
312
|
-
: (0, snaps_utils_1.logError)(error);
|
|
313
|
-
}
|
|
314
|
-
});
|
|
315
|
-
return mux;
|
|
316
|
-
}
|
|
317
|
-
exports.setupMultiplex = setupMultiplex;
|
|
318
|
-
//# sourceMappingURL=AbstractExecutionService.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AbstractExecutionService.js","sourceRoot":"","sources":["../../src/services/AbstractExecutionService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,kFAAyD;AAEzD,uDAK+B;AAC/B,2CAMyB;AACzB,qDAKyB;AACzB,2EAAoE;AACpE,mCAAgC;AAChC,gDAAwB;AAGxB,wCAAiC;AACjC,oCAAoD;AAQpD,MAAM,cAAc,GAAG,kBAAkB,CAAC;AAuB1C,MAAsB,wBAAwB;IAmB5C,YAAY,EACV,iBAAiB,EACjB,SAAS,EACT,kBAAkB,GAAG,gBAAQ,CAAC,MAAM,GACf;;QApBvB,yDAAwC;QAQxC,yDAAmC;QAEnC,yDAAmC;QAEnC,sDAAsC;QAEtC,+DAA4B;QAO1B,uBAAA,IAAI,0CAAiB,IAAI,GAAG,EAAE,MAAA,CAAC;QAC/B,IAAI,CAAC,IAAI,GAAG,IAAI,GAAG,EAAE,CAAC;QACtB,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,uBAAA,IAAI,0CAAiB,IAAI,GAAG,EAAE,MAAA,CAAC;QAC/B,uBAAA,IAAI,0CAAiB,IAAI,GAAG,EAAE,MAAA,CAAC;QAC/B,uBAAA,IAAI,uCAAc,SAAS,MAAA,C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gBAAgB,EAChB,CAAC,KAAK,EAAE,EAAE;QACR,IAAI,KAAK,EAAE;YACT,UAAU;gBACR,CAAC,CAAC,IAAA,sBAAQ,EAAC,IAAI,UAAU,mBAAmB,EAAE,KAAK,CAAC;gBACpD,CAAC,CAAC,IAAA,sBAAQ,EAAC,KAAK,CAAC,CAAC;SACrB;IACH,CAAC,CACF,CAAC;IACF,OAAO,GAAG,CAAC;AACb,CAAC;AAnBD,wCAmBC","sourcesContent":["import ObjectMultiplex from '@metamask/object-multiplex';\nimport { BasePostMessageStream } from '@metamask/post-message-stream';\nimport {\n SnapRpcHook,\n SnapRpcHookArgs,\n SNAP_STREAM_NAMES,\n logError,\n} from '@metamask/snaps-utils';\nimport {\n Duration,\n isJsonRpcNotification,\n isObject,\n Json,\n JsonRpcNotification,\n} from '@metamask/utils';\nimport {\n JsonRpcEngine,\n // TODO: Replace with @metamask/utils version after bumping json-rpc-engine\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from 'json-rpc-engine';\nimport { createStreamMiddleware } from 'json-rpc-middleware-stream';\nimport { nanoid } from 'nanoid';\nimport pump from 'pump';\nimport { Duplex } from 'stream';\n\nimport { log } from '../logging';\nimport { hasTimedOut, withTimeout } from '../utils';\nimport {\n ExecutionService,\n ExecutionServiceMessenger,\n SnapErrorJson,\n SnapExecutionData,\n} from './ExecutionService';\n\nconst controllerName = 'ExecutionService';\n\nexport type SetupSnapProvider = (snapId: string, stream: Duplex) => void;\n\nexport type ExecutionServiceArgs = {\n setupSnapProvider: SetupSnapProvider;\n messenger: ExecutionServiceMessenger;\n terminationTimeout?: number;\n};\n\nexport type JobStreams = {\n command: Duplex;\n rpc: Duplex;\n _connection: BasePostMessageStream;\n};\n\nexport type Job<WorkerType> = {\n id: string;\n streams: JobStreams;\n rpcEngine: JsonRpcEngine;\n worker: WorkerType;\n};\n\nexport abstract class AbstractExecutionService<WorkerType>\n implements ExecutionService\n{\n #snapRpcHooks: Map<string, SnapRpcHook>;\n\n // Cannot be hash private yet because of tests.\n protected jobs: Map<string, Job<WorkerType>>;\n\n // Cannot be hash private yet because of tests.\n private readonly setupSnapProvider: SetupSnapProvider;\n\n #snapToJobMap: Map<string, string>;\n\n #jobToSnapMap: Map<string, string>;\n\n #messenger: ExecutionServiceMessenger;\n\n #terminationTimeout: number;\n\n constructor({\n setupSnapProvider,\n messenger,\n terminationTimeout = Duration.Second,\n }: ExecutionServiceArgs) {\n this.#snapRpcHooks = new Map();\n this.jobs = new Map();\n this.setupSnapProvider = setupSnapProvider;\n this.#snapToJobMap = new Map();\n this.#jobToSnapMap = new Map();\n this.#messenger = messenger;\n this.#terminationTimeout = terminationTimeout;\n\n this.registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering the controller's messaging system\n * actions.\n */\n private registerMessageHandlers(): void {\n this.#messenger.registerActionHandler(\n `${controllerName}:handleRpcRequest`,\n async (snapId: string, options: SnapRpcHookArgs) =>\n this.handleRpcRequest(snapId, options),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:executeSnap`,\n async (snapData: SnapExecutionData) => this.executeSnap(snapData),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateSnap`,\n async (snapId: string) => this.terminateSnap(snapId),\n );\n\n this.#messenger.registerActionHandler(\n `${controllerName}:terminateAllSnaps`,\n async () => this.terminateAllSnaps(),\n );\n }\n\n /**\n * Performs additional necessary work during job termination. **MUST** be\n * implemented by concrete implementations. See\n * {@link AbstractExecutionService.terminate} for details.\n *\n * @param job - The object corresponding to the job to be terminated.\n */\n protected abstract terminateJob(job: Job<WorkerType>): void;\n\n /**\n * Terminates the job with the specified ID and deletes all its associated\n * data. Any subsequent messages targeting the job will fail with an error.\n * Throws an error if the specified job does not exist, or if termination\n * fails unexpectedly.\n *\n * @param jobId - The id of the job to be terminated.\n */\n public async terminate(jobId: string): Promise<void> {\n const jobWrapper = this.jobs.get(jobId);\n if (!jobWrapper) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n // Ping worker and tell it to run teardown, continue with termination if it takes too long\n const result = await withTimeout(\n this.command(jobId, {\n jsonrpc: '2.0',\n method: 'terminate',\n params: [],\n id: nanoid(),\n }),\n this.#terminationTimeout,\n );\n\n if (result === hasTimedOut || result !== 'OK') {\n // We tried to shutdown gracefully but failed. This probably means the Snap is in infinite loop and\n // hogging down the whole JS process.\n // TODO(ritave): It might be doing weird things such as posting a lot of setTimeouts. Add a test to ensure that this behaviour\n // doesn't leak into other workers. Especially important in IframeExecutionEnvironment since they all share the same\n // JS process.\n logError(`Job \"${jobId}\" failed to terminate gracefully.`, result);\n }\n\n Object.values(jobWrapper.streams).forEach((stream) => {\n try {\n !stream.destroyed && stream.destroy();\n stream.removeAllListeners();\n } catch (error) {\n logError('Error while destroying stream', error);\n }\n });\n\n this.terminateJob(jobWrapper);\n\n this.#removeSnapAndJobMapping(jobId);\n this.jobs.delete(jobId);\n log(`Job \"${jobId}\" terminated.`);\n }\n\n /**\n * Initiates a job for a snap.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @returns Information regarding the created job.\n */\n protected async initJob(): Promise<Job<WorkerType>> {\n const jobId = nanoid();\n const { streams, worker } = await this.initStreams(jobId);\n const rpcEngine = new JsonRpcEngine();\n\n const jsonRpcConnection = createStreamMiddleware();\n\n pump(jsonRpcConnection.stream, streams.command, jsonRpcConnection.stream);\n\n rpcEngine.push(jsonRpcConnection.middleware);\n\n const envMetadata = {\n id: jobId,\n streams,\n rpcEngine,\n worker,\n };\n this.jobs.set(jobId, envMetadata);\n\n return envMetadata;\n }\n\n /**\n * Sets up the streams for an initiated job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param jobId - The id of the job.\n * @returns The streams to communicate with the worker and the worker itself.\n */\n protected async initStreams(\n jobId: string,\n ): Promise<{ streams: JobStreams; worker: WorkerType }> {\n const { worker, stream: envStream } = await this.initEnvStream(jobId);\n // Typecast justification: stream type mismatch\n const mux = setupMultiplex(\n envStream as unknown as Duplex,\n `Job: \"${jobId}\"`,\n );\n\n const commandStream = mux.createStream(SNAP_STREAM_NAMES.COMMAND);\n\n // Handle out-of-band errors, i.e. errors thrown from the snap outside of the req/res cycle.\n // Also keep track of outbound request/responses\n const notificationHandler = (\n message:\n | JsonRpcRequest<unknown>\n | JsonRpcNotification<Json[] | Record<string, Json>>,\n ) => {\n if (!isJsonRpcNotification(message)) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const snapId = this.#jobToSnapMap.get(jobId)!;\n if (message.method === 'OutboundRequest') {\n this.#messenger.publish('ExecutionService:outboundRequest', snapId);\n } else if (message.method === 'OutboundResponse') {\n this.#messenger.publish('ExecutionService:outboundResponse', snapId);\n } else if (message.method === 'UnhandledError') {\n if (isObject(message.params) && message.params.error) {\n this.#messenger.publish(\n 'ExecutionService:unhandledError',\n snapId,\n message.params.error as SnapErrorJson,\n );\n commandStream.removeListener('data', notificationHandler);\n } else {\n logError(\n new Error(\n `Received malformed \"${message.method}\" command stream notification.`,\n ),\n );\n }\n } else {\n logError(\n new Error(\n `Received unexpected command stream notification \"${message.method}\".`,\n ),\n );\n }\n };\n\n commandStream.on('data', notificationHandler);\n const rpcStream = mux.createStream(SNAP_STREAM_NAMES.JSON_RPC);\n\n // Typecast: stream type mismatch\n return {\n streams: {\n command: commandStream as unknown as Duplex,\n rpc: rpcStream,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n _connection: envStream,\n },\n worker,\n };\n }\n\n /**\n * Abstract function implemented by implementing class that spins up a new worker for a job.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n */\n protected abstract initEnvStream(jobId: string): Promise<{\n worker: WorkerType;\n stream: BasePostMessageStream;\n }>;\n\n /**\n * Terminates the Snap with the specified ID. May throw an error if\n * termination unexpectedly fails, but will not fail if no job for the snap\n * with the specified ID is found.\n *\n * @param snapId - The ID of the snap to terminate.\n */\n async terminateSnap(snapId: string) {\n const jobId = this.#snapToJobMap.get(snapId);\n if (jobId) {\n await this.terminate(jobId);\n }\n }\n\n async terminateAllSnaps() {\n await Promise.all(\n [...this.jobs.keys()].map(async (jobId) => this.terminate(jobId)),\n );\n this.#snapRpcHooks.clear();\n }\n\n /**\n * Gets the RPC request handler for the given snap.\n *\n * @param snapId - The id of the Snap whose message handler to get.\n * @returns The RPC request handler for the snap.\n */\n private getRpcRequestHandler(snapId: string) {\n return this.#snapRpcHooks.get(snapId);\n }\n\n /**\n * Initializes and executes a snap, setting up the communication channels to the snap etc.\n *\n * Depending on the execution environment, this may run forever if the Snap fails to start up properly, therefore any call to this function should be wrapped in a timeout.\n *\n * @param snapData - Data needed for Snap execution.\n * @returns A string `OK` if execution succeeded.\n * @throws If the execution service returns an error.\n */\n async executeSnap(snapData: SnapExecutionData): Promise<string> {\n if (this.#snapToJobMap.has(snapData.snapId)) {\n throw new Error(`Snap \"${snapData.snapId}\" is already being executed.`);\n }\n\n const job = await this.initJob();\n this.#mapSnapAndJob(snapData.snapId, job.id);\n\n // Ping the worker to ensure that it started up\n await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'ping',\n id: nanoid(),\n });\n\n const rpcStream = job.streams.rpc as unknown as Duplex;\n\n this.setupSnapProvider(snapData.snapId, rpcStream);\n\n const result = await this.command(job.id, {\n jsonrpc: '2.0',\n method: 'executeSnap',\n params: snapData,\n id: nanoid(),\n });\n this.#createSnapHooks(snapData.snapId, job.id);\n return result as string;\n }\n\n // Cannot be hash private yet because of tests.\n private async command(\n jobId: string,\n message: JsonRpcRequest<unknown>,\n ): Promise<unknown> {\n if (typeof message !== 'object') {\n throw new Error('Must send object.');\n }\n\n const job = this.jobs.get(jobId);\n if (!job) {\n throw new Error(`Job with id \"${jobId}\" not found.`);\n }\n\n log('Parent: Sending Command', message);\n const response: PendingJsonRpcResponse<unknown> =\n await job.rpcEngine.handle(message);\n if (response.error) {\n throw new Error(response.error.message);\n }\n return response.result;\n }\n\n #removeSnapHooks(snapId: string) {\n this.#snapRpcHooks.delete(snapId);\n }\n\n #createSnapHooks(snapId: string, workerId: string) {\n const rpcHook = async ({ origin, handler, request }: SnapRpcHookArgs) => {\n return await this.command(workerId, {\n id: nanoid(),\n jsonrpc: '2.0',\n method: 'snapRpc',\n params: {\n origin,\n handler,\n request,\n target: snapId,\n },\n });\n };\n\n this.#snapRpcHooks.set(snapId, rpcHook);\n }\n\n /**\n * Gets the job id for a given snap.\n *\n * @param snapId - A given snap id.\n * @returns The ID of the snap's job.\n */\n #getJobForSnap(snapId: string): string | undefined {\n return this.#snapToJobMap.get(snapId);\n }\n\n /**\n * Gets the snap id for a given job.\n *\n * @param jobId - A given job id.\n * @returns The ID of the snap that is running the job.\n */\n #getSnapForJob(jobId: string): string | undefined {\n return this.#jobToSnapMap.get(jobId);\n }\n\n #mapSnapAndJob(snapId: string, jobId: string): void {\n this.#snapToJobMap.set(snapId, jobId);\n this.#jobToSnapMap.set(jobId, snapId);\n }\n\n #removeSnapAndJobMapping(jobId: string): void {\n const snapId = this.#jobToSnapMap.get(jobId);\n if (!snapId) {\n throw new Error(`job: \"${jobId}\" has no mapped snap.`);\n }\n\n this.#jobToSnapMap.delete(jobId);\n this.#snapToJobMap.delete(snapId);\n this.#removeSnapHooks(snapId);\n }\n\n /**\n * Handle RPC request.\n *\n * @param snapId - The ID of the recipient snap.\n * @param options - Bag of options to pass to the RPC handler.\n * @returns Promise that can handle the request.\n */\n public async handleRpcRequest(\n snapId: string,\n options: SnapRpcHookArgs,\n ): Promise<unknown> {\n const rpcRequestHandler = await this.getRpcRequestHandler(snapId);\n\n if (!rpcRequestHandler) {\n throw new Error(\n `Snap execution service returned no RPC handler for running snap \"${snapId}\".`,\n );\n }\n\n return rpcRequestHandler(options);\n }\n}\n\n/**\n * Sets up stream multiplexing for the given stream.\n *\n * @param connectionStream - The stream to mux.\n * @param streamName - The name of the stream, for identification in errors.\n * @returns The multiplexed stream.\n */\nexport function setupMultiplex(\n connectionStream: Duplex,\n streamName: string,\n): ObjectMultiplex {\n const mux = new ObjectMultiplex();\n pump(\n connectionStream,\n // Typecast: stream type mismatch\n mux as unknown as Duplex,\n connectionStream,\n (error) => {\n if (error) {\n streamName\n ? logError(`\"${streamName}\" stream failure.`, error)\n : logError(error);\n }\n },\n );\n return mux;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ExecutionService.js","sourceRoot":"","sources":["../../src/services/ExecutionService.ts"],"names":[],"mappings":";;AAgCA,MAAM,cAAc,GAAG,kBAAkB,CAAC","sourcesContent":["import { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { SnapId, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport { Json } from '@metamask/types';\n\ntype TerminateSnap = (snapId: string) => Promise<void>;\ntype TerminateAll = () => Promise<void>;\ntype ExecuteSnap = (snapData: SnapExecutionData) => Promise<unknown>;\n\ntype HandleRpcRequest = (\n snapId: string,\n options: SnapRpcHookArgs,\n) => Promise<unknown>;\n\nexport interface ExecutionService {\n terminateSnap: TerminateSnap;\n terminateAllSnaps: TerminateAll;\n executeSnap: ExecuteSnap;\n handleRpcRequest: HandleRpcRequest;\n}\n\nexport type SnapExecutionData = {\n snapId: string;\n sourceCode: string;\n endowments?: Json;\n};\n\nexport type SnapErrorJson = {\n message: string;\n code: number;\n data?: Json;\n};\n\nconst controllerName = 'ExecutionService';\n\nexport type ErrorMessageEvent = {\n type: 'ExecutionService:unhandledError';\n payload: [SnapId, SnapErrorJson];\n};\n\nexport type OutboundRequest = {\n type: 'ExecutionService:outboundRequest';\n payload: [SnapId];\n};\n\nexport type OutboundResponse = {\n type: 'ExecutionService:outboundResponse';\n payload: [SnapId];\n};\n\nexport type ExecutionServiceEvents =\n | ErrorMessageEvent\n | OutboundRequest\n | OutboundResponse;\n\n/**\n * Handles RPC request.\n */\nexport type HandleRpcRequestAction = {\n type: `${typeof controllerName}:handleRpcRequest`;\n handler: ExecutionService['handleRpcRequest'];\n};\n\n/**\n * Executes a given snap.\n */\nexport type ExecuteSnapAction = {\n type: `${typeof controllerName}:executeSnap`;\n handler: ExecutionService['executeSnap'];\n};\n\n/**\n * Terminates a given snap.\n */\nexport type TerminateSnapAction = {\n type: `${typeof controllerName}:terminateSnap`;\n handler: ExecutionService['terminateSnap'];\n};\n\n/**\n * Terminates all snaps.\n */\nexport type TerminateAllSnapsAction = {\n type: `${typeof controllerName}:terminateAllSnaps`;\n handler: ExecutionService['terminateAllSnaps'];\n};\n\nexport type ExecutionServiceActions =\n | HandleRpcRequestAction\n | ExecuteSnapAction\n | TerminateSnapAction\n | TerminateAllSnapsAction;\n\nexport type ExecutionServiceMessenger = RestrictedControllerMessenger<\n 'ExecutionService',\n ExecutionServiceActions,\n ExecutionServiceEvents,\n ExecutionServiceActions['type'],\n ExecutionServiceEvents['type']\n>;\n"]}
|