@metamask/snaps-rpc-methods 8.1.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +10 -1
  2. package/dist/{chunk-MXCJWR45.mjs → chunk-2CTOCP34.mjs} +8 -8
  3. package/dist/chunk-2CTOCP34.mjs.map +1 -0
  4. package/dist/{chunk-TKXU7ZXP.mjs → chunk-2L2ATCIK.mjs} +2 -2
  5. package/dist/{chunk-YG7W4CDT.js → chunk-33MTKZ4H.js} +11 -4
  6. package/dist/chunk-33MTKZ4H.js.map +1 -0
  7. package/dist/{chunk-LGUJMQC7.js → chunk-4BPNRCZJ.js} +5 -4
  8. package/dist/chunk-4BPNRCZJ.js.map +1 -0
  9. package/dist/{chunk-VNH2GKLV.mjs → chunk-CJPFADO7.mjs} +3 -3
  10. package/dist/{chunk-IDZGMGIB.js → chunk-DLVPMPRZ.js} +8 -8
  11. package/dist/chunk-DLVPMPRZ.js.map +1 -0
  12. package/dist/{chunk-AOWUGDER.js → chunk-E27BGHCR.js} +3 -3
  13. package/dist/{chunk-Y4LNTDZ2.mjs → chunk-FR26QD3N.mjs} +3 -3
  14. package/dist/{chunk-PG32JMWC.mjs → chunk-I3QG3QZL.mjs} +5 -5
  15. package/dist/{chunk-S7AR3ROH.js → chunk-IE6EHYEG.js} +3 -3
  16. package/dist/{chunk-Q5W3YGEB.js → chunk-IVD2ORDS.js} +3 -3
  17. package/dist/{chunk-IBV23QOX.mjs → chunk-KIXPIIY5.mjs} +2 -2
  18. package/dist/{chunk-AYJK7MSH.js → chunk-LLH2T5NT.js} +5 -5
  19. package/dist/{chunk-TNRH2LRU.mjs → chunk-LXJBBRQ4.mjs} +2 -2
  20. package/dist/{chunk-R2M4YLJ7.js → chunk-M2JQCKR7.js} +3 -3
  21. package/dist/{chunk-RIALLTR7.js → chunk-O2VSIMDY.js} +9 -9
  22. package/dist/{chunk-RX7WZZ32.js → chunk-QAKSH24Z.js} +8 -8
  23. package/dist/{chunk-6WUIFFMQ.mjs → chunk-R3DRYUNH.mjs} +5 -4
  24. package/dist/chunk-R3DRYUNH.mjs.map +1 -0
  25. package/dist/{chunk-3W4SMZFD.mjs → chunk-S46RTIDR.mjs} +3 -3
  26. package/dist/{chunk-NESDQ4PF.mjs → chunk-TE4W25CA.mjs} +2 -2
  27. package/dist/{chunk-L675SYPP.mjs → chunk-TUIJOZXZ.mjs} +4 -4
  28. package/dist/{chunk-GP6TDVNT.js → chunk-VBCE6VHM.js} +5 -5
  29. package/dist/{chunk-SGQXD5K7.mjs → chunk-W33UWNA2.mjs} +11 -4
  30. package/dist/chunk-W33UWNA2.mjs.map +1 -0
  31. package/dist/{chunk-INB4AX37.js → chunk-XXSAESE7.js} +5 -5
  32. package/dist/index.js +13 -13
  33. package/dist/index.mjs +12 -12
  34. package/dist/permissions.js +9 -9
  35. package/dist/permissions.mjs +8 -8
  36. package/dist/permitted/handlers.js +4 -4
  37. package/dist/permitted/handlers.mjs +3 -3
  38. package/dist/permitted/index.js +6 -6
  39. package/dist/permitted/index.mjs +5 -5
  40. package/dist/permitted/invokeKeyring.js +3 -3
  41. package/dist/permitted/invokeKeyring.mjs +2 -2
  42. package/dist/permitted/invokeSnapSugar.js +2 -2
  43. package/dist/permitted/invokeSnapSugar.mjs +1 -1
  44. package/dist/permitted/middleware.js +6 -6
  45. package/dist/permitted/middleware.mjs +5 -5
  46. package/dist/restricted/caveats/index.js +5 -5
  47. package/dist/restricted/caveats/index.mjs +4 -4
  48. package/dist/restricted/getBip32Entropy.js +3 -3
  49. package/dist/restricted/getBip32Entropy.mjs +2 -2
  50. package/dist/restricted/getBip32PublicKey.js +3 -3
  51. package/dist/restricted/getBip32PublicKey.mjs +2 -2
  52. package/dist/restricted/getEntropy.js +3 -3
  53. package/dist/restricted/getEntropy.mjs +2 -2
  54. package/dist/restricted/index.js +8 -8
  55. package/dist/restricted/index.mjs +7 -7
  56. package/dist/restricted/manageState.js +3 -3
  57. package/dist/restricted/manageState.mjs +2 -2
  58. package/dist/tsconfig.build.tsbuildinfo +1 -1
  59. package/dist/types/permitted/handlers.d.ts +2 -2
  60. package/dist/types/permitted/invokeSnapSugar.d.ts +12 -7
  61. package/dist/types/restricted/getBip32PublicKey.d.ts +2 -5
  62. package/dist/types/utils.d.ts +7 -5
  63. package/dist/utils.js +2 -2
  64. package/dist/utils.mjs +1 -1
  65. package/package.json +4 -4
  66. package/dist/chunk-6WUIFFMQ.mjs.map +0 -1
  67. package/dist/chunk-IDZGMGIB.js.map +0 -1
  68. package/dist/chunk-LGUJMQC7.js.map +0 -1
  69. package/dist/chunk-MXCJWR45.mjs.map +0 -1
  70. package/dist/chunk-SGQXD5K7.mjs.map +0 -1
  71. package/dist/chunk-YG7W4CDT.js.map +0 -1
  72. /package/dist/{chunk-TKXU7ZXP.mjs.map → chunk-2L2ATCIK.mjs.map} +0 -0
  73. /package/dist/{chunk-VNH2GKLV.mjs.map → chunk-CJPFADO7.mjs.map} +0 -0
  74. /package/dist/{chunk-AOWUGDER.js.map → chunk-E27BGHCR.js.map} +0 -0
  75. /package/dist/{chunk-Y4LNTDZ2.mjs.map → chunk-FR26QD3N.mjs.map} +0 -0
  76. /package/dist/{chunk-PG32JMWC.mjs.map → chunk-I3QG3QZL.mjs.map} +0 -0
  77. /package/dist/{chunk-S7AR3ROH.js.map → chunk-IE6EHYEG.js.map} +0 -0
  78. /package/dist/{chunk-Q5W3YGEB.js.map → chunk-IVD2ORDS.js.map} +0 -0
  79. /package/dist/{chunk-IBV23QOX.mjs.map → chunk-KIXPIIY5.mjs.map} +0 -0
  80. /package/dist/{chunk-AYJK7MSH.js.map → chunk-LLH2T5NT.js.map} +0 -0
  81. /package/dist/{chunk-TNRH2LRU.mjs.map → chunk-LXJBBRQ4.mjs.map} +0 -0
  82. /package/dist/{chunk-R2M4YLJ7.js.map → chunk-M2JQCKR7.js.map} +0 -0
  83. /package/dist/{chunk-RIALLTR7.js.map → chunk-O2VSIMDY.js.map} +0 -0
  84. /package/dist/{chunk-RX7WZZ32.js.map → chunk-QAKSH24Z.js.map} +0 -0
  85. /package/dist/{chunk-3W4SMZFD.mjs.map → chunk-S46RTIDR.mjs.map} +0 -0
  86. /package/dist/{chunk-NESDQ4PF.mjs.map → chunk-TE4W25CA.mjs.map} +0 -0
  87. /package/dist/{chunk-L675SYPP.mjs.map → chunk-TUIJOZXZ.mjs.map} +0 -0
  88. /package/dist/{chunk-GP6TDVNT.js.map → chunk-VBCE6VHM.js.map} +0 -0
  89. /package/dist/{chunk-INB4AX37.js.map → chunk-XXSAESE7.js.map} +0 -0
@@ -2,7 +2,7 @@ export declare const methodHandlers: {
2
2
  wallet_getAllSnaps: import("@metamask/permission-controller").PermittedHandlerExport<import("./getAllSnaps").GetAllSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult>;
3
3
  wallet_getSnaps: import("@metamask/permission-controller").PermittedHandlerExport<import("./getSnaps").GetSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult>;
4
4
  wallet_requestSnaps: import("@metamask/permission-controller").PermittedHandlerExport<import("./requestSnaps").RequestSnapsHooks, import("@metamask/snaps-sdk").RequestSnapsParams, import("@metamask/snaps-sdk").RequestSnapsResult>;
5
- wallet_invokeSnap: import("@metamask/permission-controller").PermittedHandlerExport<void, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json>;
5
+ wallet_invokeSnap: import("@metamask/permission-controller").PermittedHandlerExport<import("./invokeSnapSugar").InvokeSnapSugarHooks, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json>;
6
6
  wallet_invokeKeyring: import("@metamask/permission-controller").PermittedHandlerExport<import("./invokeKeyring").InvokeKeyringHooks, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json>;
7
7
  snap_getClientStatus: import("@metamask/permission-controller").PermittedHandlerExport<import("./getClientStatus").GetClientStatusHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetClientStatusResult>;
8
8
  snap_getFile: import("@metamask/permission-controller").PermittedHandlerExport<import("./getFile").GetFileHooks, import("@metamask/snaps-sdk").GetFileParams, string>;
@@ -10,4 +10,4 @@ export declare const methodHandlers: {
10
10
  snap_updateInterface: import("@metamask/permission-controller").PermittedHandlerExport<import("./updateInterface").UpdateInterfaceMethodHooks, import("@metamask/snaps-sdk").UpdateInterfaceParams, null>;
11
11
  snap_getInterfaceState: import("@metamask/permission-controller").PermittedHandlerExport<import("./getInterfaceState").GetInterfaceStateMethodHooks, import("@metamask/snaps-sdk").GetInterfaceStateParams, Record<string, string | Record<string, string | null> | null>>;
12
12
  };
13
- export declare const handlers: (import("@metamask/permission-controller").PermittedHandlerExport<import("./createInterface").CreateInterfaceMethodHooks, import("@metamask/snaps-sdk").CreateInterfaceParams, string> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getAllSnaps").GetAllSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getClientStatus").GetClientStatusHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetClientStatusResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getInterfaceState").GetInterfaceStateMethodHooks, import("@metamask/snaps-sdk").GetInterfaceStateParams, Record<string, string | Record<string, string | null> | null>> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getSnaps").GetSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./requestSnaps").RequestSnapsHooks, import("@metamask/snaps-sdk").RequestSnapsParams, import("@metamask/snaps-sdk").RequestSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./updateInterface").UpdateInterfaceMethodHooks, import("@metamask/snaps-sdk").UpdateInterfaceParams, null> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getFile").GetFileHooks, import("@metamask/snaps-sdk").GetFileParams, string> | import("@metamask/permission-controller").PermittedHandlerExport<void, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json> | import("@metamask/permission-controller").PermittedHandlerExport<import("./invokeKeyring").InvokeKeyringHooks, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json>)[];
13
+ export declare const handlers: (import("@metamask/permission-controller").PermittedHandlerExport<import("./createInterface").CreateInterfaceMethodHooks, import("@metamask/snaps-sdk").CreateInterfaceParams, string> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getAllSnaps").GetAllSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getClientStatus").GetClientStatusHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetClientStatusResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getInterfaceState").GetInterfaceStateMethodHooks, import("@metamask/snaps-sdk").GetInterfaceStateParams, Record<string, string | Record<string, string | null> | null>> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getSnaps").GetSnapsHooks, import("@metamask/utils").JsonRpcParams, import("@metamask/snaps-sdk").GetSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./requestSnaps").RequestSnapsHooks, import("@metamask/snaps-sdk").RequestSnapsParams, import("@metamask/snaps-sdk").RequestSnapsResult> | import("@metamask/permission-controller").PermittedHandlerExport<import("./updateInterface").UpdateInterfaceMethodHooks, import("@metamask/snaps-sdk").UpdateInterfaceParams, null> | import("@metamask/permission-controller").PermittedHandlerExport<import("./getFile").GetFileHooks, import("@metamask/snaps-sdk").GetFileParams, string> | import("@metamask/permission-controller").PermittedHandlerExport<import("./invokeSnapSugar").InvokeSnapSugarHooks, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json> | import("@metamask/permission-controller").PermittedHandlerExport<import("./invokeKeyring").InvokeKeyringHooks, import("@metamask/snaps-sdk").InvokeSnapParams, import("@metamask/utils").Json>)[];
@@ -1,24 +1,29 @@
1
1
  import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback } from '@metamask/json-rpc-engine';
2
2
  import type { PermittedHandlerExport } from '@metamask/permission-controller';
3
3
  import type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';
4
- import type { JsonRpcRequest } from '@metamask/utils';
4
+ import type { JsonRpcRequest, PendingJsonRpcResponse } from '@metamask/utils';
5
5
  /**
6
6
  * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.
7
7
  */
8
- export declare const invokeSnapSugarHandler: PermittedHandlerExport<void, InvokeSnapParams, InvokeSnapResult>;
8
+ export declare const invokeSnapSugarHandler: PermittedHandlerExport<InvokeSnapSugarHooks, InvokeSnapParams, InvokeSnapResult>;
9
+ export declare type InvokeSnapSugarHooks = {
10
+ invokeSnap: (params: InvokeSnapParams) => Promise<InvokeSnapResult>;
11
+ };
9
12
  /**
10
13
  * The `wallet_invokeSnap` method implementation.
11
- * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.
14
+ * Effectively calls `wallet_snap` under the hood.
12
15
  *
13
16
  * @param req - The JSON-RPC request object.
14
- * @param _res - The JSON-RPC response object. Not used by this
15
- * function.
16
- * @param next - The `json-rpc-engine` "next" callback.
17
+ * @param res - The JSON-RPC response object.
18
+ * @param _next - The `json-rpc-engine` "next" callback.
17
19
  * @param end - The `json-rpc-engine` "end" callback.
20
+ * @param hooks - The RPC method hooks.
21
+ * @param hooks.invokeSnap - A function to invoke a snap designated by its parameters,
22
+ * bound to the requesting origin.
18
23
  * @returns Nothing.
19
24
  * @throws If the params are invalid.
20
25
  */
21
- export declare function invokeSnapSugar(req: JsonRpcRequest<InvokeSnapParams>, _res: unknown, next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback): void;
26
+ export declare function invokeSnapSugar(req: JsonRpcRequest<InvokeSnapParams>, res: PendingJsonRpcResponse<InvokeSnapResult>, _next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback, { invokeSnap }: InvokeSnapSugarHooks): Promise<void>;
22
27
  /**
23
28
  * Validates the wallet_invokeSnap method `params` and returns them cast to the correct
24
29
  * type. Throws if validation fails.
@@ -21,14 +21,11 @@ declare type GetBip32PublicKeySpecificationBuilderOptions = {
21
21
  };
22
22
  export declare const Bip32PublicKeyArgsStruct: import("superstruct").Struct<{
23
23
  path: string[];
24
- curve: "ed25519" | "secp256k1";
24
+ curve: "ed25519" | "ed25519Bip32" | "secp256k1";
25
25
  compressed?: boolean | undefined;
26
26
  }, {
27
27
  path: import("superstruct").Struct<string[], import("superstruct").Struct<string, null>>;
28
- curve: import("superstruct").Struct<"ed25519" | "secp256k1", {
29
- ed25519: "ed25519";
30
- secp256k1: "secp256k1";
31
- }>;
28
+ curve: import("superstruct").Describe<"ed25519" | "ed25519Bip32" | "secp256k1">;
32
29
  compressed: import("superstruct").Struct<boolean | undefined, null>;
33
30
  }>;
34
31
  export declare const getBip32PublicKeyBuilder: Readonly<{
@@ -1,3 +1,4 @@
1
+ import type { SupportedCurve } from '@metamask/key-tree';
1
2
  import { SLIP10Node } from '@metamask/key-tree';
2
3
  import type { MagicValue } from '@metamask/snaps-utils';
3
4
  import type { Hex } from '@metamask/utils';
@@ -61,19 +62,20 @@ export declare function deriveEntropy({ input, salt, mnemonicPhrase, magic, }: D
61
62
  * Get the path prefix to use for key derivation in `key-tree`. This assumes the
62
63
  * following:
63
64
  *
64
- * - The Secp256k1 curve always use the BIP-32 specification.
65
- * - The Ed25519 curve always use the SLIP-10 specification.
65
+ * - The Secp256k1 curve always uses the BIP-32 specification.
66
+ * - The Ed25519 curve always uses the SLIP-10 specification.
67
+ * - The BIP-32-Ed25519 curve always uses the CIP-3 specification.
66
68
  *
67
69
  * While this does not matter in most situations (no known case at the time of
68
70
  * writing), `key-tree` requires a specific specification to be used.
69
71
  *
70
72
  * @param curve - The curve to get the path prefix for. The curve is NOT
71
73
  * validated by this function.
72
- * @returns The path prefix, i.e., `secp256k1` or `ed25519`.
74
+ * @returns The path prefix, i.e., `bip32` or `slip10`.
73
75
  */
74
- export declare function getPathPrefix(curve: 'secp256k1' | 'ed25519'): 'bip32' | 'slip10';
76
+ export declare function getPathPrefix(curve: SupportedCurve): 'bip32' | 'slip10' | 'cip3';
75
77
  declare type GetNodeArgs = {
76
- curve: 'secp256k1' | 'ed25519';
78
+ curve: SupportedCurve;
77
79
  secretRecoveryPhrase: Uint8Array;
78
80
  path: string[];
79
81
  };
package/dist/utils.js CHANGED
@@ -3,11 +3,11 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkYG7W4CDTjs = require('./chunk-YG7W4CDT.js');
6
+ var _chunk33MTKZ4Hjs = require('./chunk-33MTKZ4H.js');
7
7
 
8
8
 
9
9
 
10
10
 
11
11
 
12
- exports.deriveEntropy = _chunkYG7W4CDTjs.deriveEntropy; exports.getNode = _chunkYG7W4CDTjs.getNode; exports.getPathPrefix = _chunkYG7W4CDTjs.getPathPrefix; exports.selectHooks = _chunkYG7W4CDTjs.selectHooks;
12
+ exports.deriveEntropy = _chunk33MTKZ4Hjs.deriveEntropy; exports.getNode = _chunk33MTKZ4Hjs.getNode; exports.getPathPrefix = _chunk33MTKZ4Hjs.getPathPrefix; exports.selectHooks = _chunk33MTKZ4Hjs.selectHooks;
13
13
  //# sourceMappingURL=utils.js.map
package/dist/utils.mjs CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  getNode,
4
4
  getPathPrefix,
5
5
  selectHooks
6
- } from "./chunk-SGQXD5K7.mjs";
6
+ } from "./chunk-W33UWNA2.mjs";
7
7
  export {
8
8
  deriveEntropy,
9
9
  getNode,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-rpc-methods",
3
- "version": "8.1.0",
3
+ "version": "9.0.0",
4
4
  "description": "MetaMask Snaps JSON-RPC method implementations.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -39,11 +39,11 @@
39
39
  "build:ci": "tsup --clean"
40
40
  },
41
41
  "dependencies": {
42
- "@metamask/key-tree": "^9.0.0",
42
+ "@metamask/key-tree": "^9.1.0",
43
43
  "@metamask/permission-controller": "^9.0.2",
44
44
  "@metamask/rpc-errors": "^6.2.1",
45
- "@metamask/snaps-sdk": "^4.1.0",
46
- "@metamask/snaps-utils": "^7.3.0",
45
+ "@metamask/snaps-sdk": "^4.2.0",
46
+ "@metamask/snaps-utils": "^7.4.0",
47
47
  "@metamask/utils": "^8.3.0",
48
48
  "@noble/hashes": "^1.3.1",
49
49
  "superstruct": "^1.0.3"
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/restricted/getBip32PublicKey.ts"],"sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32PublicKeyParams,\n GetBip32PublicKeyResult,\n} from '@metamask/snaps-sdk';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\nexport const Bip32PublicKeyArgsStruct = bip32entropy(\n object({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n compressed: optional(boolean()),\n }),\n);\n\n/**\n * The specification builder for the `snap_getBip32PublicKey` permission.\n * `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular\n * BIP-32 node.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getBip32PublicKey` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32PublicKeySpecificationBuilderOptions,\n GetBip32PublicKeySpecification\n> = ({ methodHooks }: GetBip32PublicKeySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32PublicKeyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32PublicKeyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32PublicKeyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32PublicKey`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a public key.\n * @throws If the params are invalid.\n */\nexport function getBip32PublicKeyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32PublicKeyMethodHooks) {\n return async function getBip32PublicKey(\n args: RestrictedMethodOptions<GetBip32PublicKeyParams>,\n ): Promise<GetBip32PublicKeyResult> {\n await getUnlockPromise(true);\n\n assertStruct(\n args.params,\n Bip32PublicKeyArgsStruct,\n 'Invalid BIP-32 public key params',\n rpcErrors.invalidParams,\n );\n\n const { params } = args;\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n if (params.compressed) {\n return node.compressedPublicKey;\n }\n\n return node.publicKey;\n };\n}\n"],"mappings":";;;;;AAMA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAK1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS,OAAO,QAAQ,gBAAgB;AAKjD,IAAM,aAAa;AA4BZ,IAAM,2BAA2B;AAAA,EACtC,OAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MAAM,CAAC,WAAW,WAAW,CAAC;AAAA,IACrC,YAAY,SAAS,QAAQ,CAAC;AAAA,EAChC,CAAC;AACH;AAWA,IAAM,uBAIF,CAAC,EAAE,aAAAA,aAAY,MAAoD;AACrE,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B;AAAA,IACA,gBAAgB,CAAC,eAAe,wBAAwB;AAAA,IACxD,sBAAsB,gCAAgCA,YAAW;AAAA,IACjE,WAAW,CAAC,EAAE,QAAQ,MAAM;AAC1B,UACE,SAAS,WAAW,KACpB,QAAQ,CAAC,EAAE,SAAS,eAAe,0BACnC;AACA,cAAM,UAAU,cAAc;AAAA,UAC5B,SAAS,sBAAsB,eAAe,wBAAwB;AAAA,QACxE,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAA+D;AAAA,EACnE,aAAa;AAAA,EACb,kBAAkB;AACpB;AAEO,IAAM,2BAA2B,OAAO,OAAO;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAYH,SAAS,gCAAgC;AAAA,EAC9C;AAAA,EACA;AACF,GAAiC;AAC/B,SAAO,eAAe,kBACpB,MACkC;AAClC,UAAM,iBAAiB,IAAI;AAE3B;AAAA,MACE,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU;AAAA,IACZ;AAEA,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,OAAO,MAAM,QAAQ;AAAA,MACzB,OAAO,OAAO;AAAA,MACd,MAAM,OAAO;AAAA,MACb,sBAAsB,MAAM,YAAY;AAAA,IAC1C,CAAC;AAED,QAAI,OAAO,YAAY;AACrB,aAAO,KAAK;AAAA,IACd;AAEA,WAAO,KAAK;AAAA,EACd;AACF;","names":["methodHooks"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/permitted/invokeSnapSugar.ts"],"names":[],"mappings":";AAKA,SAAS,iBAAiB;AAG1B,SAAS,gBAAgB;AAKlB,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,mBAAmB;AAAA,EACjC,gBAAgB;AAAA,EAChB,WAAW;AACb;AAcO,SAAS,gBACd,KACA,MACA,MACA,KACM;AACN,MAAI;AACJ,MAAI;AACF,aAAS,mBAAmB,IAAI,MAAM;AAAA,EACxC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,SAAO,KAAK;AACd;AASO,SAAS,mBAAmB,QAAmC;AACpE,MAAI,CAAC,SAAS,MAAM,GAAG;AACrB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI;AAE5B,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,WAAW,IAAI;AAC1D,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,CAAC,SAAS,OAAO,GAAG;AACtB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO;AACT","sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapParams,\n InvokeSnapResult\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapParams>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapParams;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/restricted/getBip32PublicKey.ts"],"names":["methodHooks"],"mappings":";;;;;AAMA,SAAS,gBAAgB,mBAAmB;AAC5C,SAAS,iBAAiB;AAK1B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,SAAS,OAAO,QAAQ,gBAAgB;AAKjD,IAAM,aAAa;AA4BZ,IAAM,2BAA2B;AAAA,EACtC,OAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,MAAM,CAAC,WAAW,WAAW,CAAC;AAAA,IACrC,YAAY,SAAS,QAAQ,CAAC;AAAA,EAChC,CAAC;AACH;AAWA,IAAM,uBAIF,CAAC,EAAE,aAAAA,aAAY,MAAoD;AACrE,SAAO;AAAA,IACL,gBAAgB,eAAe;AAAA,IAC/B;AAAA,IACA,gBAAgB,CAAC,eAAe,wBAAwB;AAAA,IACxD,sBAAsB,gCAAgCA,YAAW;AAAA,IACjE,WAAW,CAAC,EAAE,QAAQ,MAAM;AAC1B,UACE,SAAS,WAAW,KACpB,QAAQ,CAAC,EAAE,SAAS,eAAe,0BACnC;AACA,cAAM,UAAU,cAAc;AAAA,UAC5B,SAAS,sBAAsB,eAAe,wBAAwB;AAAA,QACxE,CAAC;AAAA,MACH;AAAA,IACF;AAAA,IACA,cAAc,CAAC,YAAY,IAAI;AAAA,EACjC;AACF;AAEA,IAAM,cAA+D;AAAA,EACnE,aAAa;AAAA,EACb,kBAAkB;AACpB;AAEO,IAAM,2BAA2B,OAAO,OAAO;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AACF,CAAU;AAYH,SAAS,gCAAgC;AAAA,EAC9C;AAAA,EACA;AACF,GAAiC;AAC/B,SAAO,eAAe,kBACpB,MACkC;AAClC,UAAM,iBAAiB,IAAI;AAE3B;AAAA,MACE,KAAK;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU;AAAA,IACZ;AAEA,UAAM,EAAE,OAAO,IAAI;AACnB,UAAM,OAAO,MAAM,QAAQ;AAAA,MACzB,OAAO,OAAO;AAAA,MACd,MAAM,OAAO;AAAA,MACb,sBAAsB,MAAM,YAAY;AAAA,IAC1C,CAAC;AAED,QAAI,OAAO,YAAY;AACrB,aAAO,KAAK;AAAA,IACd;AAEA,WAAO,KAAK;AAAA,EACd;AACF","sourcesContent":["import type {\n PermissionSpecificationBuilder,\n PermissionValidatorConstraint,\n RestrictedMethodOptions,\n ValidPermissionSpecification,\n} from '@metamask/permission-controller';\nimport { PermissionType, SubjectType } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type {\n GetBip32PublicKeyParams,\n GetBip32PublicKeyResult,\n} from '@metamask/snaps-sdk';\nimport {\n bip32entropy,\n Bip32PathStruct,\n SnapCaveatType,\n} from '@metamask/snaps-utils';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assertStruct } from '@metamask/utils';\nimport { boolean, enums, object, optional } from 'superstruct';\n\nimport type { MethodHooksObject } from '../utils';\nimport { getNode } from '../utils';\n\nconst targetName = 'snap_getBip32PublicKey';\n\nexport type GetBip32PublicKeyMethodHooks = {\n /**\n * @returns The mnemonic of the user's primary keyring.\n */\n getMnemonic: () => Promise<Uint8Array>;\n\n /**\n * Waits for the extension to be unlocked.\n *\n * @returns A promise that resolves once the extension is unlocked.\n */\n getUnlockPromise: (shouldShowUnlockRequest: boolean) => Promise<void>;\n};\n\ntype GetBip32PublicKeySpecificationBuilderOptions = {\n methodHooks: GetBip32PublicKeyMethodHooks;\n};\n\ntype GetBip32PublicKeySpecification = ValidPermissionSpecification<{\n permissionType: PermissionType.RestrictedMethod;\n targetName: typeof targetName;\n methodImplementation: ReturnType<typeof getBip32PublicKeyImplementation>;\n allowedCaveats: Readonly<NonEmptyArray<string>> | null;\n validator: PermissionValidatorConstraint;\n}>;\n\nexport const Bip32PublicKeyArgsStruct = bip32entropy(\n object({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n compressed: optional(boolean()),\n }),\n);\n\n/**\n * The specification builder for the `snap_getBip32PublicKey` permission.\n * `snap_getBip32PublicKey` lets the Snap retrieve public keys for a particular\n * BIP-32 node.\n *\n * @param options - The specification builder options.\n * @param options.methodHooks - The RPC method hooks needed by the method implementation.\n * @returns The specification for the `snap_getBip32PublicKey` permission.\n */\nconst specificationBuilder: PermissionSpecificationBuilder<\n PermissionType.RestrictedMethod,\n GetBip32PublicKeySpecificationBuilderOptions,\n GetBip32PublicKeySpecification\n> = ({ methodHooks }: GetBip32PublicKeySpecificationBuilderOptions) => {\n return {\n permissionType: PermissionType.RestrictedMethod,\n targetName,\n allowedCaveats: [SnapCaveatType.PermittedDerivationPaths],\n methodImplementation: getBip32PublicKeyImplementation(methodHooks),\n validator: ({ caveats }) => {\n if (\n caveats?.length !== 1 ||\n caveats[0].type !== SnapCaveatType.PermittedDerivationPaths\n ) {\n throw rpcErrors.invalidParams({\n message: `Expected a single \"${SnapCaveatType.PermittedDerivationPaths}\" caveat.`,\n });\n }\n },\n subjectTypes: [SubjectType.Snap],\n };\n};\n\nconst methodHooks: MethodHooksObject<GetBip32PublicKeyMethodHooks> = {\n getMnemonic: true,\n getUnlockPromise: true,\n};\n\nexport const getBip32PublicKeyBuilder = Object.freeze({\n targetName,\n specificationBuilder,\n methodHooks,\n} as const);\n\n/**\n * Builds the method implementation for `snap_getBip32PublicKey`.\n *\n * @param hooks - The RPC method hooks.\n * @param hooks.getMnemonic - A function to retrieve the Secret Recovery Phrase of the user.\n * @param hooks.getUnlockPromise - A function that resolves once the MetaMask extension is unlocked\n * and prompts the user to unlock their MetaMask if it is locked.\n * @returns The method implementation which returns a public key.\n * @throws If the params are invalid.\n */\nexport function getBip32PublicKeyImplementation({\n getMnemonic,\n getUnlockPromise,\n}: GetBip32PublicKeyMethodHooks) {\n return async function getBip32PublicKey(\n args: RestrictedMethodOptions<GetBip32PublicKeyParams>,\n ): Promise<GetBip32PublicKeyResult> {\n await getUnlockPromise(true);\n\n assertStruct(\n args.params,\n Bip32PublicKeyArgsStruct,\n 'Invalid BIP-32 public key params',\n rpcErrors.invalidParams,\n );\n\n const { params } = args;\n const node = await getNode({\n curve: params.curve,\n path: params.path,\n secretRecoveryPhrase: await getMnemonic(),\n });\n\n if (params.compressed) {\n return node.compressedPublicKey;\n }\n\n return node.publicKey;\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/permitted/invokeSnapSugar.ts"],"sourcesContent":["import type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { PermittedHandlerExport } from '@metamask/permission-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { InvokeSnapParams, InvokeSnapResult } from '@metamask/snaps-sdk';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { isObject } from '@metamask/utils';\n\n/**\n * `wallet_invokeSnap` attempts to invoke an RPC method of the specified Snap.\n */\nexport const invokeSnapSugarHandler: PermittedHandlerExport<\n void,\n InvokeSnapParams,\n InvokeSnapResult\n> = {\n methodNames: ['wallet_invokeSnap'],\n implementation: invokeSnapSugar,\n hookNames: undefined,\n};\n\n/**\n * The `wallet_invokeSnap` method implementation.\n * Reroutes incoming JSON-RPC requests that are targeting snaps, by modifying the method and params.\n *\n * @param req - The JSON-RPC request object.\n * @param _res - The JSON-RPC response object. Not used by this\n * function.\n * @param next - The `json-rpc-engine` \"next\" callback.\n * @param end - The `json-rpc-engine` \"end\" callback.\n * @returns Nothing.\n * @throws If the params are invalid.\n */\nexport function invokeSnapSugar(\n req: JsonRpcRequest<InvokeSnapParams>,\n _res: unknown,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n): void {\n let params: InvokeSnapParams;\n try {\n params = getValidatedParams(req.params);\n } catch (error) {\n return end(error);\n }\n\n req.method = 'wallet_snap';\n req.params = params;\n return next();\n}\n\n/**\n * Validates the wallet_invokeSnap method `params` and returns them cast to the correct\n * type. Throws if validation fails.\n *\n * @param params - The unvalidated params object from the method request.\n * @returns The validated method parameter object.\n */\nexport function getValidatedParams(params: unknown): InvokeSnapParams {\n if (!isObject(params)) {\n throw rpcErrors.invalidParams({\n message: 'Expected params to be a single object.',\n });\n }\n\n const { snapId, request } = params;\n\n if (!snapId || typeof snapId !== 'string' || snapId === '') {\n throw rpcErrors.invalidParams({\n message: 'Must specify a valid snap ID.',\n });\n }\n\n if (!isObject(request)) {\n throw rpcErrors.invalidParams({\n message: 'Expected request to be a single object.',\n });\n }\n\n return params as InvokeSnapParams;\n}\n"],"mappings":";AAKA,SAAS,iBAAiB;AAG1B,SAAS,gBAAgB;AAKlB,IAAM,yBAIT;AAAA,EACF,aAAa,CAAC,mBAAmB;AAAA,EACjC,gBAAgB;AAAA,EAChB,WAAW;AACb;AAcO,SAAS,gBACd,KACA,MACA,MACA,KACM;AACN,MAAI;AACJ,MAAI;AACF,aAAS,mBAAmB,IAAI,MAAM;AAAA,EACxC,SAAS,OAAO;AACd,WAAO,IAAI,KAAK;AAAA,EAClB;AAEA,MAAI,SAAS;AACb,MAAI,SAAS;AACb,SAAO,KAAK;AACd;AASO,SAAS,mBAAmB,QAAmC;AACpE,MAAI,CAAC,SAAS,MAAM,GAAG;AACrB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,QAAM,EAAE,QAAQ,QAAQ,IAAI;AAE5B,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,WAAW,IAAI;AAC1D,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,MAAI,CAAC,SAAS,OAAO,GAAG;AACtB,UAAM,UAAU,cAAc;AAAA,MAC5B,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath({\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n });\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always use the BIP-32 specification.\n * - The Ed25519 curve always use the SLIP-10 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `secp256k1` or `ed25519`.\n */\nexport function getPathPrefix(\n curve: 'secp256k1' | 'ed25519',\n): 'bip32' | 'slip10' {\n if (curve === 'secp256k1') {\n return 'bip32';\n }\n\n return 'slip10';\n}\n\ntype GetNodeArgs = {\n curve: 'secp256k1' | 'ed25519';\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n return await SLIP10Node.fromDerivationPath({\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n });\n}\n"],"mappings":";AAKA,SAAS,kBAAkB;AAG3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc,iBAAiB;AAExC,IAAM,iBAAiB;AAuBhB,SAAS,YAId,OACA,WACmC;AACnC,MAAI,WAAW;AACb,WAAO,OAAO,KAAK,SAAS,EAAE;AAAA,MAC5B,CAAC,YAAY,cAAc;AACzB,cAAM,WAAW;AACjB,mBAAW,QAAQ,IAAI,MAAM,QAAQ;AACrC,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AASA,SAAS,uBAAuB,MAAuC;AACrE,QAAM,QAA6B,CAAC;AACpC,QAAM,OAAO,eAAe,IAAI;AAEhC,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AACtC,UAAM,SAAS,KAAK,UAAU,QAAQ,CAAC;AAMvC,UAAM,aAAa,SAAS,oBAAoB;AAChD,UAAM,KAAK,SAAS,YAAY,cAAc,GAAY;AAAA,EAC5D;AAEA,SAAO;AACT;AAwCA,eAAsB,cAAc;AAAA,EAClC;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AACF,GAAuC;AACrC,QAAM,aAAa,cAAc,KAAK;AACtC,QAAM,YAAY,cAAc,IAAI;AAGpC,QAAM,OAAO,UAAU,YAAY,CAAC,YAAY,UAAU,SAAS,CAAC,CAAC,CAAC;AACtE,QAAM,yBAAyB,uBAAuB,IAAI;AAG1D,QAAM,EAAE,WAAW,IAAI,MAAM,WAAW,mBAAmB;AAAA,IACzD,gBAAgB;AAAA,MACd;AAAA,MACA,SAAS,KAAK;AAAA,MACd,GAAG;AAAA,IACL;AAAA,IACA,OAAO;AAAA,EACT,CAAC;AAGD,SAAO,YAAY,+BAA+B;AAElD,SAAO,MAAM,UAAU;AACzB;AAgBO,SAAS,cACd,OACoB;AACpB,MAAI,UAAU,aAAa;AACzB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAqBA,eAAsB,QAAQ;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAgB;AACd,QAAM,SAAS,cAAc,KAAK;AAClC,SAAO,MAAM,WAAW,mBAAmB;AAAA,IACzC;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA,GAAI,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,KAAK,EAAE;AAAA,IAGvD;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils.ts"],"names":[],"mappings":";AAKA,SAAS,kBAAkB;AAG3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc,iBAAiB;AAExC,IAAM,iBAAiB;AAuBhB,SAAS,YAId,OACA,WACmC;AACnC,MAAI,WAAW;AACb,WAAO,OAAO,KAAK,SAAS,EAAE;AAAA,MAC5B,CAAC,YAAY,cAAc;AACzB,cAAM,WAAW;AACjB,mBAAW,QAAQ,IAAI,MAAM,QAAQ;AACrC,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;AASA,SAAS,uBAAuB,MAAuC;AACrE,QAAM,QAA6B,CAAC;AACpC,QAAM,OAAO,eAAe,IAAI;AAEhC,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AACtC,UAAM,SAAS,KAAK,UAAU,QAAQ,CAAC;AAMvC,UAAM,aAAa,SAAS,oBAAoB;AAChD,UAAM,KAAK,SAAS,YAAY,cAAc,GAAY;AAAA,EAC5D;AAEA,SAAO;AACT;AAwCA,eAAsB,cAAc;AAAA,EAClC;AAAA,EACA,OAAO;AAAA,EACP;AAAA,EACA;AACF,GAAuC;AACrC,QAAM,aAAa,cAAc,KAAK;AACtC,QAAM,YAAY,cAAc,IAAI;AAGpC,QAAM,OAAO,UAAU,YAAY,CAAC,YAAY,UAAU,SAAS,CAAC,CAAC,CAAC;AACtE,QAAM,yBAAyB,uBAAuB,IAAI;AAG1D,QAAM,EAAE,WAAW,IAAI,MAAM,WAAW,mBAAmB;AAAA,IACzD,gBAAgB;AAAA,MACd;AAAA,MACA,SAAS,KAAK;AAAA,MACd,GAAG;AAAA,IACL;AAAA,IACA,OAAO;AAAA,EACT,CAAC;AAGD,SAAO,YAAY,+BAA+B;AAElD,SAAO,MAAM,UAAU;AACzB;AAgBO,SAAS,cACd,OACoB;AACpB,MAAI,UAAU,aAAa;AACzB,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAqBA,eAAsB,QAAQ;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AACF,GAAgB;AACd,QAAM,SAAS,cAAc,KAAK;AAClC,SAAO,MAAM,WAAW,mBAAmB;AAAA,IACzC;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA,GAAI,KAAK,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,KAAK,EAAE;AAAA,IAGvD;AAAA,EACF,CAAC;AACH","sourcesContent":["import type {\n HardenedBIP32Node,\n BIP32Node,\n SLIP10PathNode,\n} from '@metamask/key-tree';\nimport { SLIP10Node } from '@metamask/key-tree';\nimport type { MagicValue } from '@metamask/snaps-utils';\nimport type { Hex } from '@metamask/utils';\nimport {\n add0x,\n assert,\n concatBytes,\n createDataView,\n stringToBytes,\n} from '@metamask/utils';\nimport { keccak_256 as keccak256 } from '@noble/hashes/sha3';\n\nconst HARDENED_VALUE = 0x80000000;\n\n/**\n * Maps an interface with method hooks to an object, using the keys of the\n * interface, and `true` as value. This ensures that the `methodHooks` object\n * has the same values as the interface.\n */\nexport type MethodHooksObject<HooksType extends Record<string, unknown>> = {\n [Key in keyof HooksType]: true;\n};\n\n/**\n * Returns the subset of the specified `hooks` that are included in the\n * `hookNames` object. This is a Principle of Least Authority (POLA) measure\n * to ensure that each RPC method implementation only has access to the\n * API \"hooks\" it needs to do its job.\n *\n * @param hooks - The hooks to select from.\n * @param hookNames - The names of the hooks to select.\n * @returns The selected hooks.\n * @template Hooks - The hooks to select from.\n * @template HookName - The names of the hooks to select.\n */\nexport function selectHooks<\n Hooks extends Record<string, unknown>,\n HookName extends keyof Hooks,\n>(\n hooks: Hooks,\n hookNames?: Record<HookName, boolean>,\n): Pick<Hooks, HookName> | undefined {\n if (hookNames) {\n return Object.keys(hookNames).reduce<Partial<Pick<Hooks, HookName>>>(\n (hookSubset, _hookName) => {\n const hookName = _hookName as HookName;\n hookSubset[hookName] = hooks[hookName];\n return hookSubset;\n },\n {},\n ) as Pick<Hooks, HookName>;\n }\n return undefined;\n}\n\n/**\n * Get a BIP-32 derivation path array from a hash, which is compatible with\n * `@metamask/key-tree`. The hash is assumed to be 32 bytes long.\n *\n * @param hash - The hash to derive indices from.\n * @returns The derived indices as a {@link HardenedBIP32Node} array.\n */\nfunction getDerivationPathArray(hash: Uint8Array): HardenedBIP32Node[] {\n const array: HardenedBIP32Node[] = [];\n const view = createDataView(hash);\n\n for (let index = 0; index < 8; index++) {\n const uint32 = view.getUint32(index * 4);\n\n // This is essentially `index | 0x80000000`. Because JavaScript numbers are\n // signed, we use the bitwise unsigned right shift operator to ensure that\n // the result is a positive number.\n // eslint-disable-next-line no-bitwise\n const pathIndex = (uint32 | HARDENED_VALUE) >>> 0;\n array.push(`bip32:${pathIndex - HARDENED_VALUE}'` as const);\n }\n\n return array;\n}\n\ntype DeriveEntropyOptions = {\n /**\n * The input value to derive entropy from.\n */\n input: string;\n\n /**\n * An optional salt to use when deriving entropy.\n */\n salt?: string;\n\n /**\n * The mnemonic phrase to use for entropy derivation.\n */\n mnemonicPhrase: Uint8Array;\n\n /**\n * A hardened BIP-32 index, which is used to derive the root key from the\n * mnemonic phrase.\n */\n magic: MagicValue;\n};\n\n/**\n * Derive entropy from the given mnemonic phrase and salt.\n *\n * This is based on the reference implementation of\n * [SIP-6](https://metamask.github.io/SIPs/SIPS/sip-6).\n *\n * @param options - The options for entropy derivation.\n * @param options.input - The input value to derive entropy from.\n * @param options.salt - An optional salt to use when deriving entropy.\n * @param options.mnemonicPhrase - The mnemonic phrase to use for entropy\n * derivation.\n * @param options.magic - A hardened BIP-32 index, which is used to derive the\n * root key from the mnemonic phrase.\n * @returns The derived entropy.\n */\nexport async function deriveEntropy({\n input,\n salt = '',\n mnemonicPhrase,\n magic,\n}: DeriveEntropyOptions): Promise<Hex> {\n const inputBytes = stringToBytes(input);\n const saltBytes = stringToBytes(salt);\n\n // Get the derivation path from the snap ID.\n const hash = keccak256(concatBytes([inputBytes, keccak256(saltBytes)]));\n const computedDerivationPath = getDerivationPathArray(hash);\n\n // Derive the private key using BIP-32.\n const { privateKey } = await SLIP10Node.fromDerivationPath({\n derivationPath: [\n mnemonicPhrase,\n `bip32:${magic}`,\n ...computedDerivationPath,\n ],\n curve: 'secp256k1',\n });\n\n // This should never happen, but this keeps TypeScript happy.\n assert(privateKey, 'Failed to derive the entropy.');\n\n return add0x(privateKey);\n}\n\n/**\n * Get the path prefix to use for key derivation in `key-tree`. This assumes the\n * following:\n *\n * - The Secp256k1 curve always use the BIP-32 specification.\n * - The Ed25519 curve always use the SLIP-10 specification.\n *\n * While this does not matter in most situations (no known case at the time of\n * writing), `key-tree` requires a specific specification to be used.\n *\n * @param curve - The curve to get the path prefix for. The curve is NOT\n * validated by this function.\n * @returns The path prefix, i.e., `secp256k1` or `ed25519`.\n */\nexport function getPathPrefix(\n curve: 'secp256k1' | 'ed25519',\n): 'bip32' | 'slip10' {\n if (curve === 'secp256k1') {\n return 'bip32';\n }\n\n return 'slip10';\n}\n\ntype GetNodeArgs = {\n curve: 'secp256k1' | 'ed25519';\n secretRecoveryPhrase: Uint8Array;\n path: string[];\n};\n\n/**\n * Get a `key-tree`-compatible node.\n *\n * Note: This function assumes that all the parameters have been validated\n * beforehand.\n *\n * @param options - The derivation options.\n * @param options.curve - The curve to use for derivation.\n * @param options.secretRecoveryPhrase - The secret recovery phrase to use for\n * derivation.\n * @param options.path - The derivation path to use as array, starting with an\n * \"m\" as the first item.\n */\nexport async function getNode({\n curve,\n secretRecoveryPhrase,\n path,\n}: GetNodeArgs) {\n const prefix = getPathPrefix(curve);\n return await SLIP10Node.fromDerivationPath({\n curve,\n derivationPath: [\n secretRecoveryPhrase,\n ...(path.slice(1).map((index) => `${prefix}:${index}`) as\n | BIP32Node[]\n | SLIP10PathNode[]),\n ],\n });\n}\n"]}