@metamask/snaps-jest 6.0.2 → 7.0.1
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 +18 -1
- package/README.md +100 -7
- package/dist/{chunk-6RXFM4YC.js → chunk-2JAGD4N6.js} +3 -3
- package/dist/{chunk-7YD4IW43.mjs → chunk-3M4GRUMH.mjs} +3 -6
- package/dist/chunk-3M4GRUMH.mjs.map +1 -0
- package/dist/{chunk-WIFOID2P.mjs → chunk-3OEADJAL.mjs} +20 -10
- package/dist/chunk-3OEADJAL.mjs.map +1 -0
- package/dist/{chunk-7BFTEFLS.mjs → chunk-5U5WB3SM.mjs} +5 -3
- package/dist/chunk-5U5WB3SM.mjs.map +1 -0
- package/dist/chunk-7L5S3PID.js +127 -0
- package/dist/chunk-7L5S3PID.js.map +1 -0
- package/dist/{chunk-7VILST6M.mjs → chunk-BVGI3E45.mjs} +2 -2
- package/dist/chunk-CKRORVDW.js +1 -0
- package/dist/{chunk-6HW5NGCB.js → chunk-DTDYOBCI.js} +3 -3
- package/dist/{chunk-B4QZXXQY.js → chunk-FIZAYEHV.js} +4 -4
- package/dist/{chunk-T2BE4O5H.js → chunk-IDGD7TZ7.js} +33 -23
- package/dist/chunk-IDGD7TZ7.js.map +1 -0
- package/dist/chunk-KR7CYXCR.js +213 -0
- package/dist/chunk-KR7CYXCR.js.map +1 -0
- package/dist/{chunk-BS24WMRW.mjs → chunk-LG3VKXGH.mjs} +2 -2
- package/dist/{chunk-5PLDD7ZC.js → chunk-LMCG5RIX.js} +24 -14
- package/dist/chunk-LMCG5RIX.js.map +1 -0
- package/dist/{chunk-C2ONPIIB.js → chunk-MCYTJUDG.js} +10 -15
- package/dist/chunk-MCYTJUDG.js.map +1 -0
- package/dist/chunk-QPC6UJH7.mjs +213 -0
- package/dist/chunk-QPC6UJH7.mjs.map +1 -0
- package/dist/chunk-S2HLITUN.js +1 -0
- package/dist/{chunk-ISWZ7XZ5.js → chunk-SB5EPHE3.js} +5 -3
- package/dist/chunk-SB5EPHE3.js.map +1 -0
- package/dist/{chunk-HBLJOACO.mjs → chunk-TAIJXTLU.mjs} +2 -10
- package/dist/chunk-TAIJXTLU.mjs.map +1 -0
- package/dist/chunk-TGZ7WOTJ.mjs +1 -0
- package/dist/chunk-UDOXICJK.mjs +1 -0
- package/dist/{chunk-3HU56QS3.mjs → chunk-VSUNWJMQ.mjs} +8 -13
- package/dist/chunk-VSUNWJMQ.mjs.map +1 -0
- package/dist/{chunk-TO46ICOZ.js → chunk-WMLSD6B5.js} +3 -6
- package/dist/chunk-WMLSD6B5.js.map +1 -0
- package/dist/{chunk-3SNZ4SPY.mjs → chunk-X5IPMTHO.mjs} +2 -2
- package/dist/{chunk-7J34R6YW.mjs → chunk-YEVKBYKO.mjs} +35 -25
- package/dist/chunk-YEVKBYKO.mjs.map +1 -0
- package/dist/chunk-ZJVA3AOC.mjs +127 -0
- package/dist/chunk-ZJVA3AOC.mjs.map +1 -0
- package/dist/{chunk-LXSNRZV4.js → chunk-ZWN4SO2V.js} +5 -13
- package/dist/chunk-ZWN4SO2V.js.map +1 -0
- package/dist/environment.js +13 -14
- package/dist/environment.mjs +12 -13
- package/dist/global.js +2 -0
- package/dist/global.js.map +1 -0
- package/dist/global.mjs +2 -0
- package/dist/global.mjs.map +1 -0
- package/dist/helpers.js +13 -14
- package/dist/helpers.mjs +12 -13
- package/dist/index.js +16 -16
- package/dist/index.mjs +15 -15
- package/dist/internals/index.js +27 -14
- package/dist/internals/index.mjs +30 -17
- package/dist/internals/request.js +12 -11
- package/dist/internals/request.mjs +13 -12
- package/dist/internals/simulation/controllers.js +6 -7
- package/dist/internals/simulation/controllers.mjs +5 -6
- package/dist/internals/simulation/index.js +17 -10
- package/dist/internals/simulation/index.mjs +17 -10
- package/dist/internals/simulation/interface.js +11 -3
- package/dist/internals/simulation/interface.mjs +12 -4
- package/dist/internals/simulation/methods/hooks/index.js +4 -10
- package/dist/internals/simulation/methods/hooks/index.mjs +3 -9
- package/dist/internals/simulation/methods/hooks/notifications.js +1 -1
- package/dist/internals/simulation/methods/hooks/notifications.mjs +1 -1
- package/dist/internals/simulation/methods/hooks/show-dialog.js +1 -1
- package/dist/internals/simulation/methods/hooks/show-dialog.mjs +1 -1
- package/dist/internals/simulation/methods/hooks/state.js +3 -3
- package/dist/internals/simulation/methods/hooks/state.mjs +2 -2
- package/dist/internals/simulation/methods/index.js +5 -6
- package/dist/internals/simulation/methods/index.mjs +4 -5
- package/dist/internals/simulation/methods/specifications.js +5 -6
- package/dist/internals/simulation/methods/specifications.mjs +4 -5
- package/dist/internals/simulation/simulation.js +8 -9
- package/dist/internals/simulation/simulation.mjs +7 -8
- package/dist/internals/simulation/store/index.js +2 -2
- package/dist/internals/simulation/store/index.mjs +1 -1
- package/dist/internals/simulation/store/store.js +2 -2
- package/dist/internals/simulation/store/store.mjs +1 -1
- package/dist/internals/structs.js +6 -2
- package/dist/internals/structs.mjs +5 -1
- package/dist/matchers.js +13 -14
- package/dist/matchers.mjs +12 -13
- package/dist/setup.js +12 -13
- package/dist/setup.mjs +12 -13
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/global.d.ts +69 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/internals/request.d.ts +13 -4
- package/dist/types/internals/simulation/interface.d.ts +47 -4
- package/dist/types/internals/simulation/methods/hooks/index.d.ts +0 -1
- package/dist/types/internals/simulation/methods/hooks/state.d.ts +2 -1
- package/dist/types/internals/simulation/store/store.d.ts +1 -2
- package/dist/types/internals/structs.d.ts +79 -156
- package/dist/types/types.d.ts +42 -21
- package/package.json +6 -6
- package/dist/chunk-2X23DUDP.mjs +0 -22
- package/dist/chunk-2X23DUDP.mjs.map +0 -1
- package/dist/chunk-3HU56QS3.mjs.map +0 -1
- package/dist/chunk-5PLDD7ZC.js.map +0 -1
- package/dist/chunk-6MVV44M5.mjs +0 -76
- package/dist/chunk-6MVV44M5.mjs.map +0 -1
- package/dist/chunk-7BFTEFLS.mjs.map +0 -1
- package/dist/chunk-7J34R6YW.mjs.map +0 -1
- package/dist/chunk-7YD4IW43.mjs.map +0 -1
- package/dist/chunk-C2ONPIIB.js.map +0 -1
- package/dist/chunk-HBLJOACO.mjs.map +0 -1
- package/dist/chunk-HNH5UAKZ.js +0 -80
- package/dist/chunk-HNH5UAKZ.js.map +0 -1
- package/dist/chunk-ISWZ7XZ5.js.map +0 -1
- package/dist/chunk-LXSNRZV4.js.map +0 -1
- package/dist/chunk-LYK6EGZU.mjs +0 -80
- package/dist/chunk-LYK6EGZU.mjs.map +0 -1
- package/dist/chunk-RD7GQCPL.js +0 -22
- package/dist/chunk-RD7GQCPL.js.map +0 -1
- package/dist/chunk-T2BE4O5H.js.map +0 -1
- package/dist/chunk-TO46ICOZ.js.map +0 -1
- package/dist/chunk-U5BLLHIU.js +0 -1
- package/dist/chunk-V6LFAN3U.mjs +0 -1
- package/dist/chunk-WIFOID2P.mjs.map +0 -1
- package/dist/chunk-ZAQZRYPW.js +0 -76
- package/dist/chunk-ZAQZRYPW.js.map +0 -1
- package/dist/internals/simulation/methods/hooks/encryption.js +0 -10
- package/dist/internals/simulation/methods/hooks/encryption.mjs +0 -10
- package/dist/types/internals/simulation/methods/hooks/encryption.d.ts +0 -29
- /package/dist/{chunk-6RXFM4YC.js.map → chunk-2JAGD4N6.js.map} +0 -0
- /package/dist/{chunk-7VILST6M.mjs.map → chunk-BVGI3E45.mjs.map} +0 -0
- /package/dist/{chunk-U5BLLHIU.js.map → chunk-CKRORVDW.js.map} +0 -0
- /package/dist/{chunk-6HW5NGCB.js.map → chunk-DTDYOBCI.js.map} +0 -0
- /package/dist/{chunk-B4QZXXQY.js.map → chunk-FIZAYEHV.js.map} +0 -0
- /package/dist/{chunk-BS24WMRW.mjs.map → chunk-LG3VKXGH.mjs.map} +0 -0
- /package/dist/{internals/simulation/methods/hooks/encryption.js.map → chunk-S2HLITUN.js.map} +0 -0
- /package/dist/{chunk-V6LFAN3U.mjs.map → chunk-TGZ7WOTJ.mjs.map} +0 -0
- /package/dist/{internals/simulation/methods/hooks/encryption.mjs.map → chunk-UDOXICJK.mjs.map} +0 -0
- /package/dist/{chunk-3SNZ4SPY.mjs.map → chunk-X5IPMTHO.mjs.map} +0 -0
package/dist/chunk-2X23DUDP.mjs
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
// src/internals/simulation/methods/hooks/encryption.ts
|
|
2
|
-
function encryptImplementation(password, value) {
|
|
3
|
-
return JSON.stringify({
|
|
4
|
-
password,
|
|
5
|
-
value
|
|
6
|
-
});
|
|
7
|
-
}
|
|
8
|
-
function decryptImplementation(password, value) {
|
|
9
|
-
const decryptedValue = JSON.parse(value);
|
|
10
|
-
if (decryptedValue.password !== password) {
|
|
11
|
-
throw new Error(
|
|
12
|
-
"Incorrect password. This is a bug in `@metamask/snaps-jest`, please report it."
|
|
13
|
-
);
|
|
14
|
-
}
|
|
15
|
-
return decryptedValue.value;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export {
|
|
19
|
-
encryptImplementation,
|
|
20
|
-
decryptImplementation
|
|
21
|
-
};
|
|
22
|
-
//# sourceMappingURL=chunk-2X23DUDP.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/hooks/encryption.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Mocks encrypting a value using a password. This is not a real encryption\n * method, but rather is used to simulate encryption in the tests.\n *\n * Ideally we would use a real encryption method, such as\n * `@metamask/browser-passworder`, but it doesn't seem to work with Node.js 18\n * without some mocking. We can switch to a real encryption method once we\n * drop support for Node.js 18.\n *\n * @param password - The password to use.\n * @param value - The value to encrypt.\n * @returns The \"encrypted\" value.\n */\nexport function encryptImplementation(password: string, value: Json) {\n return JSON.stringify({\n password,\n value,\n });\n}\n\n/**\n * Mocks decrypting a value using a password. This is not a real encryption\n * method, but rather is used to simulate encryption in the tests.\n *\n * Ideally we would use a real decryption method, such as\n * `@metamask/browser-passworder`, but it doesn't seem to work with Node.js 18\n * without some mocking. We can switch to a real encryption method once we\n * drop support for Node.js 18.\n *\n * @param password - The password to use.\n * @param value - The value to decrypt.\n * @returns The \"decrypted\" value.\n */\nexport function decryptImplementation(password: string, value: string) {\n const decryptedValue = JSON.parse(value);\n if (decryptedValue.password !== password) {\n throw new Error(\n 'Incorrect password. This is a bug in `@metamask/snaps-jest`, please report it.',\n );\n }\n\n return decryptedValue.value;\n}\n"],"mappings":";AAeO,SAAS,sBAAsB,UAAkB,OAAa;AACnE,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAeO,SAAS,sBAAsB,UAAkB,OAAe;AACrE,QAAM,iBAAiB,KAAK,MAAM,KAAK;AACvC,MAAI,eAAe,aAAa,UAAU;AACxC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,eAAe;AACxB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/simulation.ts"],"sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport { ControllerMessenger } from '@metamask/base-controller';\nimport { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport { mnemonicPhraseToBytes } from '@metamask/key-tree';\nimport type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n fetchSnap,\n detectSnapLocation,\n NodeThreadExecutionService,\n setupMultiplex,\n} from '@metamask/snaps-controllers/node';\nimport { getEncryptionKey } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapId,\n AuxiliaryFileEncoding,\n Component,\n InterfaceState,\n} from '@metamask/snaps-sdk';\nimport type { FetchedSnapFiles } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getControllers, registerSnap } from './controllers';\nimport { getSnapFile } from './files';\nimport { getEndowments } from './methods';\nimport { createJsonRpcEngine } from './middleware';\nimport type { SimulationOptions, SimulationUserOptions } from './options';\nimport { getOptions } from './options';\nimport type { RunSagaFunction, Store } from './store';\nimport { createStore } from './store';\n\n/**\n * Options for the execution service, without the options that are shared\n * between all execution services.\n *\n * @template Service - The type of the execution service, i.e., the class that\n * creates the execution service.\n */\nexport type ExecutionServiceOptions<\n Service extends new (...args: any[]) => any,\n> = Omit<\n ConstructorParameters<Service>[0],\n keyof ConstructorParameters<typeof AbstractExecutionService<unknown>>[0]\n>;\n\n/**\n * The options for running a Snap in a simulated environment.\n *\n * @property executionService - The execution service to use.\n * @property executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @property options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport type InstallSnapOptions<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService<unknown>\n >,\n> = ExecutionServiceOptions<Service> extends Record<string, never>\n ? {\n executionService: Service;\n executionServiceOptions?: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n }\n : {\n executionService: Service;\n executionServiceOptions: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n };\n\nexport type InstalledSnap = {\n snapId: SnapId;\n store: Store;\n executionService: InstanceType<typeof AbstractExecutionService>;\n controllerMessenger: ControllerMessenger<ActionConstraint, EventConstraint>;\n runSaga: RunSagaFunction;\n};\n\nexport type MiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * A hook that returns the Snap's auxiliary file for the given path.\n *\n * @param path - The path of the auxiliary file to get.\n * @param encoding - The encoding to use when returning the file.\n * @returns The Snap's auxiliary file for the given path.\n */\n getSnapFile: (\n path: string,\n encoding: AuxiliaryFileEncoding,\n ) => Promise<string | null>;\n\n /**\n * A hook that returns whether the client is locked or not.\n *\n * @returns A boolean flag signaling whether the client is locked.\n */\n getIsLocked: () => boolean;\n createInterface: (content: Component) => Promise<string>;\n updateInterface: (id: string, content: Component) => Promise<void>;\n getInterfaceState: (id: string) => InterfaceState;\n};\n\n/**\n * Install a Snap in a simulated environment. This will fetch the Snap files,\n * create a Redux store, set up the controllers and JSON-RPC stack, register the\n * Snap, and run the Snap code in the execution service.\n *\n * @param snapId - The ID of the Snap to install.\n * @param options - The options to use when installing the Snap.\n * @param options.executionService - The execution service to use.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport async function handleInstallSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId,\n {\n executionService,\n executionServiceOptions,\n options: rawOptions = {},\n }: Partial<InstallSnapOptions<Service>> = {},\n): Promise<InstalledSnap> {\n const options = getOptions(rawOptions);\n\n // Fetch Snap files.\n const location = detectSnapLocation(snapId, {\n allowLocal: true,\n });\n\n const snapFiles = await fetchSnap(snapId, location);\n\n // Create Redux store.\n const password = await getEncryptionKey({\n mnemonicPhrase: mnemonicPhraseToBytes(options.secretRecoveryPhrase),\n snapId,\n });\n\n const { store, runSaga } = createStore(password, options);\n\n const controllerMessenger = new ControllerMessenger<any, any>();\n\n registerActions(controllerMessenger);\n\n // Set up controllers and JSON-RPC stack.\n const hooks = getHooks(options, snapFiles, snapId, controllerMessenger);\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n store,\n hooks,\n permissionMiddleware: permissionController.createPermissionMiddleware({\n origin: snapId,\n }),\n });\n\n // Create execution service.\n const ExecutionService = executionService ?? NodeThreadExecutionService;\n const service = new ExecutionService({\n ...executionServiceOptions,\n messenger: controllerMessenger.getRestricted({\n name: 'ExecutionService',\n allowedActions: [],\n allowedEvents: [],\n }),\n setupSnapProvider: (_snapId: string, rpcStream: Duplex) => {\n const mux = setupMultiplex(rpcStream, 'snapStream');\n const stream = mux.createStream('metamask-provider');\n const providerStream = createEngineStream({ engine });\n\n // Error function is difficult to test, so we ignore it.\n /* istanbul ignore next 2 */\n pipeline(stream, providerStream, stream, (error: unknown) => {\n if (error) {\n logError(`Provider stream failure.`, error);\n }\n });\n },\n });\n\n // Register the Snap. This sets up the Snap's permissions and subject\n // metadata.\n await registerSnap(snapId, snapFiles.manifest.result, {\n permissionController,\n subjectMetadataController,\n });\n\n // Run the Snap code in the execution service.\n await service.executeSnap({\n snapId,\n sourceCode: snapFiles.sourceCode.toString('utf8'),\n endowments: await getEndowments(permissionController, snapId),\n });\n\n return {\n snapId,\n store,\n executionService: service,\n controllerMessenger,\n runSaga,\n };\n}\n\n/**\n * Get the hooks for the simulation.\n *\n * @param options - The simulation options.\n * @param snapFiles - The Snap files.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The hooks for the simulation.\n */\nexport function getHooks(\n options: SimulationOptions,\n snapFiles: FetchedSnapFiles,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): MiddlewareHooks {\n return {\n getMnemonic: async () =>\n Promise.resolve(mnemonicPhraseToBytes(options.secretRecoveryPhrase)),\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n getIsLocked: () => false,\n createInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n ...args,\n ),\n updateInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:updateInterface',\n snapId,\n ...args,\n ),\n getInterfaceState: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n ...args,\n ).state,\n };\n}\n\n/**\n * Register mocked action handlers.\n *\n * @param controllerMessenger - The controller messenger.\n */\nexport function registerActions(controllerMessenger: RootControllerMessenger) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:maybeUpdateState',\n async () => Promise.resolve(),\n );\n\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: 'all' }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC,SAAS,6BAA6B;AAEtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB;AAQjC,SAAS,gBAAgB;AAEzB,SAAS,gBAAgB;AAyGzB,eAAsB,kBAKpB,QACA;AAAA,EACE;AAAA,EACA;AAAA,EACA,SAAS,aAAa,CAAC;AACzB,IAA0C,CAAC,GACnB;AACxB,QAAM,UAAU,WAAW,UAAU;AAGrC,QAAM,WAAW,mBAAmB,QAAQ;AAAA,IAC1C,YAAY;AAAA,EACd,CAAC;AAED,QAAM,YAAY,MAAM,UAAU,QAAQ,QAAQ;AAGlD,QAAM,WAAW,MAAM,iBAAiB;AAAA,IACtC,gBAAgB,sBAAsB,QAAQ,oBAAoB;AAAA,IAClE;AAAA,EACF,CAAC;AAED,QAAM,EAAE,OAAO,QAAQ,IAAI,YAAY,UAAU,OAAO;AAExD,QAAM,sBAAsB,IAAI,oBAA8B;AAE9D,kBAAgB,mBAAmB;AAGnC,QAAM,QAAQ,SAAS,SAAS,WAAW,QAAQ,mBAAmB;AAEtE,QAAM,EAAE,2BAA2B,qBAAqB,IAAI,eAAe;AAAA,IACzE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,QAAM,SAAS,oBAAoB;AAAA,IACjC;AAAA,IACA;AAAA,IACA,sBAAsB,qBAAqB,2BAA2B;AAAA,MACpE,QAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AAGD,QAAM,mBAAmB,oBAAoB;AAC7C,QAAM,UAAU,IAAI,iBAAiB;AAAA,IACnC,GAAG;AAAA,IACH,WAAW,oBAAoB,cAAc;AAAA,MAC3C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B,MAAM,CAAC;AAAA,QAC1C;AAAA,MACF;AAAA,IACF;AAAA,IAEA,OAAO,YAAY;AACjB,UAAI,4BAA4B;AAChC;AAAA,QACE;AAAA,MACF;AAEA,YAAM,iBAAiB,kBAAkB;AAAA,IAC3C;AAAA,EACF;AACF","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType, logInfo } from '@metamask/snaps-utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { create } from 'superstruct';\n\nimport {\n rootLogger,\n handleRequest,\n TransactionOptionsStruct,\n getEnvironment,\n JsonRpcMockOptionsStruct,\n SignatureOptionsStruct,\n} from './internals';\nimport type { InstallSnapOptions } from './internals';\nimport {\n addJsonRpcMock,\n removeJsonRpcMock,\n} from './internals/simulation/store/mocks';\nimport type {\n CronjobOptions,\n JsonRpcMockOptions,\n Snap,\n SnapResponse,\n TransactionOptions,\n} from './types';\n\nconst log = createModuleLogger(rootLogger, 'helpers');\n\n/**\n * Get the options for {@link installSnap}.\n *\n * @param snapId - The ID of the Snap, or the options.\n * @param options - The options, if any.\n * @returns The options.\n */\nfunction getOptions<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId | Partial<InstallSnapOptions<Service>> | undefined,\n options: Partial<InstallSnapOptions<Service>>,\n): [SnapId | undefined, Partial<InstallSnapOptions<Service>>] {\n if (typeof snapId === 'object') {\n return [undefined, snapId];\n }\n\n return [snapId, options];\n}\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap(): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(options: Partial<InstallSnapOptions<Service>>): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param snapId - The ID of the snap, including the prefix (`local:`). Defaults\n * to the URL of the built-in server, if it is running. This supports both\n * local snap IDs and NPM snap IDs.\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId,\n options?: Partial<InstallSnapOptions<Service>>,\n): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param snapId - The ID of the snap, including the prefix (`local:`). Defaults\n * to the URL of the built-in server, if it is running. This supports both\n * local snap IDs and NPM snap IDs.\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId?: SnapId | Partial<InstallSnapOptions<Service>>,\n options: Partial<InstallSnapOptions<Service>> = {},\n): Promise<Snap> {\n const resolvedOptions = getOptions(snapId, options);\n const {\n snapId: installedSnapId,\n store,\n executionService,\n runSaga,\n controllerMessenger,\n } = await getEnvironment().installSnap(...resolvedOptions);\n\n const onTransaction = async (\n request: TransactionOptions,\n ): Promise<SnapResponse> => {\n log('Sending transaction %o.', request);\n\n const {\n origin: transactionOrigin,\n chainId,\n ...transaction\n } = create(request, TransactionOptionsStruct);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n runSaga,\n controllerMessenger,\n handler: HandlerType.OnTransaction,\n request: {\n method: '',\n params: {\n chainId,\n transaction,\n transactionOrigin,\n },\n },\n });\n };\n\n const onCronjob = (request: CronjobOptions) => {\n log('Running cronjob %o.', options);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnCronjob,\n request,\n });\n };\n\n return {\n request: (request) => {\n log('Sending request %o.', request);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnRpcRequest,\n request,\n });\n },\n\n onTransaction,\n sendTransaction: onTransaction,\n\n onSignature: async (request: unknown): Promise<SnapResponse> => {\n log('Requesting signature %o.', request);\n\n const { origin: signatureOrigin, ...signature } = create(\n request,\n SignatureOptionsStruct,\n );\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnSignature,\n request: {\n method: '',\n params: {\n signature,\n signatureOrigin,\n },\n },\n });\n },\n\n onCronjob,\n runCronjob: onCronjob,\n\n onHomePage: async (): Promise<SnapResponse> => {\n log('Rendering home page.');\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnHomePage,\n request: {\n method: '',\n },\n });\n },\n\n mockJsonRpc(mock: JsonRpcMockOptions) {\n log('Mocking JSON-RPC request %o.', mock);\n\n const { method, result } = create(mock, JsonRpcMockOptionsStruct);\n store.dispatch(addJsonRpcMock({ method, result }));\n\n return {\n unmock() {\n log('Unmocking JSON-RPC request %o.', mock);\n\n store.dispatch(removeJsonRpcMock(method));\n },\n };\n },\n\n close: async () => {\n log('Closing execution service.');\n logInfo(\n 'Calling `snap.close()` is deprecated, and will be removed in a future release. Snaps are now automatically closed when the test ends.',\n );\n\n await executionService.terminateAllSnaps();\n },\n };\n}\n"]}
|
package/dist/chunk-6MVV44M5.mjs
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
getCurrentInterface,
|
|
3
|
-
resolveInterface,
|
|
4
|
-
setInterface
|
|
5
|
-
} from "./chunk-74TIKA2T.mjs";
|
|
6
|
-
|
|
7
|
-
// src/internals/simulation/interface.ts
|
|
8
|
-
import { DialogType } from "@metamask/snaps-sdk";
|
|
9
|
-
import { put, select, take } from "redux-saga/effects";
|
|
10
|
-
function getInterfaceResponse(runSaga, type, content) {
|
|
11
|
-
switch (type) {
|
|
12
|
-
case DialogType.Alert:
|
|
13
|
-
return {
|
|
14
|
-
type,
|
|
15
|
-
content,
|
|
16
|
-
ok: resolveWith(runSaga, null)
|
|
17
|
-
};
|
|
18
|
-
case DialogType.Confirmation:
|
|
19
|
-
return {
|
|
20
|
-
type,
|
|
21
|
-
content,
|
|
22
|
-
ok: resolveWith(runSaga, true),
|
|
23
|
-
cancel: resolveWith(runSaga, false)
|
|
24
|
-
};
|
|
25
|
-
case DialogType.Prompt:
|
|
26
|
-
return {
|
|
27
|
-
type,
|
|
28
|
-
content,
|
|
29
|
-
ok: resolveWithInput(runSaga),
|
|
30
|
-
cancel: resolveWith(runSaga, null)
|
|
31
|
-
};
|
|
32
|
-
default:
|
|
33
|
-
throw new Error(`Unknown or unsupported dialog type: "${String(type)}".`);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
function resolveWith(runSaga, value) {
|
|
37
|
-
function* resolveWithSaga() {
|
|
38
|
-
yield put(resolveInterface(value));
|
|
39
|
-
}
|
|
40
|
-
return async () => {
|
|
41
|
-
await runSaga(resolveWithSaga).toPromise();
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
function resolveWithInput(runSaga) {
|
|
45
|
-
function* resolveWithSaga(value) {
|
|
46
|
-
yield put(resolveInterface(value));
|
|
47
|
-
}
|
|
48
|
-
return async (value = "") => {
|
|
49
|
-
await runSaga(resolveWithSaga, value).toPromise();
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
function* getInterface(runSaga, snapId, controllerMessenger) {
|
|
53
|
-
const currentInterface = yield select(getCurrentInterface);
|
|
54
|
-
if (currentInterface) {
|
|
55
|
-
const { content: content2 } = controllerMessenger.call(
|
|
56
|
-
"SnapInterfaceController:getInterface",
|
|
57
|
-
snapId,
|
|
58
|
-
currentInterface.id
|
|
59
|
-
);
|
|
60
|
-
return getInterfaceResponse(runSaga, currentInterface.type, content2);
|
|
61
|
-
}
|
|
62
|
-
const { payload } = yield take(setInterface.type);
|
|
63
|
-
const { type, id } = payload;
|
|
64
|
-
const { content } = controllerMessenger.call(
|
|
65
|
-
"SnapInterfaceController:getInterface",
|
|
66
|
-
snapId,
|
|
67
|
-
id
|
|
68
|
-
);
|
|
69
|
-
return getInterfaceResponse(runSaga, type, content);
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
export {
|
|
73
|
-
getInterfaceResponse,
|
|
74
|
-
getInterface
|
|
75
|
-
};
|
|
76
|
-
//# sourceMappingURL=chunk-6MVV44M5.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/interface.ts"],"sourcesContent":["import type { Component, SnapId } from '@metamask/snaps-sdk';\nimport { DialogType } from '@metamask/snaps-sdk';\nimport type { PayloadAction } from '@reduxjs/toolkit';\nimport type { SagaIterator } from 'redux-saga';\nimport { put, select, take } from 'redux-saga/effects';\n\nimport type { SnapInterface } from '../../types';\nimport type { RootControllerMessenger } from './controllers';\nimport type { Interface, RunSagaFunction } from './store';\nimport { getCurrentInterface, resolveInterface, setInterface } from './store';\n\n/**\n * Get a user interface object from a type and content object.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param type - The type of the interface.\n * @param content - The content to show in the interface.\n * @returns The user interface object.\n */\nexport function getInterfaceResponse(\n runSaga: RunSagaFunction,\n type: DialogType,\n content: Component,\n): SnapInterface {\n switch (type) {\n case DialogType.Alert:\n return {\n type,\n content,\n ok: resolveWith(runSaga, null),\n };\n\n case DialogType.Confirmation:\n return {\n type,\n content,\n\n ok: resolveWith(runSaga, true),\n cancel: resolveWith(runSaga, false),\n };\n\n case DialogType.Prompt:\n return {\n type,\n content,\n\n ok: resolveWithInput(runSaga),\n cancel: resolveWith(runSaga, null),\n };\n\n default:\n throw new Error(`Unknown or unsupported dialog type: \"${String(type)}\".`);\n }\n}\n\n/**\n * Resolve the current user interface with the given value. This returns a\n * function that can be used to resolve the user interface.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param value - The value to resolve the user interface with.\n * @returns A function that can be used to resolve the user interface.\n */\nfunction resolveWith(runSaga: RunSagaFunction, value: unknown) {\n /**\n * Resolve the current user interface with the given value.\n *\n * @yields Puts the resolve user interface action.\n */\n function* resolveWithSaga(): SagaIterator {\n yield put(resolveInterface(value));\n }\n\n return async () => {\n await runSaga(resolveWithSaga).toPromise();\n };\n}\n\n/**\n * Resolve the current user interface with the provided input. This returns a\n * function that can be used to resolve the user interface.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @returns A function that can be used to resolve the user interface.\n */\nfunction resolveWithInput(runSaga: RunSagaFunction) {\n /**\n * Resolve the current user interface with the given value.\n *\n * @param value - The value to resolve the user interface with.\n * @yields Puts the resolve user interface action.\n */\n function* resolveWithSaga(value: string): SagaIterator {\n yield put(resolveInterface(value));\n }\n\n return async (value = '') => {\n await runSaga(resolveWithSaga, value).toPromise();\n };\n}\n\n/**\n * Get a user interface object from a Snap.\n *\n * @param runSaga - A function to run a saga outside the usual Redux flow.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger used to call actions.\n * @yields Takes the set interface action.\n * @returns The user interface object.\n */\nexport function* getInterface(\n runSaga: RunSagaFunction,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): SagaIterator<SnapInterface> {\n const currentInterface: Interface | null = yield select(getCurrentInterface);\n if (currentInterface) {\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n currentInterface.id,\n );\n return getInterfaceResponse(runSaga, currentInterface.type, content);\n }\n\n const { payload }: PayloadAction<Interface> = yield take(setInterface.type);\n const { type, id } = payload;\n\n const { content } = controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n id,\n );\n\n return getInterfaceResponse(runSaga, type, content);\n}\n"],"mapp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AAM,EAAE,QAAQ,IAA8B,MAAM,KAAK,aAAa,IAAI;AAC1E,QAAM,EAAE,MAAM,GAAG,IAAI;AAErB,QAAM,EAAE,QAAQ,IAAI,oBAAoB;AAAA,IACtC;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,qBAAqB,SAAS,MAAM,OAAO;AACpD;","names":["content"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/hooks/state.ts"],"sourcesContent":["import type { SagaIterator } from 'redux-saga';\nimport { put, select } from 'redux-saga/effects';\n\nimport type { RunSagaFunction } from '../../store';\nimport { clearState, getState, setState } from '../../store';\n\n/**\n * Get the Snap state from the store.\n *\n * @param _snapId - The ID of the Snap to get the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to get the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @returns The state of the Snap.\n * @yields Selects the state from the store.\n */\nfunction* getSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<string> {\n return yield select(getState(encrypted));\n}\n\n/**\n * Get the implementation of the `getSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `getSnapState` hook.\n */\nexport function getGetSnapStateMethodImplementation(runSaga: RunSagaFunction) {\n return (...args: Parameters<typeof getSnapStateImplementation>) => {\n return runSaga(getSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Update the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to update the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param newState - The new state.\n * @param encrypted - Whether to update the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* updateSnapStateImplementation(\n _snapId: string,\n newState: string,\n encrypted = true,\n): SagaIterator<void> {\n yield put(setState({ state: newState, encrypted }));\n}\n\n/**\n * Get the implementation of the `updateSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `updateSnapState` hook.\n */\nexport function getUpdateSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return (...args: Parameters<typeof updateSnapStateImplementation>) => {\n runSaga(updateSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Clear the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to clear the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to clear the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* clearSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<void> {\n yield put(clearState({ encrypted }));\n}\n\n/**\n * Get the implementation of the `clearSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `clearSnapState` hook.\n */\nexport function getClearSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return async (...args: Parameters<typeof clearSnapStateImplementation>) => {\n runSaga(clearSnapStateImplementation, ...args).result();\n };\n}\n"],"mappings":";;;;;;;AACA,SAAS,KAAK,cAAc;AAe5B,UAAU,2BACR,SACA,YAAY,MACU;AACtB,SAAO,MAAM,OAAO,SAAS,SAAS,CAAC;AACzC;AAQO,SAAS,oCAAoC,SAA0B;AAC5E,SAAO,IAAI,SAAwD;AACjE,WAAO,QAAQ,4BAA4B,GAAG,IAAI,EAAE,OAAO;AAAA,EAC7D;AACF;AAYA,UAAU,8BACR,SACA,UACA,YAAY,MACQ;AACpB,QAAM,IAAI,SAAS,EAAE,OAAO,UAAU,UAAU,CAAC,CAAC;AACpD;AAQO,SAAS,uCACd,SACA;AACA,SAAO,IAAI,SAA2D;AACpE,YAAQ,+BAA+B,GAAG,IAAI,EAAE,OAAO;AAAA,EACzD;AACF;AAWA,UAAU,6BACR,SACA,YAAY,MACQ;AACpB,QAAM,IAAI,WAAW,EAAE,UAAU,CAAC,CAAC;AACrC;AAQO,SAAS,sCACd,SACA;AACA,SAAO,UAAU,SAA0D;AACzE,YAAQ,8BAA8B,GAAG,IAAI,EAAE,OAAO;AAAA,EACxD;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/structs.ts"],"sourcesContent":["import {\n NotificationType,\n ComponentStruct,\n enumValue,\n} from '@metamask/snaps-sdk';\nimport {\n bytesToHex,\n JsonStruct,\n StrictHexStruct,\n valueToBytes,\n} from '@metamask/utils';\nimport { randomBytes } from 'crypto';\nimport {\n array,\n assign,\n bigint,\n coerce,\n defaulted,\n instance,\n literal,\n number,\n object,\n optional,\n string,\n type,\n union,\n record,\n any,\n} from 'superstruct';\n\n// TODO: Export this from `@metamask/utils` instead.\nconst BytesLikeStruct = union([\n bigint(),\n number(),\n string(),\n instance(Uint8Array),\n]);\n\nexport const TransactionOptionsStruct = object({\n /**\n * The CAIP-2 chain ID to send the transaction on. Defaults to `eip155:1`.\n */\n chainId: defaulted(string(), 'eip155:1'),\n\n /**\n * The origin to send the transaction from. Defaults to `metamask.io`.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address to send the transaction from. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The address to send the transaction to. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n to: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The value to send with the transaction. The value may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n value: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x0',\n ),\n\n /**\n * The gas limit to use for the transaction. The gas limit may be specified\n * as a `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `21_000`.\n */\n gasLimit: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(21_000),\n ),\n\n /**\n * The max fee per gas (in Wei) to use for the transaction. The max fee per\n * gas may be specified as a `number`, `bigint`, `string`, or `Uint8Array`.\n * Defaults to `1`.\n */\n maxFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The max priority fee per gas (in Wei) to use for the transaction. The max\n * priority fee per gas may be specified as a `number`, `bigint`, `string`,\n * or `Uint8Array`. Defaults to `1`.\n */\n maxPriorityFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The nonce to use for the transaction. The nonce may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n nonce: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(0),\n ),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0x`.\n */\n data: defaulted(\n coerce(union([StrictHexStruct, literal('0x')]), BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x',\n ),\n});\n\nexport const SignatureOptionsStruct = object({\n /**\n * The origin making the signature request.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address signing the signature request. Defaults to a randomly generated\n * address.\n */\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `string`, an object, or an array of objects. This covers the data types\n * for the supported signature methods. Defaults to `0x`.\n */\n data: defaulted(\n union([\n StrictHexStruct,\n literal('0x'),\n record(string(), any()),\n array(record(string(), any())),\n ]),\n '0x',\n ),\n\n /**\n * The signature method being used.\n */\n signatureMethod: defaulted(\n union([\n literal('eth_sign'),\n literal('personal_sign'),\n literal('eth_signTypedData'),\n literal('eth_signTypedData_v3'),\n literal('eth_signTypedData_v4'),\n ]),\n 'personal_sign',\n ),\n});\n\nexport const SnapOptionsStruct = object({\n /**\n * The timeout in milliseconds to use for requests to the snap. Defaults to\n * `1000`.\n */\n timeout: defaulted(optional(number()), 1000),\n});\n\nexport const JsonRpcMockOptionsStruct = object({\n method: string(),\n result: JsonStruct,\n});\n\nexport const InterfaceStruct = type({\n content: optional(ComponentStruct),\n});\n\nexport const SnapResponseStruct = assign(\n InterfaceStruct,\n object({\n id: string(),\n\n response: union([\n object({\n result: JsonStruct,\n }),\n object({\n error: JsonStruct,\n }),\n ]),\n\n notifications: array(\n object({\n id: string(),\n message: string(),\n type: union([\n enumValue(NotificationType.InApp),\n enumValue(NotificationType.Native),\n ]),\n }),\n ),\n }),\n);\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,IAAM,kBAAkB,MAAM;AAAA,EAC5B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,SAAS,UAAU;AACrB,CAAC;AAEM,IAAM,2BAA2B,OAAO;AAAA;AAAA;AAAA;AAAA,EAI7C,SAAS,UAAU,OAAO,GAAG,UAAU;AAAA;AAAA;AAAA;AAAA,EAKvC,QAAQ,UAAU,OAAO,GAAG,aAAa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AAO;AAAA,EACf,QAAQ;AACV,CAAC;AAEM,IAAM,kBAAkB,KAAK;AAAA,EAClC,SAAS,SAAS,eAAe;AACnC,CAAC;AAEM,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA,OAAO;AAAA,IACL,IAAI,OAAO;AAAA,IAEX,UAAU,MAAM;AAAA,MACd,OAAO;AAAA,QACL,QAAQ;AAAA,MACV,CAAC;AAAA,MACD,OAAO;AAAA,QACL,OAAO;AAAA,MACT,CAAC;AAAA,IACH,CAAC;AAAA,IAED,eAAe;AAAA,MACb,OAAO;AAAA,QACL,IAAI,OAAO;AAAA,QACX,SAAS,OAAO;AAAA,QAChB,MAAM,MAAM;AAAA,UACV,UAAU,iBAAiB,KAAK;AAAA,UAChC,UAAU,iBAAiB,MAAM;AAAA,QACnC,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/store/store.ts"],"sourcesContent":["import { configureStore } from '@reduxjs/toolkit';\nimport createSagaMiddleware from 'redux-saga';\n\nimport type { SimulationOptions } from '../options';\nimport { mocksSlice } from './mocks';\nimport { notificationsSlice } from './notifications';\nimport { setState, stateSlice } from './state';\nimport { uiSlice } from './ui';\n\n/**\n * Create a Redux store.\n *\n * @param password - The password to use for state encryption.\n * @param options - The simulation options.\n * @param options.state - The initial state for the Snap.\n * @param options.unencryptedState - The initial unencrypted state for the Snap.\n * @returns A Redux store with the default state.\n */\nexport function createStore(\n password: string,\n { state, unencryptedState }: SimulationOptions,\n) {\n const sagaMiddleware = createSagaMiddleware();\n const store = configureStore({\n reducer: {\n mocks: mocksSlice.reducer,\n notifications: notificationsSlice.reducer,\n state: stateSlice.reducer,\n ui: uiSlice.reducer,\n },\n middleware: (getDefaultMiddleware) =>\n getDefaultMiddleware({ thunk: false }).concat(sagaMiddleware),\n });\n\n // Set initial state for the Snap.\n if (state) {\n store.dispatch(\n setState({\n state: JSON.stringify({\n password,\n value: state,\n }),\n encrypted: true,\n }),\n );\n }\n\n if (unencryptedState) {\n store.dispatch(\n setState({\n state: JSON.stringify(unencryptedState),\n encrypted: false,\n }),\n );\n }\n\n return {\n store,\n runSaga: sagaMiddleware.run.bind(sagaMiddleware),\n };\n}\n\nexport type Store = ReturnType<typeof createStore>['store'];\nexport type ApplicationState = ReturnType<Store['getState']>;\nexport type RunSagaFunction = ReturnType<typeof createStore>['runSaga'];\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;AAC/B,OAAO,0BAA0B;AAiB1B,SAAS,YACd,UACA,EAAE,OAAO,iBAAiB,GAC1B;AACA,QAAM,iBAAiB,qBAAqB;AAC5C,QAAM,QAAQ,eAAe;AAAA,IAC3B,SAAS;AAAA,MACP,OAAO,WAAW;AAAA,MAClB,eAAe,mBAAmB;AAAA,MAClC,OAAO,WAAW;AAAA,MAClB,IAAI,QAAQ;AAAA,IACd;AAAA,IACA,YAAY,CAAC,yBACX,qBAAqB,EAAE,OAAO,MAAM,CAAC,EAAE,OAAO,cAAc;AAAA,EAChE,CAAC;AAGD,MAAI,OAAO;AACT,UAAM;AAAA,MACJ,SAAS;AAAA,QACP,OAAO,KAAK,UAAU;AAAA,UACpB;AAAA,UACA,OAAO;AAAA,QACT,CAAC;AAAA,QACD,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,MAAI,kBAAkB;AACpB,UAAM;AAAA,MACJ,SAAS;AAAA,QACP,OAAO,KAAK,UAAU,gBAAgB;AAAA,QACtC,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS,eAAe,IAAI,KAAK,cAAc;AAAA,EACjD;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/simulation.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,2BA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C;AACF","sourcesContent":["import type {\n ActionConstraint,\n EventConstraint,\n} from '@metamask/base-controller';\nimport { ControllerMessenger } from '@metamask/base-controller';\nimport { createEngineStream } from '@metamask/json-rpc-middleware-stream';\nimport { mnemonicPhraseToBytes } from '@metamask/key-tree';\nimport type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport {\n fetchSnap,\n detectSnapLocation,\n NodeThreadExecutionService,\n setupMultiplex,\n} from '@metamask/snaps-controllers/node';\nimport { getEncryptionKey } from '@metamask/snaps-rpc-methods';\nimport type {\n SnapId,\n AuxiliaryFileEncoding,\n Component,\n InterfaceState,\n} from '@metamask/snaps-sdk';\nimport type { FetchedSnapFiles } from '@metamask/snaps-utils';\nimport { logError } from '@metamask/snaps-utils';\nimport type { Duplex } from 'readable-stream';\nimport { pipeline } from 'readable-stream';\n\nimport type { RootControllerMessenger } from './controllers';\nimport { getControllers, registerSnap } from './controllers';\nimport { getSnapFile } from './files';\nimport { getEndowments } from './methods';\nimport { createJsonRpcEngine } from './middleware';\nimport type { SimulationOptions, SimulationUserOptions } from './options';\nimport { getOptions } from './options';\nimport type { RunSagaFunction, Store } from './store';\nimport { createStore } from './store';\n\n/**\n * Options for the execution service, without the options that are shared\n * between all execution services.\n *\n * @template Service - The type of the execution service, i.e., the class that\n * creates the execution service.\n */\nexport type ExecutionServiceOptions<\n Service extends new (...args: any[]) => any,\n> = Omit<\n ConstructorParameters<Service>[0],\n keyof ConstructorParameters<typeof AbstractExecutionService<unknown>>[0]\n>;\n\n/**\n * The options for running a Snap in a simulated environment.\n *\n * @property executionService - The execution service to use.\n * @property executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @property options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport type InstallSnapOptions<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService<unknown>\n >,\n> = ExecutionServiceOptions<Service> extends Record<string, never>\n ? {\n executionService: Service;\n executionServiceOptions?: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n }\n : {\n executionService: Service;\n executionServiceOptions: ExecutionServiceOptions<Service>;\n options?: SimulationUserOptions;\n };\n\nexport type InstalledSnap = {\n snapId: SnapId;\n store: Store;\n executionService: InstanceType<typeof AbstractExecutionService>;\n controllerMessenger: ControllerMessenger<ActionConstraint, EventConstraint>;\n runSaga: RunSagaFunction;\n};\n\nexport type MiddlewareHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * A hook that returns the Snap's auxiliary file for the given path.\n *\n * @param path - The path of the auxiliary file to get.\n * @param encoding - The encoding to use when returning the file.\n * @returns The Snap's auxiliary file for the given path.\n */\n getSnapFile: (\n path: string,\n encoding: AuxiliaryFileEncoding,\n ) => Promise<string | null>;\n\n /**\n * A hook that returns whether the client is locked or not.\n *\n * @returns A boolean flag signaling whether the client is locked.\n */\n getIsLocked: () => boolean;\n createInterface: (content: Component) => Promise<string>;\n updateInterface: (id: string, content: Component) => Promise<void>;\n getInterfaceState: (id: string) => InterfaceState;\n};\n\n/**\n * Install a Snap in a simulated environment. This will fetch the Snap files,\n * create a Redux store, set up the controllers and JSON-RPC stack, register the\n * Snap, and run the Snap code in the execution service.\n *\n * @param snapId - The ID of the Snap to install.\n * @param options - The options to use when installing the Snap.\n * @param options.executionService - The execution service to use.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @template Service - The type of the execution service.\n */\nexport async function handleInstallSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId,\n {\n executionService,\n executionServiceOptions,\n options: rawOptions = {},\n }: Partial<InstallSnapOptions<Service>> = {},\n): Promise<InstalledSnap> {\n const options = getOptions(rawOptions);\n\n // Fetch Snap files.\n const location = detectSnapLocation(snapId, {\n allowLocal: true,\n });\n\n const snapFiles = await fetchSnap(snapId, location);\n\n // Create Redux store.\n const password = await getEncryptionKey({\n mnemonicPhrase: mnemonicPhraseToBytes(options.secretRecoveryPhrase),\n snapId,\n });\n\n const { store, runSaga } = createStore(password, options);\n\n const controllerMessenger = new ControllerMessenger<any, any>();\n\n registerActions(controllerMessenger);\n\n // Set up controllers and JSON-RPC stack.\n const hooks = getHooks(options, snapFiles, snapId, controllerMessenger);\n\n const { subjectMetadataController, permissionController } = getControllers({\n controllerMessenger,\n hooks,\n runSaga,\n options,\n });\n\n const engine = createJsonRpcEngine({\n store,\n hooks,\n permissionMiddleware: permissionController.createPermissionMiddleware({\n origin: snapId,\n }),\n });\n\n // Create execution service.\n const ExecutionService = executionService ?? NodeThreadExecutionService;\n const service = new ExecutionService({\n ...executionServiceOptions,\n messenger: controllerMessenger.getRestricted({\n name: 'ExecutionService',\n allowedActions: [],\n allowedEvents: [],\n }),\n setupSnapProvider: (_snapId: string, rpcStream: Duplex) => {\n const mux = setupMultiplex(rpcStream, 'snapStream');\n const stream = mux.createStream('metamask-provider');\n const providerStream = createEngineStream({ engine });\n\n // Error function is difficult to test, so we ignore it.\n /* istanbul ignore next 2 */\n pipeline(stream, providerStream, stream, (error: unknown) => {\n if (error) {\n logError(`Provider stream failure.`, error);\n }\n });\n },\n });\n\n // Register the Snap. This sets up the Snap's permissions and subject\n // metadata.\n await registerSnap(snapId, snapFiles.manifest.result, {\n permissionController,\n subjectMetadataController,\n });\n\n // Run the Snap code in the execution service.\n await service.executeSnap({\n snapId,\n sourceCode: snapFiles.sourceCode.toString('utf8'),\n endowments: await getEndowments(permissionController, snapId),\n });\n\n return {\n snapId,\n store,\n executionService: service,\n controllerMessenger,\n runSaga,\n };\n}\n\n/**\n * Get the hooks for the simulation.\n *\n * @param options - The simulation options.\n * @param snapFiles - The Snap files.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The hooks for the simulation.\n */\nexport function getHooks(\n options: SimulationOptions,\n snapFiles: FetchedSnapFiles,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): MiddlewareHooks {\n return {\n getMnemonic: async () =>\n Promise.resolve(mnemonicPhraseToBytes(options.secretRecoveryPhrase)),\n getSnapFile: async (path: string, encoding: AuxiliaryFileEncoding) =>\n await getSnapFile(snapFiles.auxiliaryFiles, path, encoding),\n getIsLocked: () => false,\n createInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:createInterface',\n snapId,\n ...args,\n ),\n updateInterface: async (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:updateInterface',\n snapId,\n ...args,\n ),\n getInterfaceState: (...args) =>\n controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n ...args,\n ).state,\n };\n}\n\n/**\n * Register mocked action handlers.\n *\n * @param controllerMessenger - The controller messenger.\n */\nexport function registerActions(controllerMessenger: RootControllerMessenger) {\n controllerMessenger.registerActionHandler(\n 'PhishingController:maybeUpdateState',\n async () => Promise.resolve(),\n );\n\n controllerMessenger.registerActionHandler(\n 'PhishingController:testOrigin',\n () => ({ result: false, type: 'all' }),\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/specifications.ts"],"sourcesContent":["import type { GenericPermissionController } from '@metamask/permission-controller';\nimport {\n endowmentPermissionBuilders,\n buildSnapEndowmentSpecifications,\n buildSnapRestrictedMethodSpecifications,\n} from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snaps-utils';\n\nimport type { RootControllerMessenger } from '../controllers';\nimport type { SimulationOptions } from '../options';\nimport type { RunSagaFunction } from '../store';\nimport {\n EXCLUDED_SNAP_ENDOWMENTS,\n EXCLUDED_SNAP_PERMISSIONS,\n} from './constants';\nimport {\n getGetLocaleMethodImplementation,\n getClearSnapStateMethodImplementation,\n getGetSnapStateMethodImplementation,\n getUpdateSnapStateMethodImplementation,\n getShowDialogImplementation,\n getShowInAppNotificationImplementation,\n getShowNativeNotificationImplementation,\n encryptImplementation,\n decryptImplementation,\n getCreateInterfaceImplementation,\n getGetInterfaceImplementation,\n} from './hooks';\n\nexport type PermissionSpecificationsHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n};\n\nexport type GetPermissionSpecificationsOptions = {\n controllerMessenger: RootControllerMessenger;\n hooks: PermissionSpecificationsHooks;\n runSaga: RunSagaFunction;\n options: SimulationOptions;\n};\n\n/**\n * Get a function which resolves with the specified result.\n *\n * @param result - The result to return.\n * @returns The function implementation.\n */\nexport function resolve(result: unknown) {\n return () => result;\n}\n\n/**\n * Get a function which resolves with the specified result.\n *\n * @param result - The result to return. If not specified, the function will\n * resolve with `undefined`.\n * @returns The function implementation.\n */\nexport function asyncResolve(result?: unknown) {\n return async () => result;\n}\n\n/**\n * Get the permission specifications for the Snap.\n *\n * @param options - The options.\n * @param options.controllerMessenger - The controller messenger.\n * @param options.hooks - The hooks.\n * @param options.runSaga - The function to run a saga outside the usual Redux\n * flow.\n * @param options.options - The simulation options.\n * @returns The permission specifications for the Snap.\n */\nexport function getPermissionSpecifications({\n controllerMessenger,\n hooks,\n runSaga,\n options,\n}: GetPermissionSpecificationsOptions) {\n return {\n ...buildSnapEndowmentSpecifications(EXCLUDED_SNAP_ENDOWMENTS),\n ...buildSnapRestrictedMethodSpecifications(EXCLUDED_SNAP_PERMISSIONS, {\n // Shared hooks.\n ...hooks,\n\n // Encryption and decryption hooks.\n // TODO: Swap these out for the real implementations.\n encrypt: encryptImplementation,\n decrypt: decryptImplementation,\n\n // Snaps-specific hooks.\n clearSnapState: getClearSnapStateMethodImplementation(runSaga),\n getLocale: getGetLocaleMethodImplementation(options),\n getSnapState: getGetSnapStateMethodImplementation(runSaga),\n getUnlockPromise: asyncResolve(true),\n\n // TODO: Allow the user to specify the result of this function.\n isOnPhishingList: resolve(false),\n\n maybeUpdatePhishingList: asyncResolve(),\n showDialog: getShowDialogImplementation(runSaga),\n showInAppNotification: getShowInAppNotificationImplementation(runSaga),\n showNativeNotification: getShowNativeNotificationImplementation(runSaga),\n updateSnapState: getUpdateSnapStateMethodImplementation(runSaga),\n createInterface: getCreateInterfaceImplementation(controllerMessenger),\n getInterface: getGetInterfaceImplementation(controllerMessenger),\n }),\n };\n}\n\n/**\n * Get the endowments for the Snap.\n *\n * @param permissionController - The permission controller.\n * @param snapId - The ID of the Snap.\n * @returns The endowments for the Snap.\n */\nexport async function getEndowments(\n permissionController: GenericPermissionController,\n snapId: SnapId,\n) {\n const allEndowments = await Object.keys(endowmentPermissionBuilders).reduce<\n Promise<string[]>\n >(async (promise, permissionName) => {\n const accumulator = await promise;\n if (permissionController.hasPermission(snapId, permissionName)) {\n const endowments = await permissionController.getEndowments(\n snapId,\n permissionName,\n );\n\n if (endowments) {\n return accumulator.concat(endowments as string[]);\n }\n }\n\n return accumulator;\n }, Promise.resolve([]));\n\n return [...new Set([...DEFAULT_ENDOWMENTS, ...allEndowments])];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0BAA0B;AA6C5B,SAAS,QAAQ,QAAiB;AACvC,SAAO,MAAM;AACf;AASO,SAAS,aAAa,QAAkB;AAC7C,SAAO,YAAY;AACrB;AAaO,SAAS,4BAA4B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAuC;AACrC,SAAO;AAAA,IACL,GAAG,iCAAiC,wBAAwB;AAAA,IAC5D,GAAG,wCAAwC,2BAA2B;AAAA;AAAA,MAEpE,GAAG;AAAA;AAAA;AAAA,MAIH,SAAS;AAAA,MACT,SAAS;AAAA;AAAA,MAGT,gBAAgB,sCAAsC,OAAO;AAAA,MAC7D,WAAW,iCAAiC,OAAO;AAAA,MACnD,cAAc,oCAAoC,OAAO;AAAA,MACzD,kBAAkB,aAAa,IAAI;AAAA;AAAA,MAGnC,kBAAkB,QAAQ,KAAK;AAAA,MAE/B,yBAAyB,aAAa;AAAA,MACtC,YAAY,4BAA4B,OAAO;AAAA,MAC/C,uBAAuB,uCAAuC,OAAO;AAAA,MACrE,wBAAwB,wCAAwC,OAAO;AAAA,MACvE,iBAAiB,uCAAuC,OAAO;AAAA,MAC/D,iBAAiB,iCAAiC,mBAAmB;AAAA,MACrE,cAAc,8BAA8B,mBAAmB;AAAA,IACjE,CAAC;AAAA,EACH;AACF;AASA,eAAsB,cACpB,sBACA,QACA;AACA,QAAM,gBAAgB,MAAM,OAAO,KAAK,2BAA2B,EAAE,OAEnE,OAAO,SAAS,mBAAmB;AACnC,UAAM,cAAc,MAAM;AAC1B,QAAI,qBAAqB,cAAc,QAAQ,cAAc,GAAG;AAC9D,YAAM,aAAa,MAAM,qBAAqB;AAAA,QAC5C;AAAA,QACA;AAAA,MACF;AAEA,UAAI,YAAY;AACd,eAAO,YAAY,OAAO,UAAsB;AAAA,MAClD;AAAA,IACF;AAEA,WAAO;AAAA,EACT,GAAG,QAAQ,QAAQ,CAAC,CAAC,CAAC;AAEtB,SAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,GAAG,oBAAoB,GAAG,aAAa,CAAC,CAAC;AAC/D;","names":[]}
|
package/dist/chunk-HNH5UAKZ.js
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
-
|
|
3
|
-
var _chunkZAQZRYPWjs = require('./chunk-ZAQZRYPW.js');
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
var _chunk2YE2P5BZjs = require('./chunk-2YE2P5BZ.js');
|
|
8
|
-
|
|
9
|
-
// src/internals/request.ts
|
|
10
|
-
var _snapsutils = require('@metamask/snaps-utils');
|
|
11
|
-
var _utils = require('@metamask/utils');
|
|
12
|
-
var _toolkit = require('@reduxjs/toolkit');
|
|
13
|
-
function handleRequest({
|
|
14
|
-
snapId,
|
|
15
|
-
store,
|
|
16
|
-
executionService,
|
|
17
|
-
handler,
|
|
18
|
-
controllerMessenger,
|
|
19
|
-
runSaga,
|
|
20
|
-
request: { id = _toolkit.nanoid.call(void 0, ), origin = "https://metamask.io", ...options }
|
|
21
|
-
}) {
|
|
22
|
-
const promise = executionService.handleRpcRequest(snapId, {
|
|
23
|
-
origin,
|
|
24
|
-
handler,
|
|
25
|
-
request: {
|
|
26
|
-
jsonrpc: "2.0",
|
|
27
|
-
id: 1,
|
|
28
|
-
...options
|
|
29
|
-
}
|
|
30
|
-
}).then((result) => {
|
|
31
|
-
const notifications = _chunk2YE2P5BZjs.getNotifications.call(void 0, store.getState());
|
|
32
|
-
store.dispatch(_chunk2YE2P5BZjs.clearNotifications.call(void 0, ));
|
|
33
|
-
const content = getContentFromResult(result, snapId, controllerMessenger);
|
|
34
|
-
return {
|
|
35
|
-
id: String(id),
|
|
36
|
-
response: {
|
|
37
|
-
result: _utils.getSafeJson.call(void 0, result)
|
|
38
|
-
},
|
|
39
|
-
notifications,
|
|
40
|
-
content
|
|
41
|
-
};
|
|
42
|
-
}).catch((error) => {
|
|
43
|
-
const [unwrappedError] = _snapsutils.unwrapError.call(void 0, error);
|
|
44
|
-
return {
|
|
45
|
-
id: String(id),
|
|
46
|
-
response: {
|
|
47
|
-
error: unwrappedError.serialize()
|
|
48
|
-
},
|
|
49
|
-
notifications: []
|
|
50
|
-
};
|
|
51
|
-
});
|
|
52
|
-
promise.getInterface = async () => {
|
|
53
|
-
return await runSaga(
|
|
54
|
-
_chunkZAQZRYPWjs.getInterface,
|
|
55
|
-
runSaga,
|
|
56
|
-
snapId,
|
|
57
|
-
controllerMessenger
|
|
58
|
-
).toPromise();
|
|
59
|
-
};
|
|
60
|
-
return promise;
|
|
61
|
-
}
|
|
62
|
-
function getContentFromResult(result, snapId, controllerMessenger) {
|
|
63
|
-
if (_utils.isPlainObject.call(void 0, result) && _utils.hasProperty.call(void 0, result, "id")) {
|
|
64
|
-
return controllerMessenger.call(
|
|
65
|
-
"SnapInterfaceController:getInterface",
|
|
66
|
-
snapId,
|
|
67
|
-
result.id
|
|
68
|
-
).content;
|
|
69
|
-
}
|
|
70
|
-
if (_utils.isPlainObject.call(void 0, result) && _utils.hasProperty.call(void 0, result, "content")) {
|
|
71
|
-
return result.content;
|
|
72
|
-
}
|
|
73
|
-
return void 0;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
exports.handleRequest = handleRequest; exports.getContentFromResult = getContentFromResult;
|
|
80
|
-
//# sourceMappingURL=chunk-HNH5UAKZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/request.ts"],"names":[],"mappings":";;;;;;;;;AAGA,SAAS,mBAAmB;AAC5B,SAAS,aAAa,aAAa,qBAAqB;AACxD,SAAS,cAAc;AAyChB,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,EAAE,KAAK,OAAO,GAAG,SAAS,uBAAuB,GAAG,QAAQ;AACvE,GAAsC;AACpC,QAAM,UAAU,iBACb,iBAAiB,QAAQ;AAAA,IACxB;AAAA,IACA;AAAA,IACA,SAAS;AAAA,MACP,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,GAAG;AAAA,IACL;AAAA,EACF,CAAC,EACA,KAAK,CAAC,WAAW;AAChB,UAAM,gBAAgB,iBAAiB,MAAM,SAAS,CAAC;AACvD,UAAM,SAAS,mBAAmB,CAAC;AAEnC,UAAM,UAAU,qBAAqB,QAAQ,QAAQ,mBAAmB;AAExE,WAAO;AAAA,MACL,IAAI,OAAO,EAAE;AAAA,MACb,UAAU;AAAA,QACR,QAAQ,YAAY,MAAM;AAAA,MAC5B;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC,EACA,MAAM,CAAC,UAAU;AAChB,UAAM,CAAC,cAAc,IAAI,YAAY,KAAK;AAE1C,WAAO;AAAA,MACL,IAAI,OAAO,EAAE;AAAA,MACb,UAAU;AAAA,QACR,OAAO,eAAe,UAAU;AAAA,MAClC;AAAA,MACA,eAAe,CAAC;AAAA,IAClB;AAAA,EACF,CAAC;AAEH,UAAQ,eAAe,YAAY;AACjC,WAAO,MAAM;AAAA,MACX;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,EAAE,UAAU;AAAA,EACd;AAEA,SAAO;AACT;AAUO,SAAS,qBACd,QACA,QACA,qBACuB;AACvB,MAAI,cAAc,MAAM,KAAK,YAAY,QAAQ,IAAI,GAAG;AACtD,WAAO,oBAAoB;AAAA,MACzB;AAAA,MACA;AAAA,MACA,OAAO;AAAA,IACT,EAAE;AAAA,EACJ;AAEA,MAAI,cAAc,MAAM,KAAK,YAAY,QAAQ,SAAS,GAAG;AAC3D,WAAO,OAAO;AAAA,EAChB;AAEA,SAAO;AACT","sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport type { SnapId, Component } from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { getSafeJson, hasProperty, isPlainObject } from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RequestOptions, SnapRequest } from '../types';\nimport {\n clearNotifications,\n getInterface,\n getNotifications,\n} from './simulation';\nimport type { RunSagaFunction, Store } from './simulation';\nimport type { RootControllerMessenger } from './simulation/controllers';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n runSaga: RunSagaFunction;\n request: RequestOptions;\n};\n\n/**\n * Send a JSON-RPC request to the Snap, and wrap the response in a\n * {@link SnapResponse} object.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.store - The Redux store.\n * @param options.executionService - The execution service to use to send the\n * request.\n * @param options.handler - The handler to use to send the request.\n * @param options.controllerMessenger - The controller messenger used to call actions.\n * @param options.runSaga - A function to run a saga outside the usual Redux\n * flow.\n * @param options.request - The request to send.\n * @param options.request.id - The ID of the request. If not provided, a random\n * ID will be generated.\n * @param options.request.origin - The origin of the request. Defaults to\n * `https://metamask.io`.\n * @returns The response, wrapped in a {@link SnapResponse} object.\n */\nexport function handleRequest({\n snapId,\n store,\n executionService,\n handler,\n controllerMessenger,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const promise = executionService\n .handleRpcRequest(snapId, {\n origin,\n handler,\n request: {\n jsonrpc: '2.0',\n id: 1,\n ...options,\n },\n })\n .then((result) => {\n const notifications = getNotifications(store.getState());\n store.dispatch(clearNotifications());\n\n const content = getContentFromResult(result, snapId, controllerMessenger);\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n content,\n };\n })\n .catch((error) => {\n const [unwrappedError] = unwrapError(error);\n\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n return await runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n ).toPromise();\n };\n\n return promise;\n}\n\n/**\n * Get the response content either from the SnapInterfaceController or the response object if there is one.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The content components if any.\n */\nexport function getContentFromResult(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): Component | undefined {\n if (isPlainObject(result) && hasProperty(result, 'id')) {\n return controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n result.id as string,\n ).content;\n }\n\n if (isPlainObject(result) && hasProperty(result, 'content')) {\n return result.content as Component;\n }\n\n return undefined;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/hooks/state.ts"],"names":[],"mappings":";;;;;;;AACA,SAAS,KAAK,cAAc;AAe5B,UAAU,2BACR,SACA,YAAY,MACU;AACtB,SAAO,MAAM,OAAO,SAAS,SAAS,CAAC;AACzC;AAQO,SAAS,oCAAoC,SAA0B;AAC5E,SAAO,IAAI,SAAwD;AACjE,WAAO,QAAQ,4BAA4B,GAAG,IAAI,EAAE,OAAO;AAAA,EAC7D;AACF;AAYA,UAAU,8BACR,SACA,UACA,YAAY,MACQ;AACpB,QAAM,IAAI,SAAS,EAAE,OAAO,UAAU,UAAU,CAAC,CAAC;AACpD;AAQO,SAAS,uCACd,SACA;AACA,SAAO,IAAI,SAA2D;AACpE,YAAQ,+BAA+B,GAAG,IAAI,EAAE,OAAO;AAAA,EACzD;AACF;AAWA,UAAU,6BACR,SACA,YAAY,MACQ;AACpB,QAAM,IAAI,WAAW,EAAE,UAAU,CAAC,CAAC;AACrC;AAQO,SAAS,sCACd,SACA;AACA,SAAO,UAAU,SAA0D;AACzE,YAAQ,8BAA8B,GAAG,IAAI,EAAE,OAAO;AAAA,EACxD;AACF","sourcesContent":["import type { SagaIterator } from 'redux-saga';\nimport { put, select } from 'redux-saga/effects';\n\nimport type { RunSagaFunction } from '../../store';\nimport { clearState, getState, setState } from '../../store';\n\n/**\n * Get the Snap state from the store.\n *\n * @param _snapId - The ID of the Snap to get the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to get the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @returns The state of the Snap.\n * @yields Selects the state from the store.\n */\nfunction* getSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<string> {\n return yield select(getState(encrypted));\n}\n\n/**\n * Get the implementation of the `getSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `getSnapState` hook.\n */\nexport function getGetSnapStateMethodImplementation(runSaga: RunSagaFunction) {\n return (...args: Parameters<typeof getSnapStateImplementation>) => {\n return runSaga(getSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Update the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to update the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param newState - The new state.\n * @param encrypted - Whether to update the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* updateSnapStateImplementation(\n _snapId: string,\n newState: string,\n encrypted = true,\n): SagaIterator<void> {\n yield put(setState({ state: newState, encrypted }));\n}\n\n/**\n * Get the implementation of the `updateSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `updateSnapState` hook.\n */\nexport function getUpdateSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return (...args: Parameters<typeof updateSnapStateImplementation>) => {\n runSaga(updateSnapStateImplementation, ...args).result();\n };\n}\n\n/**\n * Clear the Snap state in the store.\n *\n * @param _snapId - The ID of the Snap to clear the state for. This is ignored\n * because the simulator only supports one Snap.\n * @param encrypted - Whether to clear the encrypted or unencrypted state.\n * Defaults to encrypted state.\n * @yields Puts the new state in the store.\n */\nfunction* clearSnapStateImplementation(\n _snapId: string,\n encrypted = true,\n): SagaIterator<void> {\n yield put(clearState({ encrypted }));\n}\n\n/**\n * Get the implementation of the `clearSnapState` hook.\n *\n * @param runSaga - The function to run a saga outside the usual Redux flow.\n * @returns The implementation of the `clearSnapState` hook.\n */\nexport function getClearSnapStateMethodImplementation(\n runSaga: RunSagaFunction,\n) {\n return async (...args: Parameters<typeof clearSnapStateImplementation>) => {\n runSaga(clearSnapStateImplementation, ...args).result();\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/specifications.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0BAA0B;AA6C5B,SAAS,QAAQ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C/D","sourcesContent":["import type { GenericPermissionController } from '@metamask/permission-controller';\nimport {\n endowmentPermissionBuilders,\n buildSnapEndowmentSpecifications,\n buildSnapRestrictedMethodSpecifications,\n} from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { DEFAULT_ENDOWMENTS } from '@metamask/snaps-utils';\n\nimport type { RootControllerMessenger } from '../controllers';\nimport type { SimulationOptions } from '../options';\nimport type { RunSagaFunction } from '../store';\nimport {\n EXCLUDED_SNAP_ENDOWMENTS,\n EXCLUDED_SNAP_PERMISSIONS,\n} from './constants';\nimport {\n getGetLocaleMethodImplementation,\n getClearSnapStateMethodImplementation,\n getGetSnapStateMethodImplementation,\n getUpdateSnapStateMethodImplementation,\n getShowDialogImplementation,\n getShowInAppNotificationImplementation,\n getShowNativeNotificationImplementation,\n encryptImplementation,\n decryptImplementation,\n getCreateInterfaceImplementation,\n getGetInterfaceImplementation,\n} from './hooks';\n\nexport type PermissionSpecificationsHooks = {\n /**\n * A hook that returns the user's secret recovery phrase.\n *\n * @returns The user's secret recovery phrase.\n */\n getMnemonic: () => Promise<Uint8Array>;\n};\n\nexport type GetPermissionSpecificationsOptions = {\n controllerMessenger: RootControllerMessenger;\n hooks: PermissionSpecificationsHooks;\n runSaga: RunSagaFunction;\n options: SimulationOptions;\n};\n\n/**\n * Get a function which resolves with the specified result.\n *\n * @param result - The result to return.\n * @returns The function implementation.\n */\nexport function resolve(result: unknown) {\n return () => result;\n}\n\n/**\n * Get a function which resolves with the specified result.\n *\n * @param result - The result to return. If not specified, the function will\n * resolve with `undefined`.\n * @returns The function implementation.\n */\nexport function asyncResolve(result?: unknown) {\n return async () => result;\n}\n\n/**\n * Get the permission specifications for the Snap.\n *\n * @param options - The options.\n * @param options.controllerMessenger - The controller messenger.\n * @param options.hooks - The hooks.\n * @param options.runSaga - The function to run a saga outside the usual Redux\n * flow.\n * @param options.options - The simulation options.\n * @returns The permission specifications for the Snap.\n */\nexport function getPermissionSpecifications({\n controllerMessenger,\n hooks,\n runSaga,\n options,\n}: GetPermissionSpecificationsOptions) {\n return {\n ...buildSnapEndowmentSpecifications(EXCLUDED_SNAP_ENDOWMENTS),\n ...buildSnapRestrictedMethodSpecifications(EXCLUDED_SNAP_PERMISSIONS, {\n // Shared hooks.\n ...hooks,\n\n // Encryption and decryption hooks.\n // TODO: Swap these out for the real implementations.\n encrypt: encryptImplementation,\n decrypt: decryptImplementation,\n\n // Snaps-specific hooks.\n clearSnapState: getClearSnapStateMethodImplementation(runSaga),\n getLocale: getGetLocaleMethodImplementation(options),\n getSnapState: getGetSnapStateMethodImplementation(runSaga),\n getUnlockPromise: asyncResolve(true),\n\n // TODO: Allow the user to specify the result of this function.\n isOnPhishingList: resolve(false),\n\n maybeUpdatePhishingList: asyncResolve(),\n showDialog: getShowDialogImplementation(runSaga),\n showInAppNotification: getShowInAppNotificationImplementation(runSaga),\n showNativeNotification: getShowNativeNotificationImplementation(runSaga),\n updateSnapState: getUpdateSnapStateMethodImplementation(runSaga),\n createInterface: getCreateInterfaceImplementation(controllerMessenger),\n getInterface: getGetInterfaceImplementation(controllerMessenger),\n }),\n };\n}\n\n/**\n * Get the endowments for the Snap.\n *\n * @param permissionController - The permission controller.\n * @param snapId - The ID of the Snap.\n * @returns The endowments for the Snap.\n */\nexport async function getEndowments(\n permissionController: GenericPermissionController,\n snapId: SnapId,\n) {\n const allEndowments = await Object.keys(endowmentPermissionBuilders).reduce<\n Promise<string[]>\n >(async (promise, permissionName) => {\n const accumulator = await promise;\n if (permissionController.hasPermission(snapId, permissionName)) {\n const endowments = await permissionController.getEndowments(\n snapId,\n permissionName,\n );\n\n if (endowments) {\n return accumulator.concat(endowments as string[]);\n }\n }\n\n return accumulator;\n }, Promise.resolve([]));\n\n return [...new Set([...DEFAULT_ENDOWMENTS, ...allEndowments])];\n}\n"]}
|
package/dist/chunk-LYK6EGZU.mjs
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
getInterface
|
|
3
|
-
} from "./chunk-6MVV44M5.mjs";
|
|
4
|
-
import {
|
|
5
|
-
clearNotifications,
|
|
6
|
-
getNotifications
|
|
7
|
-
} from "./chunk-LB4R3BUA.mjs";
|
|
8
|
-
|
|
9
|
-
// src/internals/request.ts
|
|
10
|
-
import { unwrapError } from "@metamask/snaps-utils";
|
|
11
|
-
import { getSafeJson, hasProperty, isPlainObject } from "@metamask/utils";
|
|
12
|
-
import { nanoid } from "@reduxjs/toolkit";
|
|
13
|
-
function handleRequest({
|
|
14
|
-
snapId,
|
|
15
|
-
store,
|
|
16
|
-
executionService,
|
|
17
|
-
handler,
|
|
18
|
-
controllerMessenger,
|
|
19
|
-
runSaga,
|
|
20
|
-
request: { id = nanoid(), origin = "https://metamask.io", ...options }
|
|
21
|
-
}) {
|
|
22
|
-
const promise = executionService.handleRpcRequest(snapId, {
|
|
23
|
-
origin,
|
|
24
|
-
handler,
|
|
25
|
-
request: {
|
|
26
|
-
jsonrpc: "2.0",
|
|
27
|
-
id: 1,
|
|
28
|
-
...options
|
|
29
|
-
}
|
|
30
|
-
}).then((result) => {
|
|
31
|
-
const notifications = getNotifications(store.getState());
|
|
32
|
-
store.dispatch(clearNotifications());
|
|
33
|
-
const content = getContentFromResult(result, snapId, controllerMessenger);
|
|
34
|
-
return {
|
|
35
|
-
id: String(id),
|
|
36
|
-
response: {
|
|
37
|
-
result: getSafeJson(result)
|
|
38
|
-
},
|
|
39
|
-
notifications,
|
|
40
|
-
content
|
|
41
|
-
};
|
|
42
|
-
}).catch((error) => {
|
|
43
|
-
const [unwrappedError] = unwrapError(error);
|
|
44
|
-
return {
|
|
45
|
-
id: String(id),
|
|
46
|
-
response: {
|
|
47
|
-
error: unwrappedError.serialize()
|
|
48
|
-
},
|
|
49
|
-
notifications: []
|
|
50
|
-
};
|
|
51
|
-
});
|
|
52
|
-
promise.getInterface = async () => {
|
|
53
|
-
return await runSaga(
|
|
54
|
-
getInterface,
|
|
55
|
-
runSaga,
|
|
56
|
-
snapId,
|
|
57
|
-
controllerMessenger
|
|
58
|
-
).toPromise();
|
|
59
|
-
};
|
|
60
|
-
return promise;
|
|
61
|
-
}
|
|
62
|
-
function getContentFromResult(result, snapId, controllerMessenger) {
|
|
63
|
-
if (isPlainObject(result) && hasProperty(result, "id")) {
|
|
64
|
-
return controllerMessenger.call(
|
|
65
|
-
"SnapInterfaceController:getInterface",
|
|
66
|
-
snapId,
|
|
67
|
-
result.id
|
|
68
|
-
).content;
|
|
69
|
-
}
|
|
70
|
-
if (isPlainObject(result) && hasProperty(result, "content")) {
|
|
71
|
-
return result.content;
|
|
72
|
-
}
|
|
73
|
-
return void 0;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
export {
|
|
77
|
-
handleRequest,
|
|
78
|
-
getContentFromResult
|
|
79
|
-
};
|
|
80
|
-
//# sourceMappingURL=chunk-LYK6EGZU.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/request.ts"],"sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport type { SnapId, Component } from '@metamask/snaps-sdk';\nimport type { HandlerType } from '@metamask/snaps-utils';\nimport { unwrapError } from '@metamask/snaps-utils';\nimport { getSafeJson, hasProperty, isPlainObject } from '@metamask/utils';\nimport { nanoid } from '@reduxjs/toolkit';\n\nimport type { RequestOptions, SnapRequest } from '../types';\nimport {\n clearNotifications,\n getInterface,\n getNotifications,\n} from './simulation';\nimport type { RunSagaFunction, Store } from './simulation';\nimport type { RootControllerMessenger } from './simulation/controllers';\n\nexport type HandleRequestOptions = {\n snapId: SnapId;\n store: Store;\n executionService: AbstractExecutionService<unknown>;\n handler: HandlerType;\n controllerMessenger: RootControllerMessenger;\n runSaga: RunSagaFunction;\n request: RequestOptions;\n};\n\n/**\n * Send a JSON-RPC request to the Snap, and wrap the response in a\n * {@link SnapResponse} object.\n *\n * @param options - The request options.\n * @param options.snapId - The ID of the Snap to send the request to.\n * @param options.store - The Redux store.\n * @param options.executionService - The execution service to use to send the\n * request.\n * @param options.handler - The handler to use to send the request.\n * @param options.controllerMessenger - The controller messenger used to call actions.\n * @param options.runSaga - A function to run a saga outside the usual Redux\n * flow.\n * @param options.request - The request to send.\n * @param options.request.id - The ID of the request. If not provided, a random\n * ID will be generated.\n * @param options.request.origin - The origin of the request. Defaults to\n * `https://metamask.io`.\n * @returns The response, wrapped in a {@link SnapResponse} object.\n */\nexport function handleRequest({\n snapId,\n store,\n executionService,\n handler,\n controllerMessenger,\n runSaga,\n request: { id = nanoid(), origin = 'https://metamask.io', ...options },\n}: HandleRequestOptions): SnapRequest {\n const promise = executionService\n .handleRpcRequest(snapId, {\n origin,\n handler,\n request: {\n jsonrpc: '2.0',\n id: 1,\n ...options,\n },\n })\n .then((result) => {\n const notifications = getNotifications(store.getState());\n store.dispatch(clearNotifications());\n\n const content = getContentFromResult(result, snapId, controllerMessenger);\n\n return {\n id: String(id),\n response: {\n result: getSafeJson(result),\n },\n notifications,\n content,\n };\n })\n .catch((error) => {\n const [unwrappedError] = unwrapError(error);\n\n return {\n id: String(id),\n response: {\n error: unwrappedError.serialize(),\n },\n notifications: [],\n };\n }) as unknown as SnapRequest;\n\n promise.getInterface = async () => {\n return await runSaga(\n getInterface,\n runSaga,\n snapId,\n controllerMessenger,\n ).toPromise();\n };\n\n return promise;\n}\n\n/**\n * Get the response content either from the SnapInterfaceController or the response object if there is one.\n *\n * @param result - The handler result object.\n * @param snapId - The Snap ID.\n * @param controllerMessenger - The controller messenger.\n * @returns The content components if any.\n */\nexport function getContentFromResult(\n result: unknown,\n snapId: SnapId,\n controllerMessenger: RootControllerMessenger,\n): Component | undefined {\n if (isPlainObject(result) && hasProperty(result, 'id')) {\n return controllerMessenger.call(\n 'SnapInterfaceController:getInterface',\n snapId,\n result.id as string,\n ).content;\n }\n\n if (isPlainObject(result) && hasProperty(result, 'content')) {\n return result.content as Component;\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;AAGA,SAAS,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AI,cAAc,MAAM,KAAK,YAAY,QAAQ,SAAS,GAAG;AAC3D,WAAO,OAAO;AAAA,EAChB;AAEA,SAAO;AACT;","names":[]}
|
package/dist/chunk-RD7GQCPL.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/internals/simulation/methods/hooks/encryption.ts
|
|
2
|
-
function encryptImplementation(password, value) {
|
|
3
|
-
return JSON.stringify({
|
|
4
|
-
password,
|
|
5
|
-
value
|
|
6
|
-
});
|
|
7
|
-
}
|
|
8
|
-
function decryptImplementation(password, value) {
|
|
9
|
-
const decryptedValue = JSON.parse(value);
|
|
10
|
-
if (decryptedValue.password !== password) {
|
|
11
|
-
throw new Error(
|
|
12
|
-
"Incorrect password. This is a bug in `@metamask/snaps-jest`, please report it."
|
|
13
|
-
);
|
|
14
|
-
}
|
|
15
|
-
return decryptedValue.value;
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
exports.encryptImplementation = encryptImplementation; exports.decryptImplementation = decryptImplementation;
|
|
22
|
-
//# sourceMappingURL=chunk-RD7GQCPL.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/methods/hooks/encryption.ts"],"names":[],"mappings":";AAeO,SAAS,sBAAsB,UAAkB,OAAa;AACnE,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAeO,SAAS,sBAAsB,UAAkB,OAAe;AACrE,QAAM,iBAAiB,KAAK,MAAM,KAAK;AACvC,MAAI,eAAe,aAAa,UAAU;AACxC,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,SAAO,eAAe;AACxB","sourcesContent":["import type { Json } from '@metamask/utils';\n\n/**\n * Mocks encrypting a value using a password. This is not a real encryption\n * method, but rather is used to simulate encryption in the tests.\n *\n * Ideally we would use a real encryption method, such as\n * `@metamask/browser-passworder`, but it doesn't seem to work with Node.js 18\n * without some mocking. We can switch to a real encryption method once we\n * drop support for Node.js 18.\n *\n * @param password - The password to use.\n * @param value - The value to encrypt.\n * @returns The \"encrypted\" value.\n */\nexport function encryptImplementation(password: string, value: Json) {\n return JSON.stringify({\n password,\n value,\n });\n}\n\n/**\n * Mocks decrypting a value using a password. This is not a real encryption\n * method, but rather is used to simulate encryption in the tests.\n *\n * Ideally we would use a real decryption method, such as\n * `@metamask/browser-passworder`, but it doesn't seem to work with Node.js 18\n * without some mocking. We can switch to a real encryption method once we\n * drop support for Node.js 18.\n *\n * @param password - The password to use.\n * @param value - The value to decrypt.\n * @returns The \"decrypted\" value.\n */\nexport function decryptImplementation(password: string, value: string) {\n const decryptedValue = JSON.parse(value);\n if (decryptedValue.password !== password) {\n throw new Error(\n 'Incorrect password. This is a bug in `@metamask/snaps-jest`, please report it.',\n );\n }\n\n return decryptedValue.value;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/structs.ts"],"names":[],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,IAAM,kBAAkB,MAAM;AAAA,EAC5B,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,SAAS,UAAU;AACrB,CAAC;AAEM,IAAM,2BAA2B,OAAO;AAAA;AAAA;AAAA;AAAA,EAI7C,SAAS,UAAU,OAAO,GAAG,UAAU;AAAA;AAAA;AAAA;AAAA,EAKvC,QAAQ,UAAU,OAAO,GAA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AAQ,OAAO;AAAA,EACf,QAAQ;AACV,CAAC;AAEM,IAAM,kBAAkB,KAAK;AAAA,EAClC,SAAS,SAAS,eAAe;AACnC,CAAC;AAEM,IAAM,qBAAqB;AAAA,EAChC;AAAA,EACA,OAAO;AAAA,IACL,IAAI,OAAO;AAAA,IAEX,UAAU,MAAM;AAAA,MACd,OAAO;AAAA,QACL,QAAQ;AAAA,MACV,CAAC;AAAA,MACD,OAAO;AAAA,QACL,OAAO;AAAA,MACT,CAAC;AAAA,IACH,CAAC;AAAA,IAED,eAAe;AAAA,MACb,OAAO;AAAA,QACL,IAAI,OAAO;AAAA,QACX,SAAS,OAAO;AAAA,QAChB,MAAM,MAAM;AAAA,UACV,UAAU,iBAAiB,KAAK;AAAA,UAChC,UAAU,iBAAiB,MAAM;AAAA,QACnC,CAAC;AAAA,MACH,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH","sourcesContent":["import {\n NotificationType,\n ComponentStruct,\n enumValue,\n} from '@metamask/snaps-sdk';\nimport {\n bytesToHex,\n JsonStruct,\n StrictHexStruct,\n valueToBytes,\n} from '@metamask/utils';\nimport { randomBytes } from 'crypto';\nimport {\n array,\n assign,\n bigint,\n coerce,\n defaulted,\n instance,\n literal,\n number,\n object,\n optional,\n string,\n type,\n union,\n record,\n any,\n} from 'superstruct';\n\n// TODO: Export this from `@metamask/utils` instead.\nconst BytesLikeStruct = union([\n bigint(),\n number(),\n string(),\n instance(Uint8Array),\n]);\n\nexport const TransactionOptionsStruct = object({\n /**\n * The CAIP-2 chain ID to send the transaction on. Defaults to `eip155:1`.\n */\n chainId: defaulted(string(), 'eip155:1'),\n\n /**\n * The origin to send the transaction from. Defaults to `metamask.io`.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address to send the transaction from. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The address to send the transaction to. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n to: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The value to send with the transaction. The value may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n value: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x0',\n ),\n\n /**\n * The gas limit to use for the transaction. The gas limit may be specified\n * as a `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `21_000`.\n */\n gasLimit: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(21_000),\n ),\n\n /**\n * The max fee per gas (in Wei) to use for the transaction. The max fee per\n * gas may be specified as a `number`, `bigint`, `string`, or `Uint8Array`.\n * Defaults to `1`.\n */\n maxFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The max priority fee per gas (in Wei) to use for the transaction. The max\n * priority fee per gas may be specified as a `number`, `bigint`, `string`,\n * or `Uint8Array`. Defaults to `1`.\n */\n maxPriorityFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The nonce to use for the transaction. The nonce may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n nonce: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(0),\n ),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0x`.\n */\n data: defaulted(\n coerce(union([StrictHexStruct, literal('0x')]), BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x',\n ),\n});\n\nexport const SignatureOptionsStruct = object({\n /**\n * The origin making the signature request.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address signing the signature request. Defaults to a randomly generated\n * address.\n */\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return bytesToHex(valueToBytes(value));\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `string`, an object, or an array of objects. This covers the data types\n * for the supported signature methods. Defaults to `0x`.\n */\n data: defaulted(\n union([\n StrictHexStruct,\n literal('0x'),\n record(string(), any()),\n array(record(string(), any())),\n ]),\n '0x',\n ),\n\n /**\n * The signature method being used.\n */\n signatureMethod: defaulted(\n union([\n literal('eth_sign'),\n literal('personal_sign'),\n literal('eth_signTypedData'),\n literal('eth_signTypedData_v3'),\n literal('eth_signTypedData_v4'),\n ]),\n 'personal_sign',\n ),\n});\n\nexport const SnapOptionsStruct = object({\n /**\n * The timeout in milliseconds to use for requests to the snap. Defaults to\n * `1000`.\n */\n timeout: defaulted(optional(number()), 1000),\n});\n\nexport const JsonRpcMockOptionsStruct = object({\n method: string(),\n result: JsonStruct,\n});\n\nexport const InterfaceStruct = type({\n content: optional(ComponentStruct),\n});\n\nexport const SnapResponseStruct = assign(\n InterfaceStruct,\n object({\n id: string(),\n\n response: union([\n object({\n result: JsonStruct,\n }),\n object({\n error: JsonStruct,\n }),\n ]),\n\n notifications: array(\n object({\n id: string(),\n message: string(),\n type: union([\n enumValue(NotificationType.InApp),\n enumValue(NotificationType.Native),\n ]),\n }),\n ),\n }),\n);\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internals/simulation/store/store.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;AAC/B,OAAO,0BAA0B;AAiB1B,SAAS,YACd,UACA,EAAE,OAAO,iBAAiB,GAC1B;AACA,QAAM,iBAAiB,qBAAqB;AAC5C,QAAM,QAAQ,eAAe;AAAA,IAC3B,SAAS;AAAA,MACP,OAAO,WAAW;AAAA,MAClB,eAAe,mBAAmB;AAAA,MAClC,OAAO,WAAW;AAAA,MAClB,IAAI,QAAQ;AAAA,IACd;AAAA,IACA,YAAY,CAAC,yBACX,qBAAqB,EAAE,OAAO,MAAM,CAAC,EAAE,OAAO,cAAc;AAAA,EAChE,CAAC;AAGD,MAAI,OAAO;AACT,UAAM;AAAA,MACJ,SAAS;AAAA,QACP,OAAO,KAAK,UAAU;AAAA,UACpB;AAAA,UACA,OAAO;AAAA,QACT,CAAC;AAAA,QACD,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,MAAI,kBAAkB;AACpB,UAAM;AAAA,MACJ,SAAS;AAAA,QACP,OAAO,KAAK,UAAU,gBAAgB;AAAA,QACtC,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS,eAAe,IAAI,KAAK,cAAc;AAAA,EACjD;AACF","sourcesContent":["import { configureStore } from '@reduxjs/toolkit';\nimport createSagaMiddleware from 'redux-saga';\n\nimport type { SimulationOptions } from '../options';\nimport { mocksSlice } from './mocks';\nimport { notificationsSlice } from './notifications';\nimport { setState, stateSlice } from './state';\nimport { uiSlice } from './ui';\n\n/**\n * Create a Redux store.\n *\n * @param password - The password to use for state encryption.\n * @param options - The simulation options.\n * @param options.state - The initial state for the Snap.\n * @param options.unencryptedState - The initial unencrypted state for the Snap.\n * @returns A Redux store with the default state.\n */\nexport function createStore(\n password: string,\n { state, unencryptedState }: SimulationOptions,\n) {\n const sagaMiddleware = createSagaMiddleware();\n const store = configureStore({\n reducer: {\n mocks: mocksSlice.reducer,\n notifications: notificationsSlice.reducer,\n state: stateSlice.reducer,\n ui: uiSlice.reducer,\n },\n middleware: (getDefaultMiddleware) =>\n getDefaultMiddleware({ thunk: false }).concat(sagaMiddleware),\n });\n\n // Set initial state for the Snap.\n if (state) {\n store.dispatch(\n setState({\n state: JSON.stringify({\n password,\n value: state,\n }),\n encrypted: true,\n }),\n );\n }\n\n if (unencryptedState) {\n store.dispatch(\n setState({\n state: JSON.stringify(unencryptedState),\n encrypted: false,\n }),\n );\n }\n\n return {\n store,\n runSaga: sagaMiddleware.run.bind(sagaMiddleware),\n };\n}\n\nexport type Store = ReturnType<typeof createStore>['store'];\nexport type ApplicationState = ReturnType<Store['getState']>;\nexport type RunSagaFunction = ReturnType<typeof createStore>['runSaga'];\n"]}
|
package/dist/chunk-U5BLLHIU.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";//# sourceMappingURL=chunk-U5BLLHIU.js.map
|
package/dist/chunk-V6LFAN3U.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-V6LFAN3U.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/helpers.ts"],"sourcesContent":["import type { AbstractExecutionService } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType, logInfo } from '@metamask/snaps-utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { create } from 'superstruct';\n\nimport {\n rootLogger,\n handleRequest,\n TransactionOptionsStruct,\n getEnvironment,\n JsonRpcMockOptionsStruct,\n SignatureOptionsStruct,\n} from './internals';\nimport type { InstallSnapOptions } from './internals';\nimport {\n addJsonRpcMock,\n removeJsonRpcMock,\n} from './internals/simulation/store/mocks';\nimport type {\n CronjobOptions,\n JsonRpcMockOptions,\n Snap,\n SnapResponse,\n TransactionOptions,\n} from './types';\n\nconst log = createModuleLogger(rootLogger, 'helpers');\n\n/**\n * Get the options for {@link installSnap}.\n *\n * @param snapId - The ID of the Snap, or the options.\n * @param options - The options, if any.\n * @returns The options.\n */\nfunction getOptions<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId | Partial<InstallSnapOptions<Service>> | undefined,\n options: Partial<InstallSnapOptions<Service>>,\n): [SnapId | undefined, Partial<InstallSnapOptions<Service>>] {\n if (typeof snapId === 'object') {\n return [undefined, snapId];\n }\n\n return [snapId, options];\n}\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap(): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(options: Partial<InstallSnapOptions<Service>>): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param snapId - The ID of the snap, including the prefix (`local:`). Defaults\n * to the URL of the built-in server, if it is running. This supports both\n * local snap IDs and NPM snap IDs.\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId: SnapId,\n options?: Partial<InstallSnapOptions<Service>>,\n): Promise<Snap>;\n\n/**\n * Load a snap into the environment. This is the main entry point for testing\n * snaps: It returns a {@link Snap} object that can be used to interact with the\n * snap.\n *\n * @example\n * import { installSnap } from '@metamask/snaps-jest';\n *\n * describe('My Snap', () => {\n * it('should do something', async () => {\n * const { request } = await installSnap('local:my-snap');\n * const response = await request({\n * method: 'foo',\n * params: ['bar'],\n * });\n * expect(response).toRespondWith('bar');\n * });\n * });\n * @param snapId - The ID of the snap, including the prefix (`local:`). Defaults\n * to the URL of the built-in server, if it is running. This supports both\n * local snap IDs and NPM snap IDs.\n * @param options - The options to use.\n * @param options.executionService - The execution service to use. Defaults to\n * {@link NodeThreadExecutionService}. You do not need to provide this unless\n * you are testing a custom execution service.\n * @param options.executionServiceOptions - The options to use when creating the\n * execution service, if any. This should only include options specific to the\n * provided execution service.\n * @param options.options - The simulation options.\n * @returns The snap.\n * @throws If the built-in server is not running, and no snap ID is provided.\n */\nexport async function installSnap<\n Service extends new (...args: any[]) => InstanceType<\n typeof AbstractExecutionService\n >,\n>(\n snapId?: SnapId | Partial<InstallSnapOptions<Service>>,\n options: Partial<InstallSnapOptions<Service>> = {},\n): Promise<Snap> {\n const resolvedOptions = getOptions(snapId, options);\n const {\n snapId: installedSnapId,\n store,\n executionService,\n runSaga,\n controllerMessenger,\n } = await getEnvironment().installSnap(...resolvedOptions);\n\n const onTransaction = async (\n request: TransactionOptions,\n ): Promise<SnapResponse> => {\n log('Sending transaction %o.', request);\n\n const {\n origin: transactionOrigin,\n chainId,\n ...transaction\n } = create(request, TransactionOptionsStruct);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n runSaga,\n controllerMessenger,\n handler: HandlerType.OnTransaction,\n request: {\n method: '',\n params: {\n chainId,\n transaction,\n transactionOrigin,\n },\n },\n });\n };\n\n const onCronjob = (request: CronjobOptions) => {\n log('Running cronjob %o.', options);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnCronjob,\n request,\n });\n };\n\n return {\n request: (request) => {\n log('Sending request %o.', request);\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnRpcRequest,\n request,\n });\n },\n\n onTransaction,\n sendTransaction: onTransaction,\n\n onSignature: async (request: unknown): Promise<SnapResponse> => {\n log('Requesting signature %o.', request);\n\n const { origin: signatureOrigin, ...signature } = create(\n request,\n SignatureOptionsStruct,\n );\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnSignature,\n request: {\n method: '',\n params: {\n signature,\n signatureOrigin,\n },\n },\n });\n },\n\n onCronjob,\n runCronjob: onCronjob,\n\n onHomePage: async (): Promise<SnapResponse> => {\n log('Rendering home page.');\n\n return handleRequest({\n snapId: installedSnapId,\n store,\n executionService,\n controllerMessenger,\n runSaga,\n handler: HandlerType.OnHomePage,\n request: {\n method: '',\n },\n });\n },\n\n mockJsonRpc(mock: JsonRpcMockOptions) {\n log('Mocking JSON-RPC request %o.', mock);\n\n const { method, result } = create(mock, JsonRpcMockOptionsStruct);\n store.dispatch(addJsonRpcMock({ method, result }));\n\n return {\n unmock() {\n log('Unmocking JSON-RPC request %o.', mock);\n\n store.dispatch(removeJsonRpcMock(method));\n },\n };\n },\n\n close: async () => {\n log('Closing execution service.');\n logInfo(\n 'Calling `snap.close()` is deprecated, and will be removed in a future release. Snaps are now automatically closed when the test ends.',\n );\n\n await executionService.terminateAllSnaps();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAEA,SAAS,aAAa,eAAe;AACrC,SAAS,0BAA0B;AACnC,SAAS,cAAc;AAuBvB,IAAM,MAAM,mBAAmB,YAAY,SAAS;AASpD,SAAS,WAKP,QACA,SAC4D;AAC5D,MAAI,OAAO,WAAW,UAAU;AAC9B,WAAO,CAAC,QAAW,MAAM;AAAA,EAC3B;AAEA,SAAO,CAAC,QAAQ,OAAO;AACzB;AAqIA,eAAsB,YAKpB,QACA,UAAgD,CAAC,GAClC;AACf,QAAM,kBAAkB,WAAW,QAAQ,OAAO;AAClD,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI,MAAM,eAAe,EAAE,YAAY,GAAG,eAAe;AAEzD,QAAM,gBAAgB,OACpB,YAC0B;AAC1B,QAAI,2BAA2B,OAAO;AAEtC,UAAM;AAAA,MACJ,QAAQ;AAAA,MACR;AAAA,MACA,GAAG;AAAA,IACL,IAAI,OAAO,SAAS,wBAAwB;AAE5C,WAAO,cAAc;AAAA,MACnB,QAAQ;AAAA,MACR;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,SAAS,YAAY;AAAA,MACrB,SAAS;AAAA,QACP,QAAQ;AAAA,QACR,QAAQ;AAAA,UACN;AAAA,UACA;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,YAAY,CAAC,YAA4B;AAC7C,QAAI,uBAAuB,OAAO;AAElC,WAA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