@metamask-previews/multichain-api-middleware 4.0.3-preview-abca9bcea → 5.0.0-preview-0a30e47

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 (107) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/handlers/index.d.ts +25 -0
  3. package/dist/handlers/index.d.ts.map +1 -0
  4. package/dist/handlers/{index.mjs → index.js} +5 -5
  5. package/dist/handlers/index.js.map +1 -0
  6. package/dist/handlers/{types.d.cts → types.d.ts} +5 -5
  7. package/dist/handlers/types.d.ts.map +1 -0
  8. package/dist/handlers/{types.mjs → types.js} +1 -2
  9. package/dist/handlers/types.js.map +1 -0
  10. package/dist/handlers/{wallet-createSession.d.cts → wallet-createSession.d.ts} +9 -9
  11. package/dist/handlers/wallet-createSession.d.ts.map +1 -0
  12. package/dist/handlers/{wallet-createSession.mjs → wallet-createSession.js} +6 -6
  13. package/dist/handlers/wallet-createSession.js.map +1 -0
  14. package/dist/handlers/{wallet-getSession.d.mts → wallet-getSession.d.ts} +5 -5
  15. package/dist/handlers/wallet-getSession.d.ts.map +1 -0
  16. package/dist/handlers/{wallet-getSession.mjs → wallet-getSession.js} +2 -2
  17. package/dist/handlers/wallet-getSession.js.map +1 -0
  18. package/dist/handlers/{wallet-invokeMethod.d.mts → wallet-invokeMethod.d.ts} +7 -7
  19. package/dist/handlers/wallet-invokeMethod.d.ts.map +1 -0
  20. package/dist/handlers/{wallet-invokeMethod.mjs → wallet-invokeMethod.js} +4 -4
  21. package/dist/handlers/wallet-invokeMethod.js.map +1 -0
  22. package/dist/handlers/{wallet-revokeSession.d.mts → wallet-revokeSession.d.ts} +6 -6
  23. package/dist/handlers/wallet-revokeSession.d.ts.map +1 -0
  24. package/dist/handlers/{wallet-revokeSession.mjs → wallet-revokeSession.js} +5 -5
  25. package/dist/handlers/wallet-revokeSession.js.map +1 -0
  26. package/dist/index.d.ts +7 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +6 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/middlewares/{MultichainMiddlewareManager.d.cts → MultichainMiddlewareManager.d.ts} +4 -4
  31. package/dist/middlewares/MultichainMiddlewareManager.d.ts.map +1 -0
  32. package/dist/middlewares/MultichainMiddlewareManager.js +93 -0
  33. package/dist/middlewares/MultichainMiddlewareManager.js.map +1 -0
  34. package/dist/middlewares/{MultichainSubscriptionManager.d.cts → MultichainSubscriptionManager.d.ts} +6 -6
  35. package/dist/middlewares/MultichainSubscriptionManager.d.ts.map +1 -0
  36. package/dist/middlewares/MultichainSubscriptionManager.js +100 -0
  37. package/dist/middlewares/MultichainSubscriptionManager.js.map +1 -0
  38. package/dist/middlewares/{multichainMethodCallValidatorMiddleware.d.cts → multichainMethodCallValidatorMiddleware.d.ts} +2 -2
  39. package/dist/middlewares/multichainMethodCallValidatorMiddleware.d.ts.map +1 -0
  40. package/dist/middlewares/{multichainMethodCallValidatorMiddleware.mjs → multichainMethodCallValidatorMiddleware.js} +8 -15
  41. package/dist/middlewares/multichainMethodCallValidatorMiddleware.js.map +1 -0
  42. package/package.json +20 -24
  43. package/dist/handlers/index.cjs +0 -20
  44. package/dist/handlers/index.cjs.map +0 -1
  45. package/dist/handlers/index.d.cts +0 -25
  46. package/dist/handlers/index.d.cts.map +0 -1
  47. package/dist/handlers/index.d.mts +0 -25
  48. package/dist/handlers/index.d.mts.map +0 -1
  49. package/dist/handlers/index.mjs.map +0 -1
  50. package/dist/handlers/types.cjs +0 -13
  51. package/dist/handlers/types.cjs.map +0 -1
  52. package/dist/handlers/types.d.cts.map +0 -1
  53. package/dist/handlers/types.d.mts +0 -27
  54. package/dist/handlers/types.d.mts.map +0 -1
  55. package/dist/handlers/types.mjs.map +0 -1
  56. package/dist/handlers/wallet-createSession.cjs +0 -179
  57. package/dist/handlers/wallet-createSession.cjs.map +0 -1
  58. package/dist/handlers/wallet-createSession.d.cts.map +0 -1
  59. package/dist/handlers/wallet-createSession.d.mts +0 -70
  60. package/dist/handlers/wallet-createSession.d.mts.map +0 -1
  61. package/dist/handlers/wallet-createSession.mjs.map +0 -1
  62. package/dist/handlers/wallet-getSession.cjs +0 -54
  63. package/dist/handlers/wallet-getSession.cjs.map +0 -1
  64. package/dist/handlers/wallet-getSession.d.cts +0 -43
  65. package/dist/handlers/wallet-getSession.d.cts.map +0 -1
  66. package/dist/handlers/wallet-getSession.d.mts.map +0 -1
  67. package/dist/handlers/wallet-getSession.mjs.map +0 -1
  68. package/dist/handlers/wallet-invokeMethod.cjs +0 -103
  69. package/dist/handlers/wallet-invokeMethod.cjs.map +0 -1
  70. package/dist/handlers/wallet-invokeMethod.d.cts +0 -57
  71. package/dist/handlers/wallet-invokeMethod.d.cts.map +0 -1
  72. package/dist/handlers/wallet-invokeMethod.d.mts.map +0 -1
  73. package/dist/handlers/wallet-invokeMethod.mjs.map +0 -1
  74. package/dist/handlers/wallet-revokeSession.cjs +0 -106
  75. package/dist/handlers/wallet-revokeSession.cjs.map +0 -1
  76. package/dist/handlers/wallet-revokeSession.d.cts +0 -45
  77. package/dist/handlers/wallet-revokeSession.d.cts.map +0 -1
  78. package/dist/handlers/wallet-revokeSession.d.mts.map +0 -1
  79. package/dist/handlers/wallet-revokeSession.mjs.map +0 -1
  80. package/dist/index.cjs +0 -14
  81. package/dist/index.cjs.map +0 -1
  82. package/dist/index.d.cts +0 -7
  83. package/dist/index.d.cts.map +0 -1
  84. package/dist/index.d.mts +0 -7
  85. package/dist/index.d.mts.map +0 -1
  86. package/dist/index.mjs +0 -6
  87. package/dist/index.mjs.map +0 -1
  88. package/dist/middlewares/MultichainMiddlewareManager.cjs +0 -110
  89. package/dist/middlewares/MultichainMiddlewareManager.cjs.map +0 -1
  90. package/dist/middlewares/MultichainMiddlewareManager.d.cts.map +0 -1
  91. package/dist/middlewares/MultichainMiddlewareManager.d.mts +0 -35
  92. package/dist/middlewares/MultichainMiddlewareManager.d.mts.map +0 -1
  93. package/dist/middlewares/MultichainMiddlewareManager.mjs +0 -106
  94. package/dist/middlewares/MultichainMiddlewareManager.mjs.map +0 -1
  95. package/dist/middlewares/MultichainSubscriptionManager.cjs +0 -118
  96. package/dist/middlewares/MultichainSubscriptionManager.cjs.map +0 -1
  97. package/dist/middlewares/MultichainSubscriptionManager.d.cts.map +0 -1
  98. package/dist/middlewares/MultichainSubscriptionManager.d.mts +0 -49
  99. package/dist/middlewares/MultichainSubscriptionManager.d.mts.map +0 -1
  100. package/dist/middlewares/MultichainSubscriptionManager.mjs +0 -118
  101. package/dist/middlewares/MultichainSubscriptionManager.mjs.map +0 -1
  102. package/dist/middlewares/multichainMethodCallValidatorMiddleware.cjs +0 -74
  103. package/dist/middlewares/multichainMethodCallValidatorMiddleware.cjs.map +0 -1
  104. package/dist/middlewares/multichainMethodCallValidatorMiddleware.d.cts.map +0 -1
  105. package/dist/middlewares/multichainMethodCallValidatorMiddleware.d.mts +0 -7
  106. package/dist/middlewares/multichainMethodCallValidatorMiddleware.d.mts.map +0 -1
  107. package/dist/middlewares/multichainMethodCallValidatorMiddleware.mjs.map +0 -1
@@ -1,179 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.walletCreateSessionHandler = void 0;
4
- const chain_agnostic_permission_1 = require("@metamask/chain-agnostic-permission");
5
- const controller_utils_1 = require("@metamask/controller-utils");
6
- const permission_controller_1 = require("@metamask/permission-controller");
7
- const rpc_errors_1 = require("@metamask/rpc-errors");
8
- const utils_1 = require("@metamask/utils");
9
- const SOLANA_CAIP_CHAIN_ID = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
10
- /**
11
- * Handler for the `wallet_createSession` RPC method which is responsible
12
- * for prompting for approval and granting a CAIP-25 permission.
13
- *
14
- * This implementation primarily deviates from the CAIP-25 handler
15
- * specification by treating all scopes as optional regardless of
16
- * if they were specified in `requiredScopes` or `optionalScopes`.
17
- * Additionally, provided scopes, methods, notifications, and
18
- * account values that are invalid/malformed are ignored rather than
19
- * causing an error to be returned.
20
- *
21
- * @param req - The request object.
22
- * @param res - The response object.
23
- * @param _next - The next middleware function.
24
- * @param end - The end function.
25
- * @param hooks - The hooks object.
26
- * @param hooks.listAccounts - The hook that returns an array of the wallet's evm accounts.
27
- * @param hooks.findNetworkClientIdByChainId - The hook that returns the networkClientId for a chainId.
28
- * @param hooks.requestPermissionsForOrigin - The hook that approves and grants requested permissions.
29
- * @param hooks.getNonEvmSupportedMethods - The hook that returns the supported methods for a non EVM scope.
30
- * @param hooks.isNonEvmScopeSupported - The hook that returns true if a non EVM scope is supported.
31
- * @param hooks.getNonEvmAccountAddresses - The hook that returns a list of CaipAccountIds that are supported for a CaipChainId.
32
- * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by last selected.
33
- * @param hooks.getCapabilities - A function that returns the capabilities for a given address.
34
- * @param hooks.trackSessionCreatedEvent - An optional hook for platform specific logic to run.
35
- * @returns A promise with wallet_createSession handler
36
- */
37
- async function handleWalletCreateSession(req, res, _next, end, hooks) {
38
- if (!(0, utils_1.isPlainObject)(req.params)) {
39
- return end((0, permission_controller_1.invalidParams)({ data: { request: req } }));
40
- }
41
- const { requiredScopes, optionalScopes, sessionProperties } = req.params;
42
- if (sessionProperties && Object.keys(sessionProperties).length === 0) {
43
- return end(new rpc_errors_1.JsonRpcError(5302, 'Invalid sessionProperties requested'));
44
- }
45
- const filteredSessionProperties = Object.fromEntries(Object.entries(sessionProperties ?? {}).filter(([key]) => (0, chain_agnostic_permission_1.isKnownSessionPropertyValue)(key)));
46
- try {
47
- const { normalizedRequiredScopes, normalizedOptionalScopes } = (0, chain_agnostic_permission_1.validateAndNormalizeScopes)(requiredScopes || {}, optionalScopes || {});
48
- const requiredScopesWithSupportedMethodsAndNotifications = (0, chain_agnostic_permission_1.getSupportedScopeObjects)(normalizedRequiredScopes, {
49
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
50
- });
51
- const optionalScopesWithSupportedMethodsAndNotifications = (0, chain_agnostic_permission_1.getSupportedScopeObjects)(normalizedOptionalScopes, {
52
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
53
- });
54
- const networkClientExistsForChainId = (chainId) => {
55
- try {
56
- hooks.findNetworkClientIdByChainId(chainId);
57
- return true;
58
- }
59
- catch {
60
- return false;
61
- }
62
- };
63
- // if solana is a requested scope but not supported, we add a promptToCreateSolanaAccount flag to request
64
- const isSolanaRequested = (0, chain_agnostic_permission_1.isNamespaceInScopesObject)(requiredScopesWithSupportedMethodsAndNotifications, utils_1.KnownCaipNamespace.Solana) ||
65
- (0, chain_agnostic_permission_1.isNamespaceInScopesObject)(optionalScopesWithSupportedMethodsAndNotifications, utils_1.KnownCaipNamespace.Solana);
66
- let promptToCreateSolanaAccount = false;
67
- if (isSolanaRequested) {
68
- const supportedSolanaAccounts = hooks.getNonEvmAccountAddresses(SOLANA_CAIP_CHAIN_ID);
69
- promptToCreateSolanaAccount = supportedSolanaAccounts.length === 0;
70
- }
71
- const { supportedScopes: supportedRequiredScopes } = (0, chain_agnostic_permission_1.bucketScopes)(requiredScopesWithSupportedMethodsAndNotifications, {
72
- isEvmChainIdSupported: networkClientExistsForChainId,
73
- isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties
74
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
75
- isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,
76
- });
77
- const { supportedScopes: supportedOptionalScopes } = (0, chain_agnostic_permission_1.bucketScopes)(optionalScopesWithSupportedMethodsAndNotifications, {
78
- isEvmChainIdSupported: networkClientExistsForChainId,
79
- isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties
80
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
81
- isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,
82
- });
83
- const allRequestedAccountAddresses = (0, chain_agnostic_permission_1.getCaipAccountIdsFromScopesObjects)([
84
- supportedRequiredScopes,
85
- supportedOptionalScopes,
86
- ]);
87
- const allSupportedRequestedCaipChainIds = (0, chain_agnostic_permission_1.getAllScopesFromScopesObjects)([
88
- supportedRequiredScopes,
89
- supportedOptionalScopes,
90
- ]);
91
- const existingEvmAddresses = hooks
92
- .listAccounts()
93
- .map((account) => account.address);
94
- const supportedRequestedAccountAddresses = allRequestedAccountAddresses.filter((requestedAccountAddress) => {
95
- const { address, chain: { namespace }, chainId: caipChainId, } = (0, utils_1.parseCaipAccountId)(requestedAccountAddress);
96
- if (namespace === utils_1.KnownCaipNamespace.Eip155.toString()) {
97
- return existingEvmAddresses.some((existingEvmAddress) => {
98
- return (0, controller_utils_1.isEqualCaseInsensitive)(address, existingEvmAddress);
99
- });
100
- }
101
- // If the namespace is not eip155 (EVM) we do a case sensitive check
102
- return hooks
103
- .getNonEvmAccountAddresses(caipChainId)
104
- .some((existingCaipAddress) => {
105
- return requestedAccountAddress === existingCaipAddress;
106
- });
107
- });
108
- const requestedCaip25CaveatValue = {
109
- requiredScopes: (0, chain_agnostic_permission_1.getInternalScopesObject)(supportedRequiredScopes),
110
- optionalScopes: (0, chain_agnostic_permission_1.getInternalScopesObject)(supportedOptionalScopes),
111
- isMultichainOrigin: true,
112
- sessionProperties: filteredSessionProperties,
113
- };
114
- const requestedCaip25CaveatValueWithSupportedAccounts = (0, chain_agnostic_permission_1.setNonSCACaipAccountIdsInCaip25CaveatValue)(requestedCaip25CaveatValue, supportedRequestedAccountAddresses);
115
- // if `promptToCreateSolanaAccount` is true and there are no other valid scopes requested,
116
- // we add a `wallet` scope to the request in order to get passed the CAIP-25 caveat validator.
117
- // This is very hacky but is necessary because the solana opt-in flow breaks key assumptions
118
- // of the CAIP-25 permission specification - namely that we can have valid requests with no scopes.
119
- if (allSupportedRequestedCaipChainIds.length === 0) {
120
- if (promptToCreateSolanaAccount) {
121
- requestedCaip25CaveatValueWithSupportedAccounts.optionalScopes[utils_1.KnownCaipNamespace.Wallet] = {
122
- accounts: [],
123
- };
124
- }
125
- else {
126
- // if solana is not requested and there are no supported scopes, we return an error
127
- return end(new rpc_errors_1.JsonRpcError(5100, 'Requested scopes are not supported'));
128
- }
129
- }
130
- const [grantedPermissions] = await hooks.requestPermissionsForOrigin({
131
- [chain_agnostic_permission_1.Caip25EndowmentPermissionName]: {
132
- caveats: [
133
- {
134
- type: chain_agnostic_permission_1.Caip25CaveatType,
135
- value: requestedCaip25CaveatValueWithSupportedAccounts,
136
- },
137
- ],
138
- },
139
- }, {
140
- metadata: { promptToCreateSolanaAccount },
141
- });
142
- const approvedCaip25Permission = grantedPermissions[chain_agnostic_permission_1.Caip25EndowmentPermissionName];
143
- const approvedCaip25CaveatValue = approvedCaip25Permission?.caveats?.find((caveat) => caveat.type === chain_agnostic_permission_1.Caip25CaveatType)?.value;
144
- if (!approvedCaip25CaveatValue) {
145
- throw rpc_errors_1.rpcErrors.internal();
146
- }
147
- const sessionScopes = (0, chain_agnostic_permission_1.getSessionScopes)(approvedCaip25CaveatValue, {
148
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
149
- sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,
150
- });
151
- const approvedSessionProperties = await (0, chain_agnostic_permission_1.getSessionProperties)(approvedCaip25CaveatValue, {
152
- getCapabilities: hooks.getCapabilities,
153
- });
154
- hooks.trackSessionCreatedEvent?.(approvedCaip25CaveatValue);
155
- res.result = {
156
- sessionScopes,
157
- sessionProperties: approvedSessionProperties,
158
- };
159
- return end();
160
- }
161
- catch (err) {
162
- return end(err);
163
- }
164
- }
165
- exports.walletCreateSessionHandler = {
166
- implementation: handleWalletCreateSession,
167
- hookNames: {
168
- findNetworkClientIdByChainId: true,
169
- listAccounts: true,
170
- requestPermissionsForOrigin: true,
171
- getNonEvmSupportedMethods: true,
172
- isNonEvmScopeSupported: true,
173
- getNonEvmAccountAddresses: true,
174
- sortAccountIdsByLastSelected: true,
175
- getCapabilities: true,
176
- trackSessionCreatedEvent: true,
177
- },
178
- };
179
- //# sourceMappingURL=wallet-createSession.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-createSession.cjs","sourceRoot":"","sources":["../../src/handlers/wallet-createSession.ts"],"names":[],"mappings":";;;AACA,mFAc6C;AAM7C,iEAAoE;AAOpE,2EAAgE;AAKhE,qDAA+D;AAE/D,2CAIyB;AAezB,MAAM,oBAAoB,GAAG,yCAAyC,CAAC;AAyBvE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,KAAK,UAAU,yBAAyB,CACtC,GAAgD,EAChD,GAAmC,EACnC,KAAgC,EAChC,GAA6B,EAC7B,KAA+B;IAE/B,IAAI,CAAC,IAAA,qBAAa,EAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/B,OAAO,GAAG,CAAC,IAAA,qCAAa,EAAC,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;IACxD,CAAC;IACD,MAAM,EAAE,cAAc,EAAE,cAAc,EAAE,iBAAiB,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC;IAEzE,IAAI,iBAAiB,IAAI,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrE,OAAO,GAAG,CAAC,IAAI,yBAAY,CAAC,IAAI,EAAE,qCAAqC,CAAC,CAAC,CAAC;IAC5E,CAAC;IAED,MAAM,yBAAyB,GAAG,MAAM,CAAC,WAAW,CAClD,MAAM,CAAC,OAAO,CAAC,iBAAiB,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CACvD,IAAA,uDAA2B,EAAC,GAAG,CAAC,CACjC,CACF,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,GAC1D,IAAA,sDAA0B,EAAC,cAAc,IAAI,EAAE,EAAE,cAAc,IAAI,EAAE,CAAC,CAAC;QAEzE,MAAM,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YAChE,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,4BAA4B,EAAE,KAAK,CAAC,4BAA4B;SACjE,CAAC,CAAC;QAEH,MAAM,yBAAyB,GAAG,MAAM,IAAA,gDAAoB,EAC1D,yBAAyB,EACzB;YACE,eAAe,EAAE,KAAK,CAAC,eAAe;SACvC,CACF,CAAC;QAEF,KAAK,CAAC,wBAAwB,EAAE,CAAC,yBAAyB,CAAC,CAAC;QAE5D,GAAG,CAAC,MAAM,GAAG;YACX,aAAa;YACb,iBAAiB,EAAE,yBAAyB;SAC7C,CAAC;QACF,OAAO,GAAG,EAAE,CAAC;IACf,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAUY,QAAA,0BAA0B,GAAG;IACxC,cAAc,EAAE,yBAAyB;IACzC,SAAS,EAAE;QACT,4BAA4B,EAAE,IAAI;QAClC,YAAY,EAAE,IAAI;QAClB,2BAA2B,EAAE,IAAI;QACjC,yBAAyB,EAAE,IAAI;QAC/B,sBAAsB,EAAE,IAAI;QAC5B,yBAAyB,EAAE,IAAI;QAC/B,4BAA4B,EAAE,IAAI;QAClC,eAAe,EAAE,IAAI;QACrB,wBAAwB,EAAE,IAAI;KAC/B;CACmC,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport {\n Caip25CaveatType,\n Caip25EndowmentPermissionName,\n bucketScopes,\n validateAndNormalizeScopes,\n getInternalScopesObject,\n getSessionScopes,\n getSessionProperties,\n getSupportedScopeObjects,\n isKnownSessionPropertyValue,\n getCaipAccountIdsFromScopesObjects,\n getAllScopesFromScopesObjects,\n setNonSCACaipAccountIdsInCaip25CaveatValue,\n isNamespaceInScopesObject,\n} from '@metamask/chain-agnostic-permission';\nimport type {\n Caip25Authorization,\n NormalizedScopesObject,\n Caip25CaveatValue,\n} from '@metamask/chain-agnostic-permission';\nimport { isEqualCaseInsensitive } from '@metamask/controller-utils';\nimport type {\n MethodHandler,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { NetworkController } from '@metamask/network-controller';\nimport { invalidParams } from '@metamask/permission-controller';\nimport type {\n GenericPermissionController,\n RequestedPermissions,\n} from '@metamask/permission-controller';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { MultichainRoutingService } from '@metamask/snaps-controllers';\nimport {\n isPlainObject,\n KnownCaipNamespace,\n parseCaipAccountId,\n} from '@metamask/utils';\nimport type {\n CaipAccountId,\n Hex,\n Json,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n GetCapabilitiesHook,\n GetNonEvmSupportedMethodsHook,\n SortAccountIdsByLastSelectedHook,\n} from './types.js';\n\nconst SOLANA_CAIP_CHAIN_ID = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';\n\nexport type WalletCreateSessionHooks = GetNonEvmSupportedMethodsHook &\n SortAccountIdsByLastSelectedHook &\n GetCapabilitiesHook & {\n listAccounts: AccountsController['listAccounts'];\n findNetworkClientIdByChainId: NetworkController['findNetworkClientIdByChainId'];\n requestPermissionsForOrigin: (\n requestedPermissions: RequestedPermissions,\n metadata?: Record<string, Json>,\n ) => ReturnType<GenericPermissionController['requestPermissions']>;\n isNonEvmScopeSupported: MultichainRoutingService['isSupportedScope'];\n getNonEvmAccountAddresses: MultichainRoutingService['getSupportedAccounts'];\n trackSessionCreatedEvent:\n | ((approvedCaip25CaveatValue: Caip25CaveatValue) => void)\n | null;\n };\n\ntype Params = Caip25Authorization;\n\ntype Result = {\n sessionScopes: NormalizedScopesObject;\n sessionProperties?: Record<string, Json>;\n};\n\n/**\n * Handler for the `wallet_createSession` RPC method which is responsible\n * for prompting for approval and granting a CAIP-25 permission.\n *\n * This implementation primarily deviates from the CAIP-25 handler\n * specification by treating all scopes as optional regardless of\n * if they were specified in `requiredScopes` or `optionalScopes`.\n * Additionally, provided scopes, methods, notifications, and\n * account values that are invalid/malformed are ignored rather than\n * causing an error to be returned.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param _next - The next middleware function.\n * @param end - The end function.\n * @param hooks - The hooks object.\n * @param hooks.listAccounts - The hook that returns an array of the wallet's evm accounts.\n * @param hooks.findNetworkClientIdByChainId - The hook that returns the networkClientId for a chainId.\n * @param hooks.requestPermissionsForOrigin - The hook that approves and grants requested permissions.\n * @param hooks.getNonEvmSupportedMethods - The hook that returns the supported methods for a non EVM scope.\n * @param hooks.isNonEvmScopeSupported - The hook that returns true if a non EVM scope is supported.\n * @param hooks.getNonEvmAccountAddresses - The hook that returns a list of CaipAccountIds that are supported for a CaipChainId.\n * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by last selected.\n * @param hooks.getCapabilities - A function that returns the capabilities for a given address.\n * @param hooks.trackSessionCreatedEvent - An optional hook for platform specific logic to run.\n * @returns A promise with wallet_createSession handler\n */\nasync function handleWalletCreateSession(\n req: JsonRpcRequest<Params> & { origin: string },\n res: PendingJsonRpcResponse<Result>,\n _next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: WalletCreateSessionHooks,\n): Promise<void> {\n if (!isPlainObject(req.params)) {\n return end(invalidParams({ data: { request: req } }));\n }\n const { requiredScopes, optionalScopes, sessionProperties } = req.params;\n\n if (sessionProperties && Object.keys(sessionProperties).length === 0) {\n return end(new JsonRpcError(5302, 'Invalid sessionProperties requested'));\n }\n\n const filteredSessionProperties = Object.fromEntries(\n Object.entries(sessionProperties ?? {}).filter(([key]) =>\n isKnownSessionPropertyValue(key),\n ),\n );\n\n try {\n const { normalizedRequiredScopes, normalizedOptionalScopes } =\n validateAndNormalizeScopes(requiredScopes || {}, optionalScopes || {});\n\n const requiredScopesWithSupportedMethodsAndNotifications =\n getSupportedScopeObjects(normalizedRequiredScopes, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n });\n const optionalScopesWithSupportedMethodsAndNotifications =\n getSupportedScopeObjects(normalizedOptionalScopes, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n });\n\n const networkClientExistsForChainId = (chainId: Hex) => {\n try {\n hooks.findNetworkClientIdByChainId(chainId);\n return true;\n } catch {\n return false;\n }\n };\n\n // if solana is a requested scope but not supported, we add a promptToCreateSolanaAccount flag to request\n const isSolanaRequested =\n isNamespaceInScopesObject(\n requiredScopesWithSupportedMethodsAndNotifications,\n KnownCaipNamespace.Solana,\n ) ||\n isNamespaceInScopesObject(\n optionalScopesWithSupportedMethodsAndNotifications,\n KnownCaipNamespace.Solana,\n );\n\n let promptToCreateSolanaAccount = false;\n if (isSolanaRequested) {\n const supportedSolanaAccounts =\n hooks.getNonEvmAccountAddresses(SOLANA_CAIP_CHAIN_ID);\n promptToCreateSolanaAccount = supportedSolanaAccounts.length === 0;\n }\n\n const { supportedScopes: supportedRequiredScopes } = bucketScopes(\n requiredScopesWithSupportedMethodsAndNotifications,\n {\n isEvmChainIdSupported: networkClientExistsForChainId,\n isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,\n },\n );\n\n const { supportedScopes: supportedOptionalScopes } = bucketScopes(\n optionalScopesWithSupportedMethodsAndNotifications,\n {\n isEvmChainIdSupported: networkClientExistsForChainId,\n isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,\n },\n );\n\n const allRequestedAccountAddresses = getCaipAccountIdsFromScopesObjects([\n supportedRequiredScopes,\n supportedOptionalScopes,\n ]);\n\n const allSupportedRequestedCaipChainIds = getAllScopesFromScopesObjects([\n supportedRequiredScopes,\n supportedOptionalScopes,\n ]);\n\n const existingEvmAddresses = hooks\n .listAccounts()\n .map((account) => account.address);\n\n const supportedRequestedAccountAddresses =\n allRequestedAccountAddresses.filter(\n (requestedAccountAddress: CaipAccountId) => {\n const {\n address,\n chain: { namespace },\n chainId: caipChainId,\n } = parseCaipAccountId(requestedAccountAddress);\n if (namespace === KnownCaipNamespace.Eip155.toString()) {\n return existingEvmAddresses.some((existingEvmAddress) => {\n return isEqualCaseInsensitive(address, existingEvmAddress);\n });\n }\n\n // If the namespace is not eip155 (EVM) we do a case sensitive check\n return hooks\n .getNonEvmAccountAddresses(caipChainId)\n .some((existingCaipAddress) => {\n return requestedAccountAddress === existingCaipAddress;\n });\n },\n );\n\n const requestedCaip25CaveatValue = {\n requiredScopes: getInternalScopesObject(supportedRequiredScopes),\n optionalScopes: getInternalScopesObject(supportedOptionalScopes),\n isMultichainOrigin: true,\n sessionProperties: filteredSessionProperties,\n };\n\n const requestedCaip25CaveatValueWithSupportedAccounts =\n setNonSCACaipAccountIdsInCaip25CaveatValue(\n requestedCaip25CaveatValue,\n supportedRequestedAccountAddresses,\n );\n\n // if `promptToCreateSolanaAccount` is true and there are no other valid scopes requested,\n // we add a `wallet` scope to the request in order to get passed the CAIP-25 caveat validator.\n // This is very hacky but is necessary because the solana opt-in flow breaks key assumptions\n // of the CAIP-25 permission specification - namely that we can have valid requests with no scopes.\n if (allSupportedRequestedCaipChainIds.length === 0) {\n if (promptToCreateSolanaAccount) {\n requestedCaip25CaveatValueWithSupportedAccounts.optionalScopes[\n KnownCaipNamespace.Wallet\n ] = {\n accounts: [],\n };\n } else {\n // if solana is not requested and there are no supported scopes, we return an error\n return end(\n new JsonRpcError(5100, 'Requested scopes are not supported'),\n );\n }\n }\n\n const [grantedPermissions] = await hooks.requestPermissionsForOrigin(\n {\n [Caip25EndowmentPermissionName]: {\n caveats: [\n {\n type: Caip25CaveatType,\n value: requestedCaip25CaveatValueWithSupportedAccounts,\n },\n ],\n },\n },\n {\n metadata: { promptToCreateSolanaAccount },\n },\n );\n\n const approvedCaip25Permission =\n grantedPermissions[Caip25EndowmentPermissionName];\n const approvedCaip25CaveatValue = approvedCaip25Permission?.caveats?.find(\n (caveat) => caveat.type === Caip25CaveatType,\n )?.value as Caip25CaveatValue;\n if (!approvedCaip25CaveatValue) {\n throw rpcErrors.internal();\n }\n\n const sessionScopes = getSessionScopes(approvedCaip25CaveatValue, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,\n });\n\n const approvedSessionProperties = await getSessionProperties(\n approvedCaip25CaveatValue,\n {\n getCapabilities: hooks.getCapabilities,\n },\n );\n\n hooks.trackSessionCreatedEvent?.(approvedCaip25CaveatValue);\n\n res.result = {\n sessionScopes,\n sessionProperties: approvedSessionProperties,\n };\n return end();\n } catch (err) {\n return end(err);\n }\n}\n\nexport type WalletCreateSessionHandler = MethodHandler<\n WalletCreateSessionHooks,\n never,\n Params,\n Result,\n { origin: string }\n>;\n\nexport const walletCreateSessionHandler = {\n implementation: handleWalletCreateSession,\n hookNames: {\n findNetworkClientIdByChainId: true,\n listAccounts: true,\n requestPermissionsForOrigin: true,\n getNonEvmSupportedMethods: true,\n isNonEvmScopeSupported: true,\n getNonEvmAccountAddresses: true,\n sortAccountIdsByLastSelected: true,\n getCapabilities: true,\n trackSessionCreatedEvent: true,\n },\n} satisfies WalletCreateSessionHandler;\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-createSession.d.cts","sourceRoot":"","sources":["../../src/handlers/wallet-createSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAgBxE,OAAO,KAAK,EACV,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EAClB,4CAA4C;AAE7C,OAAO,KAAK,EACV,aAAa,EACb,wBAAwB,EACxB,yBAAyB,EAC1B,kCAAkC;AACnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,qCAAqC;AAEtE,OAAO,KAAK,EACV,2BAA2B,EAC3B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,wBAAwB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAgMf;AAED,MAAM,MAAM,0BAA0B,GAAG,aAAa,CACpD,wBAAwB,EACxB,KAAK,EACL,MAAM,EACN,MAAM,EACN;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CACnB,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;CAaD,CAAC"}
@@ -1,70 +0,0 @@
1
- import type { AccountsController } from "@metamask/accounts-controller";
2
- import type { Caip25Authorization, NormalizedScopesObject, Caip25CaveatValue } from "@metamask/chain-agnostic-permission";
3
- import type { MethodHandler, JsonRpcEngineEndCallback, JsonRpcEngineNextCallback } from "@metamask/json-rpc-engine";
4
- import type { NetworkController } from "@metamask/network-controller";
5
- import type { GenericPermissionController, RequestedPermissions } from "@metamask/permission-controller";
6
- import type { MultichainRoutingService } from "@metamask/snaps-controllers";
7
- import type { Json, JsonRpcRequest, PendingJsonRpcResponse } from "@metamask/utils";
8
- import type { GetCapabilitiesHook, GetNonEvmSupportedMethodsHook, SortAccountIdsByLastSelectedHook } from "./types.mjs";
9
- export type WalletCreateSessionHooks = GetNonEvmSupportedMethodsHook & SortAccountIdsByLastSelectedHook & GetCapabilitiesHook & {
10
- listAccounts: AccountsController['listAccounts'];
11
- findNetworkClientIdByChainId: NetworkController['findNetworkClientIdByChainId'];
12
- requestPermissionsForOrigin: (requestedPermissions: RequestedPermissions, metadata?: Record<string, Json>) => ReturnType<GenericPermissionController['requestPermissions']>;
13
- isNonEvmScopeSupported: MultichainRoutingService['isSupportedScope'];
14
- getNonEvmAccountAddresses: MultichainRoutingService['getSupportedAccounts'];
15
- trackSessionCreatedEvent: ((approvedCaip25CaveatValue: Caip25CaveatValue) => void) | null;
16
- };
17
- type Params = Caip25Authorization;
18
- type Result = {
19
- sessionScopes: NormalizedScopesObject;
20
- sessionProperties?: Record<string, Json>;
21
- };
22
- /**
23
- * Handler for the `wallet_createSession` RPC method which is responsible
24
- * for prompting for approval and granting a CAIP-25 permission.
25
- *
26
- * This implementation primarily deviates from the CAIP-25 handler
27
- * specification by treating all scopes as optional regardless of
28
- * if they were specified in `requiredScopes` or `optionalScopes`.
29
- * Additionally, provided scopes, methods, notifications, and
30
- * account values that are invalid/malformed are ignored rather than
31
- * causing an error to be returned.
32
- *
33
- * @param req - The request object.
34
- * @param res - The response object.
35
- * @param _next - The next middleware function.
36
- * @param end - The end function.
37
- * @param hooks - The hooks object.
38
- * @param hooks.listAccounts - The hook that returns an array of the wallet's evm accounts.
39
- * @param hooks.findNetworkClientIdByChainId - The hook that returns the networkClientId for a chainId.
40
- * @param hooks.requestPermissionsForOrigin - The hook that approves and grants requested permissions.
41
- * @param hooks.getNonEvmSupportedMethods - The hook that returns the supported methods for a non EVM scope.
42
- * @param hooks.isNonEvmScopeSupported - The hook that returns true if a non EVM scope is supported.
43
- * @param hooks.getNonEvmAccountAddresses - The hook that returns a list of CaipAccountIds that are supported for a CaipChainId.
44
- * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by last selected.
45
- * @param hooks.getCapabilities - A function that returns the capabilities for a given address.
46
- * @param hooks.trackSessionCreatedEvent - An optional hook for platform specific logic to run.
47
- * @returns A promise with wallet_createSession handler
48
- */
49
- declare function handleWalletCreateSession(req: JsonRpcRequest<Params> & {
50
- origin: string;
51
- }, res: PendingJsonRpcResponse<Result>, _next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback, hooks: WalletCreateSessionHooks): Promise<void>;
52
- export type WalletCreateSessionHandler = MethodHandler<WalletCreateSessionHooks, never, Params, Result, {
53
- origin: string;
54
- }>;
55
- export declare const walletCreateSessionHandler: {
56
- implementation: typeof handleWalletCreateSession;
57
- hookNames: {
58
- findNetworkClientIdByChainId: true;
59
- listAccounts: true;
60
- requestPermissionsForOrigin: true;
61
- getNonEvmSupportedMethods: true;
62
- isNonEvmScopeSupported: true;
63
- getNonEvmAccountAddresses: true;
64
- sortAccountIdsByLastSelected: true;
65
- getCapabilities: true;
66
- trackSessionCreatedEvent: true;
67
- };
68
- };
69
- export {};
70
- //# sourceMappingURL=wallet-createSession.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-createSession.d.mts","sourceRoot":"","sources":["../../src/handlers/wallet-createSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sCAAsC;AAgBxE,OAAO,KAAK,EACV,mBAAmB,EACnB,sBAAsB,EACtB,iBAAiB,EAClB,4CAA4C;AAE7C,OAAO,KAAK,EACV,aAAa,EACb,wBAAwB,EACxB,yBAAyB,EAC1B,kCAAkC;AACnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,qCAAqC;AAEtE,OAAO,KAAK,EACV,2BAA2B,EAC3B,oBAAoB,EACrB,wCAAwC;AAEzC,OAAO,KAAK,EAAE,wBAAwB,EAAE,oCAAoC;AAM5E,OAAO,KAAK,EAGV,IAAI,EACJ,cAAc,EACd,sBAAsB,EACvB,wBAAwB;AAEzB,OAAO,KAAK,EACV,mBAAmB,EACnB,6BAA6B,EAC7B,gCAAgC,EACjC,oBAAmB;AAIpB,MAAM,MAAM,wBAAwB,GAAG,6BAA6B,GAClE,gCAAgC,GAChC,mBAAmB,GAAG;IACpB,YAAY,EAAE,kBAAkB,CAAC,cAAc,CAAC,CAAC;IACjD,4BAA4B,EAAE,iBAAiB,CAAC,8BAA8B,CAAC,CAAC;IAChF,2BAA2B,EAAE,CAC3B,oBAAoB,EAAE,oBAAoB,EAC1C,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,KAC5B,UAAU,CAAC,2BAA2B,CAAC,oBAAoB,CAAC,CAAC,CAAC;IACnE,sBAAsB,EAAE,wBAAwB,CAAC,kBAAkB,CAAC,CAAC;IACrE,yBAAyB,EAAE,wBAAwB,CAAC,sBAAsB,CAAC,CAAC;IAC5E,wBAAwB,EACpB,CAAC,CAAC,yBAAyB,EAAE,iBAAiB,KAAK,IAAI,CAAC,GACxD,IAAI,CAAC;CACV,CAAC;AAEJ,KAAK,MAAM,GAAG,mBAAmB,CAAC;AAElC,KAAK,MAAM,GAAG;IACZ,aAAa,EAAE,sBAAsB,CAAC;IACtC,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;CAC1C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,iBAAe,yBAAyB,CACtC,GAAG,EAAE,cAAc,CAAC,MAAM,CAAC,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EAChD,GAAG,EAAE,sBAAsB,CAAC,MAAM,CAAC,EACnC,KAAK,EAAE,yBAAyB,EAChC,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,wBAAwB,GAC9B,OAAO,CAAC,IAAI,CAAC,CAgMf;AAED,MAAM,MAAM,0BAA0B,GAAG,aAAa,CACpD,wBAAwB,EACxB,KAAK,EACL,MAAM,EACN,MAAM,EACN;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CACnB,CAAC;AAEF,eAAO,MAAM,0BAA0B;;;;;;;;;;;;;CAaD,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-createSession.mjs","sourceRoot":"","sources":["../../src/handlers/wallet-createSession.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,6BAA6B,EAC7B,YAAY,EACZ,0BAA0B,EAC1B,uBAAuB,EACvB,gBAAgB,EAChB,oBAAoB,EACpB,wBAAwB,EACxB,2BAA2B,EAC3B,kCAAkC,EAClC,6BAA6B,EAC7B,0CAA0C,EAC1C,yBAAyB,EAC1B,4CAA4C;AAM7C,OAAO,EAAE,sBAAsB,EAAE,mCAAmC;AAOpE,OAAO,EAAE,aAAa,EAAE,wCAAwC;AAKhE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,6BAA6B;AAE/D,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EACnB,wBA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aAAa;YACb,iBAAiB,EAAE,yBAAyB;SAC7C,CAAC;QACF,OAAO,GAAG,EAAE,CAAC;IACf,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAUD,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,cAAc,EAAE,yBAAyB;IACzC,SAAS,EAAE;QACT,4BAA4B,EAAE,IAAI;QAClC,YAAY,EAAE,IAAI;QAClB,2BAA2B,EAAE,IAAI;QACjC,yBAAyB,EAAE,IAAI;QAC/B,sBAAsB,EAAE,IAAI;QAC5B,yBAAyB,EAAE,IAAI;QAC/B,4BAA4B,EAAE,IAAI;QAClC,eAAe,EAAE,IAAI;QACrB,wBAAwB,EAAE,IAAI;KAC/B;CACmC,CAAC","sourcesContent":["import type { AccountsController } from '@metamask/accounts-controller';\nimport {\n Caip25CaveatType,\n Caip25EndowmentPermissionName,\n bucketScopes,\n validateAndNormalizeScopes,\n getInternalScopesObject,\n getSessionScopes,\n getSessionProperties,\n getSupportedScopeObjects,\n isKnownSessionPropertyValue,\n getCaipAccountIdsFromScopesObjects,\n getAllScopesFromScopesObjects,\n setNonSCACaipAccountIdsInCaip25CaveatValue,\n isNamespaceInScopesObject,\n} from '@metamask/chain-agnostic-permission';\nimport type {\n Caip25Authorization,\n NormalizedScopesObject,\n Caip25CaveatValue,\n} from '@metamask/chain-agnostic-permission';\nimport { isEqualCaseInsensitive } from '@metamask/controller-utils';\nimport type {\n MethodHandler,\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n} from '@metamask/json-rpc-engine';\nimport type { NetworkController } from '@metamask/network-controller';\nimport { invalidParams } from '@metamask/permission-controller';\nimport type {\n GenericPermissionController,\n RequestedPermissions,\n} from '@metamask/permission-controller';\nimport { JsonRpcError, rpcErrors } from '@metamask/rpc-errors';\nimport type { MultichainRoutingService } from '@metamask/snaps-controllers';\nimport {\n isPlainObject,\n KnownCaipNamespace,\n parseCaipAccountId,\n} from '@metamask/utils';\nimport type {\n CaipAccountId,\n Hex,\n Json,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n GetCapabilitiesHook,\n GetNonEvmSupportedMethodsHook,\n SortAccountIdsByLastSelectedHook,\n} from './types.js';\n\nconst SOLANA_CAIP_CHAIN_ID = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';\n\nexport type WalletCreateSessionHooks = GetNonEvmSupportedMethodsHook &\n SortAccountIdsByLastSelectedHook &\n GetCapabilitiesHook & {\n listAccounts: AccountsController['listAccounts'];\n findNetworkClientIdByChainId: NetworkController['findNetworkClientIdByChainId'];\n requestPermissionsForOrigin: (\n requestedPermissions: RequestedPermissions,\n metadata?: Record<string, Json>,\n ) => ReturnType<GenericPermissionController['requestPermissions']>;\n isNonEvmScopeSupported: MultichainRoutingService['isSupportedScope'];\n getNonEvmAccountAddresses: MultichainRoutingService['getSupportedAccounts'];\n trackSessionCreatedEvent:\n | ((approvedCaip25CaveatValue: Caip25CaveatValue) => void)\n | null;\n };\n\ntype Params = Caip25Authorization;\n\ntype Result = {\n sessionScopes: NormalizedScopesObject;\n sessionProperties?: Record<string, Json>;\n};\n\n/**\n * Handler for the `wallet_createSession` RPC method which is responsible\n * for prompting for approval and granting a CAIP-25 permission.\n *\n * This implementation primarily deviates from the CAIP-25 handler\n * specification by treating all scopes as optional regardless of\n * if they were specified in `requiredScopes` or `optionalScopes`.\n * Additionally, provided scopes, methods, notifications, and\n * account values that are invalid/malformed are ignored rather than\n * causing an error to be returned.\n *\n * @param req - The request object.\n * @param res - The response object.\n * @param _next - The next middleware function.\n * @param end - The end function.\n * @param hooks - The hooks object.\n * @param hooks.listAccounts - The hook that returns an array of the wallet's evm accounts.\n * @param hooks.findNetworkClientIdByChainId - The hook that returns the networkClientId for a chainId.\n * @param hooks.requestPermissionsForOrigin - The hook that approves and grants requested permissions.\n * @param hooks.getNonEvmSupportedMethods - The hook that returns the supported methods for a non EVM scope.\n * @param hooks.isNonEvmScopeSupported - The hook that returns true if a non EVM scope is supported.\n * @param hooks.getNonEvmAccountAddresses - The hook that returns a list of CaipAccountIds that are supported for a CaipChainId.\n * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by last selected.\n * @param hooks.getCapabilities - A function that returns the capabilities for a given address.\n * @param hooks.trackSessionCreatedEvent - An optional hook for platform specific logic to run.\n * @returns A promise with wallet_createSession handler\n */\nasync function handleWalletCreateSession(\n req: JsonRpcRequest<Params> & { origin: string },\n res: PendingJsonRpcResponse<Result>,\n _next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: WalletCreateSessionHooks,\n): Promise<void> {\n if (!isPlainObject(req.params)) {\n return end(invalidParams({ data: { request: req } }));\n }\n const { requiredScopes, optionalScopes, sessionProperties } = req.params;\n\n if (sessionProperties && Object.keys(sessionProperties).length === 0) {\n return end(new JsonRpcError(5302, 'Invalid sessionProperties requested'));\n }\n\n const filteredSessionProperties = Object.fromEntries(\n Object.entries(sessionProperties ?? {}).filter(([key]) =>\n isKnownSessionPropertyValue(key),\n ),\n );\n\n try {\n const { normalizedRequiredScopes, normalizedOptionalScopes } =\n validateAndNormalizeScopes(requiredScopes || {}, optionalScopes || {});\n\n const requiredScopesWithSupportedMethodsAndNotifications =\n getSupportedScopeObjects(normalizedRequiredScopes, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n });\n const optionalScopesWithSupportedMethodsAndNotifications =\n getSupportedScopeObjects(normalizedOptionalScopes, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n });\n\n const networkClientExistsForChainId = (chainId: Hex) => {\n try {\n hooks.findNetworkClientIdByChainId(chainId);\n return true;\n } catch {\n return false;\n }\n };\n\n // if solana is a requested scope but not supported, we add a promptToCreateSolanaAccount flag to request\n const isSolanaRequested =\n isNamespaceInScopesObject(\n requiredScopesWithSupportedMethodsAndNotifications,\n KnownCaipNamespace.Solana,\n ) ||\n isNamespaceInScopesObject(\n optionalScopesWithSupportedMethodsAndNotifications,\n KnownCaipNamespace.Solana,\n );\n\n let promptToCreateSolanaAccount = false;\n if (isSolanaRequested) {\n const supportedSolanaAccounts =\n hooks.getNonEvmAccountAddresses(SOLANA_CAIP_CHAIN_ID);\n promptToCreateSolanaAccount = supportedSolanaAccounts.length === 0;\n }\n\n const { supportedScopes: supportedRequiredScopes } = bucketScopes(\n requiredScopesWithSupportedMethodsAndNotifications,\n {\n isEvmChainIdSupported: networkClientExistsForChainId,\n isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,\n },\n );\n\n const { supportedScopes: supportedOptionalScopes } = bucketScopes(\n optionalScopesWithSupportedMethodsAndNotifications,\n {\n isEvmChainIdSupported: networkClientExistsForChainId,\n isEvmChainIdSupportable: () => false, // intended for future usage with eip3085 scopedProperties\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n isNonEvmScopeSupported: hooks.isNonEvmScopeSupported,\n },\n );\n\n const allRequestedAccountAddresses = getCaipAccountIdsFromScopesObjects([\n supportedRequiredScopes,\n supportedOptionalScopes,\n ]);\n\n const allSupportedRequestedCaipChainIds = getAllScopesFromScopesObjects([\n supportedRequiredScopes,\n supportedOptionalScopes,\n ]);\n\n const existingEvmAddresses = hooks\n .listAccounts()\n .map((account) => account.address);\n\n const supportedRequestedAccountAddresses =\n allRequestedAccountAddresses.filter(\n (requestedAccountAddress: CaipAccountId) => {\n const {\n address,\n chain: { namespace },\n chainId: caipChainId,\n } = parseCaipAccountId(requestedAccountAddress);\n if (namespace === KnownCaipNamespace.Eip155.toString()) {\n return existingEvmAddresses.some((existingEvmAddress) => {\n return isEqualCaseInsensitive(address, existingEvmAddress);\n });\n }\n\n // If the namespace is not eip155 (EVM) we do a case sensitive check\n return hooks\n .getNonEvmAccountAddresses(caipChainId)\n .some((existingCaipAddress) => {\n return requestedAccountAddress === existingCaipAddress;\n });\n },\n );\n\n const requestedCaip25CaveatValue = {\n requiredScopes: getInternalScopesObject(supportedRequiredScopes),\n optionalScopes: getInternalScopesObject(supportedOptionalScopes),\n isMultichainOrigin: true,\n sessionProperties: filteredSessionProperties,\n };\n\n const requestedCaip25CaveatValueWithSupportedAccounts =\n setNonSCACaipAccountIdsInCaip25CaveatValue(\n requestedCaip25CaveatValue,\n supportedRequestedAccountAddresses,\n );\n\n // if `promptToCreateSolanaAccount` is true and there are no other valid scopes requested,\n // we add a `wallet` scope to the request in order to get passed the CAIP-25 caveat validator.\n // This is very hacky but is necessary because the solana opt-in flow breaks key assumptions\n // of the CAIP-25 permission specification - namely that we can have valid requests with no scopes.\n if (allSupportedRequestedCaipChainIds.length === 0) {\n if (promptToCreateSolanaAccount) {\n requestedCaip25CaveatValueWithSupportedAccounts.optionalScopes[\n KnownCaipNamespace.Wallet\n ] = {\n accounts: [],\n };\n } else {\n // if solana is not requested and there are no supported scopes, we return an error\n return end(\n new JsonRpcError(5100, 'Requested scopes are not supported'),\n );\n }\n }\n\n const [grantedPermissions] = await hooks.requestPermissionsForOrigin(\n {\n [Caip25EndowmentPermissionName]: {\n caveats: [\n {\n type: Caip25CaveatType,\n value: requestedCaip25CaveatValueWithSupportedAccounts,\n },\n ],\n },\n },\n {\n metadata: { promptToCreateSolanaAccount },\n },\n );\n\n const approvedCaip25Permission =\n grantedPermissions[Caip25EndowmentPermissionName];\n const approvedCaip25CaveatValue = approvedCaip25Permission?.caveats?.find(\n (caveat) => caveat.type === Caip25CaveatType,\n )?.value as Caip25CaveatValue;\n if (!approvedCaip25CaveatValue) {\n throw rpcErrors.internal();\n }\n\n const sessionScopes = getSessionScopes(approvedCaip25CaveatValue, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,\n });\n\n const approvedSessionProperties = await getSessionProperties(\n approvedCaip25CaveatValue,\n {\n getCapabilities: hooks.getCapabilities,\n },\n );\n\n hooks.trackSessionCreatedEvent?.(approvedCaip25CaveatValue);\n\n res.result = {\n sessionScopes,\n sessionProperties: approvedSessionProperties,\n };\n return end();\n } catch (err) {\n return end(err);\n }\n}\n\nexport type WalletCreateSessionHandler = MethodHandler<\n WalletCreateSessionHooks,\n never,\n Params,\n Result,\n { origin: string }\n>;\n\nexport const walletCreateSessionHandler = {\n implementation: handleWalletCreateSession,\n hookNames: {\n findNetworkClientIdByChainId: true,\n listAccounts: true,\n requestPermissionsForOrigin: true,\n getNonEvmSupportedMethods: true,\n isNonEvmScopeSupported: true,\n getNonEvmAccountAddresses: true,\n sortAccountIdsByLastSelected: true,\n getCapabilities: true,\n trackSessionCreatedEvent: true,\n },\n} satisfies WalletCreateSessionHandler;\n"]}
@@ -1,54 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.walletGetSessionHandler = void 0;
4
- const chain_agnostic_permission_1 = require("@metamask/chain-agnostic-permission");
5
- /**
6
- * Handler for the `wallet_getSession` RPC method as specified by [CAIP-312](https://chainagnostic.org/CAIPs/caip-312).
7
- * The implementation below deviates from the linked spec in that it ignores the `sessionId` param entirely,
8
- * and that an empty object is returned for the `sessionScopes` result rather than throwing an error if there
9
- * is no active session for the origin.
10
- *
11
- * @param _request - The request object.
12
- * @param response - The response object.
13
- * @param _next - The next middleware function. Unused.
14
- * @param end - The end function.
15
- * @param hooks - The hooks object.
16
- * @param hooks.getCaveatForOrigin - Function to retrieve a caveat for the origin.
17
- * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.
18
- * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by corresponding last selected account in the wallet.
19
- * @param hooks.getCapabilities - A function that returns the capabilities for a given address.
20
- * @returns Nothing.
21
- */
22
- async function handleWalletGetSession(_request, response, _next, end, hooks) {
23
- let caveat;
24
- try {
25
- caveat = hooks.getCaveatForOrigin(chain_agnostic_permission_1.Caip25EndowmentPermissionName, chain_agnostic_permission_1.Caip25CaveatType);
26
- }
27
- catch {
28
- // noop
29
- }
30
- if (!caveat) {
31
- response.result = { sessionScopes: {}, sessionProperties: {} };
32
- return end();
33
- }
34
- response.result = {
35
- sessionScopes: (0, chain_agnostic_permission_1.getSessionScopes)(caveat.value, {
36
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
37
- sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,
38
- }),
39
- sessionProperties: await (0, chain_agnostic_permission_1.getSessionProperties)(caveat.value, {
40
- getCapabilities: hooks.getCapabilities,
41
- }),
42
- };
43
- return end();
44
- }
45
- exports.walletGetSessionHandler = {
46
- implementation: handleWalletGetSession,
47
- hookNames: {
48
- getCaveatForOrigin: true,
49
- getNonEvmSupportedMethods: true,
50
- sortAccountIdsByLastSelected: true,
51
- getCapabilities: true,
52
- },
53
- };
54
- //# sourceMappingURL=wallet-getSession.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-getSession.cjs","sourceRoot":"","sources":["../../src/handlers/wallet-getSession.ts"],"names":[],"mappings":";;;AACA,mFAK6C;AA+B7C;;;;;;;;;;;;;;;;GAgBG;AACH,KAAK,UAAU,sBAAsB,CACnC,QAA6C,EAC7C,QAAwD,EACxD,KAAgC,EAChC,GAA6B,EAC7B,KAA4B;IAE5B,IAAI,MAAgC,CAAC;IACrC,IAAI,CAAC;QACH,MAAM,GAAG,KAAK,CAAC,kBAAkB,CAC/B,yDAA6B,EAC7B,4CAAgB,CACW,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,QAAQ,CAAC,MAAM,GAAG,EAAE,aAAa,EAAE,EAAE,EAAE,iBAAiB,EAAE,EAAE,EAAE,CAAC;QAC/D,OAAO,GAAG,EAAE,CAAC;IACf,CAAC;IAED,QAAQ,CAAC,MAAM,GAAG;QAChB,aAAa,EAAE,IAAA,4CAAgB,EAAC,MAAM,CAAC,KAAK,EAAE;YAC5C,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,4BAA4B,EAAE,KAAK,CAAC,4BAA4B;SACjE,CAAC;QACF,iBAAiB,EAAE,MAAM,IAAA,gDAAoB,EAAC,MAAM,CAAC,KAAK,EAAE;YAC1D,eAAe,EAAE,KAAK,CAAC,eAAe;SACvC,CAAC;KACH,CAAC;IACF,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAUY,QAAA,uBAAuB,GAAG;IACrC,cAAc,EAAE,sBAAsB;IACtC,SAAS,EAAE;QACT,kBAAkB,EAAE,IAAI;QACxB,yBAAyB,EAAE,IAAI;QAC/B,4BAA4B,EAAE,IAAI;QAClC,eAAe,EAAE,IAAI;KACtB;CACgC,CAAC","sourcesContent":["import type { NormalizedScopesObject } from '@metamask/chain-agnostic-permission';\nimport {\n Caip25CaveatType,\n Caip25EndowmentPermissionName,\n getSessionProperties,\n getSessionScopes,\n} from '@metamask/chain-agnostic-permission';\nimport type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n MethodHandler,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n Caip25Caveat,\n GetCapabilitiesHook,\n GetCaveatForOriginHook,\n GetNonEvmSupportedMethodsHook,\n SortAccountIdsByLastSelectedHook,\n} from './types.js';\n\ntype WalletGetSessionResult = {\n sessionScopes: NormalizedScopesObject;\n sessionProperties: Record<string, Json>;\n};\n\nexport type WalletGetSessionHooks = GetCaveatForOriginHook &\n GetNonEvmSupportedMethodsHook &\n SortAccountIdsByLastSelectedHook &\n GetCapabilitiesHook;\n\n/**\n * Handler for the `wallet_getSession` RPC method as specified by [CAIP-312](https://chainagnostic.org/CAIPs/caip-312).\n * The implementation below deviates from the linked spec in that it ignores the `sessionId` param entirely,\n * and that an empty object is returned for the `sessionScopes` result rather than throwing an error if there\n * is no active session for the origin.\n *\n * @param _request - The request object.\n * @param response - The response object.\n * @param _next - The next middleware function. Unused.\n * @param end - The end function.\n * @param hooks - The hooks object.\n * @param hooks.getCaveatForOrigin - Function to retrieve a caveat for the origin.\n * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.\n * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by corresponding last selected account in the wallet.\n * @param hooks.getCapabilities - A function that returns the capabilities for a given address.\n * @returns Nothing.\n */\nasync function handleWalletGetSession(\n _request: JsonRpcRequest & { origin: string },\n response: PendingJsonRpcResponse<WalletGetSessionResult>,\n _next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: WalletGetSessionHooks,\n) {\n let caveat: Caip25Caveat | undefined;\n try {\n caveat = hooks.getCaveatForOrigin(\n Caip25EndowmentPermissionName,\n Caip25CaveatType,\n ) as Caip25Caveat | undefined;\n } catch {\n // noop\n }\n\n if (!caveat) {\n response.result = { sessionScopes: {}, sessionProperties: {} };\n return end();\n }\n\n response.result = {\n sessionScopes: getSessionScopes(caveat.value, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,\n }),\n sessionProperties: await getSessionProperties(caveat.value, {\n getCapabilities: hooks.getCapabilities,\n }),\n };\n return end();\n}\n\nexport type WalletGetSessionHandler = MethodHandler<\n WalletGetSessionHooks,\n never,\n JsonRpcParams,\n WalletGetSessionResult,\n { origin: string }\n>;\n\nexport const walletGetSessionHandler = {\n implementation: handleWalletGetSession,\n hookNames: {\n getCaveatForOrigin: true,\n getNonEvmSupportedMethods: true,\n sortAccountIdsByLastSelected: true,\n getCapabilities: true,\n },\n} satisfies WalletGetSessionHandler;\n"]}
@@ -1,43 +0,0 @@
1
- import type { NormalizedScopesObject } from "@metamask/chain-agnostic-permission";
2
- import type { JsonRpcEngineEndCallback, JsonRpcEngineNextCallback, MethodHandler } from "@metamask/json-rpc-engine";
3
- import type { Json, JsonRpcParams, JsonRpcRequest, PendingJsonRpcResponse } from "@metamask/utils";
4
- import type { GetCapabilitiesHook, GetCaveatForOriginHook, GetNonEvmSupportedMethodsHook, SortAccountIdsByLastSelectedHook } from "./types.cjs";
5
- type WalletGetSessionResult = {
6
- sessionScopes: NormalizedScopesObject;
7
- sessionProperties: Record<string, Json>;
8
- };
9
- export type WalletGetSessionHooks = GetCaveatForOriginHook & GetNonEvmSupportedMethodsHook & SortAccountIdsByLastSelectedHook & GetCapabilitiesHook;
10
- /**
11
- * Handler for the `wallet_getSession` RPC method as specified by [CAIP-312](https://chainagnostic.org/CAIPs/caip-312).
12
- * The implementation below deviates from the linked spec in that it ignores the `sessionId` param entirely,
13
- * and that an empty object is returned for the `sessionScopes` result rather than throwing an error if there
14
- * is no active session for the origin.
15
- *
16
- * @param _request - The request object.
17
- * @param response - The response object.
18
- * @param _next - The next middleware function. Unused.
19
- * @param end - The end function.
20
- * @param hooks - The hooks object.
21
- * @param hooks.getCaveatForOrigin - Function to retrieve a caveat for the origin.
22
- * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.
23
- * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by corresponding last selected account in the wallet.
24
- * @param hooks.getCapabilities - A function that returns the capabilities for a given address.
25
- * @returns Nothing.
26
- */
27
- declare function handleWalletGetSession(_request: JsonRpcRequest & {
28
- origin: string;
29
- }, response: PendingJsonRpcResponse<WalletGetSessionResult>, _next: JsonRpcEngineNextCallback, end: JsonRpcEngineEndCallback, hooks: WalletGetSessionHooks): Promise<void>;
30
- export type WalletGetSessionHandler = MethodHandler<WalletGetSessionHooks, never, JsonRpcParams, WalletGetSessionResult, {
31
- origin: string;
32
- }>;
33
- export declare const walletGetSessionHandler: {
34
- implementation: typeof handleWalletGetSession;
35
- hookNames: {
36
- getCaveatForOrigin: true;
37
- getNonEvmSupportedMethods: true;
38
- sortAccountIdsByLastSelected: true;
39
- getCapabilities: true;
40
- };
41
- };
42
- export {};
43
- //# sourceMappingURL=wallet-getSession.d.cts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-getSession.d.cts","sourceRoot":"","sources":["../../src/handlers/wallet-getSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,4CAA4C;AAOlF,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,EACd,kCAAkC;AACnC,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,wBAAwB;AAEzB,OAAO,KAAK,EAEV,mBAAmB,EACnB,sBAAsB,EACtB,6BAA6B,EAC7B,gCAAgC,EACjC,oBAAmB;AAEpB,KAAK,sBAAsB,GAAG;IAC5B,aAAa,EAAE,sBAAsB,CAAC;IACtC,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,sBAAsB,GACxD,6BAA6B,GAC7B,gCAAgC,GAChC,mBAAmB,CAAC;AAEtB;;;;;;;;;;;;;;;;GAgBG;AACH,iBAAe,sBAAsB,CACnC,QAAQ,EAAE,cAAc,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EAC7C,QAAQ,EAAE,sBAAsB,CAAC,sBAAsB,CAAC,EACxD,KAAK,EAAE,yBAAyB,EAChC,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,qBAAqB,iBA2B7B;AAED,MAAM,MAAM,uBAAuB,GAAG,aAAa,CACjD,qBAAqB,EACrB,KAAK,EACL,aAAa,EACb,sBAAsB,EACtB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CACnB,CAAC;AAEF,eAAO,MAAM,uBAAuB;;;;;;;;CAQD,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-getSession.d.mts","sourceRoot":"","sources":["../../src/handlers/wallet-getSession.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,4CAA4C;AAOlF,OAAO,KAAK,EACV,wBAAwB,EACxB,yBAAyB,EACzB,aAAa,EACd,kCAAkC;AACnC,OAAO,KAAK,EACV,IAAI,EACJ,aAAa,EACb,cAAc,EACd,sBAAsB,EACvB,wBAAwB;AAEzB,OAAO,KAAK,EAEV,mBAAmB,EACnB,sBAAsB,EACtB,6BAA6B,EAC7B,gCAAgC,EACjC,oBAAmB;AAEpB,KAAK,sBAAsB,GAAG;IAC5B,aAAa,EAAE,sBAAsB,CAAC;IACtC,iBAAiB,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;CACzC,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG,sBAAsB,GACxD,6BAA6B,GAC7B,gCAAgC,GAChC,mBAAmB,CAAC;AAEtB;;;;;;;;;;;;;;;;GAgBG;AACH,iBAAe,sBAAsB,CACnC,QAAQ,EAAE,cAAc,GAAG;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,EAC7C,QAAQ,EAAE,sBAAsB,CAAC,sBAAsB,CAAC,EACxD,KAAK,EAAE,yBAAyB,EAChC,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,qBAAqB,iBA2B7B;AAED,MAAM,MAAM,uBAAuB,GAAG,aAAa,CACjD,qBAAqB,EACrB,KAAK,EACL,aAAa,EACb,sBAAsB,EACtB;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CACnB,CAAC;AAEF,eAAO,MAAM,uBAAuB;;;;;;;;CAQD,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-getSession.mjs","sourceRoot":"","sources":["../../src/handlers/wallet-getSession.ts"],"names":[],"mappings":"AACA,OAAO,EACL,gBAAgB,EAChB,6BAA6B,EAC7B,oBAAoB,EACpB,gBAAgB,EACjB,4CAA4C;AA+B7C;;;;;;;;;;;;;;;;GAgBG;AACH,KAAK,UAAU,sBAAsB,CACnC,QAA6C,EAC7C,QAAwD,EACxD,KAAgC,EAChC,GAA6B,EAC7B,KAA4B;IAE5B,IAAI,MAAgC,CAAC;IACrC,IAAI,CAAC;QACH,MAAM,GAAG,KAAK,CAAC,kBAAkB,CAC/B,6BAA6B,EAC7B,gBAAgB,CACW,CAAC;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO;IACT,CAAC;IAED,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,QAAQ,CAAC,MAAM,GAAG,EAAE,aAAa,EAAE,EAAE,EAAE,iBAAiB,EAAE,EAAE,EAAE,CAAC;QAC/D,OAAO,GAAG,EAAE,CAAC;IACf,CAAC;IAED,QAAQ,CAAC,MAAM,GAAG;QAChB,aAAa,EAAE,gBAAgB,CAAC,MAAM,CAAC,KAAK,EAAE;YAC5C,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;YAC1D,4BAA4B,EAAE,KAAK,CAAC,4BAA4B;SACjE,CAAC;QACF,iBAAiB,EAAE,MAAM,oBAAoB,CAAC,MAAM,CAAC,KAAK,EAAE;YAC1D,eAAe,EAAE,KAAK,CAAC,eAAe;SACvC,CAAC;KACH,CAAC;IACF,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAUD,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,cAAc,EAAE,sBAAsB;IACtC,SAAS,EAAE;QACT,kBAAkB,EAAE,IAAI;QACxB,yBAAyB,EAAE,IAAI;QAC/B,4BAA4B,EAAE,IAAI;QAClC,eAAe,EAAE,IAAI;KACtB;CACgC,CAAC","sourcesContent":["import type { NormalizedScopesObject } from '@metamask/chain-agnostic-permission';\nimport {\n Caip25CaveatType,\n Caip25EndowmentPermissionName,\n getSessionProperties,\n getSessionScopes,\n} from '@metamask/chain-agnostic-permission';\nimport type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n MethodHandler,\n} from '@metamask/json-rpc-engine';\nimport type {\n Json,\n JsonRpcParams,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n Caip25Caveat,\n GetCapabilitiesHook,\n GetCaveatForOriginHook,\n GetNonEvmSupportedMethodsHook,\n SortAccountIdsByLastSelectedHook,\n} from './types.js';\n\ntype WalletGetSessionResult = {\n sessionScopes: NormalizedScopesObject;\n sessionProperties: Record<string, Json>;\n};\n\nexport type WalletGetSessionHooks = GetCaveatForOriginHook &\n GetNonEvmSupportedMethodsHook &\n SortAccountIdsByLastSelectedHook &\n GetCapabilitiesHook;\n\n/**\n * Handler for the `wallet_getSession` RPC method as specified by [CAIP-312](https://chainagnostic.org/CAIPs/caip-312).\n * The implementation below deviates from the linked spec in that it ignores the `sessionId` param entirely,\n * and that an empty object is returned for the `sessionScopes` result rather than throwing an error if there\n * is no active session for the origin.\n *\n * @param _request - The request object.\n * @param response - The response object.\n * @param _next - The next middleware function. Unused.\n * @param end - The end function.\n * @param hooks - The hooks object.\n * @param hooks.getCaveatForOrigin - Function to retrieve a caveat for the origin.\n * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.\n * @param hooks.sortAccountIdsByLastSelected - A function that accepts an array of CaipAccountId and returns an array of CaipAccountId sorted by corresponding last selected account in the wallet.\n * @param hooks.getCapabilities - A function that returns the capabilities for a given address.\n * @returns Nothing.\n */\nasync function handleWalletGetSession(\n _request: JsonRpcRequest & { origin: string },\n response: PendingJsonRpcResponse<WalletGetSessionResult>,\n _next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: WalletGetSessionHooks,\n) {\n let caveat: Caip25Caveat | undefined;\n try {\n caveat = hooks.getCaveatForOrigin(\n Caip25EndowmentPermissionName,\n Caip25CaveatType,\n ) as Caip25Caveat | undefined;\n } catch {\n // noop\n }\n\n if (!caveat) {\n response.result = { sessionScopes: {}, sessionProperties: {} };\n return end();\n }\n\n response.result = {\n sessionScopes: getSessionScopes(caveat.value, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,\n }),\n sessionProperties: await getSessionProperties(caveat.value, {\n getCapabilities: hooks.getCapabilities,\n }),\n };\n return end();\n}\n\nexport type WalletGetSessionHandler = MethodHandler<\n WalletGetSessionHooks,\n never,\n JsonRpcParams,\n WalletGetSessionResult,\n { origin: string }\n>;\n\nexport const walletGetSessionHandler = {\n implementation: handleWalletGetSession,\n hookNames: {\n getCaveatForOrigin: true,\n getNonEvmSupportedMethods: true,\n sortAccountIdsByLastSelected: true,\n getCapabilities: true,\n },\n} satisfies WalletGetSessionHandler;\n"]}
@@ -1,103 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.walletInvokeMethodHandler = void 0;
4
- const chain_agnostic_permission_1 = require("@metamask/chain-agnostic-permission");
5
- const rpc_errors_1 = require("@metamask/rpc-errors");
6
- const utils_1 = require("@metamask/utils");
7
- /**
8
- * Handler for the `wallet_invokeMethod` RPC method as specified by [CAIP-27](https://chainagnostic.org/CAIPs/caip-27).
9
- * The implementation below deviates from the linked spec in that it ignores the `sessionId` param
10
- * and instead uses the singular session for the origin if available.
11
- *
12
- * @param request - The request object.
13
- * @param response - The response object. Unused.
14
- * @param next - The next middleware function.
15
- * @param end - The end function.
16
- * @param hooks - The hooks object.
17
- * @param hooks.getCaveatForOrigin - the hook for getting a caveat from a permission for an origin.
18
- * @param hooks.findNetworkClientIdByChainId - the hook for finding the networkClientId for a chainId.
19
- * @param hooks.getSelectedNetworkClientId - the hook for getting the current globally selected networkClientId.
20
- * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.
21
- * @param hooks.sortAccountIdsByLastSelected - A function that sorts accounts by their last selected order.
22
- * @param hooks.handleNonEvmRequestForOrigin - A function that sends a request to the MultichainRouter for processing.
23
- * @returns Nothing.
24
- */
25
- async function handleWalletInvokeMethod(request, response, next, end, hooks) {
26
- if (!(0, utils_1.isObject)(request.params)) {
27
- return end(rpc_errors_1.rpcErrors.invalidParams({ data: { request } }));
28
- }
29
- const { scope, request: wrappedRequest } = request.params;
30
- (0, chain_agnostic_permission_1.assertIsInternalScopeString)(scope);
31
- let caveat;
32
- try {
33
- caveat = hooks.getCaveatForOrigin(chain_agnostic_permission_1.Caip25EndowmentPermissionName, chain_agnostic_permission_1.Caip25CaveatType);
34
- }
35
- catch {
36
- // noop
37
- }
38
- if (!caveat) {
39
- return end(rpc_errors_1.providerErrors.unauthorized());
40
- }
41
- const scopeObject = (0, chain_agnostic_permission_1.getSessionScopes)(caveat.value, {
42
- getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,
43
- sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,
44
- })[scope];
45
- if (!scopeObject?.methods?.includes(wrappedRequest.method)) {
46
- return end(rpc_errors_1.providerErrors.unauthorized());
47
- }
48
- const { namespace, reference } = (0, chain_agnostic_permission_1.parseScopeString)(scope);
49
- const isEvmRequest = (namespace === utils_1.KnownCaipNamespace.Wallet &&
50
- (!reference || reference === utils_1.KnownCaipNamespace.Eip155)) ||
51
- namespace === utils_1.KnownCaipNamespace.Eip155;
52
- const unwrappedRequest = {
53
- ...request,
54
- scope,
55
- method: wrappedRequest.method,
56
- params: wrappedRequest.params,
57
- };
58
- if (isEvmRequest) {
59
- let networkClientId;
60
- if (namespace === utils_1.KnownCaipNamespace.Wallet) {
61
- networkClientId = hooks.getSelectedNetworkClientId();
62
- }
63
- else if (namespace === utils_1.KnownCaipNamespace.Eip155) {
64
- if (reference) {
65
- networkClientId = hooks.findNetworkClientIdByChainId((0, utils_1.numberToHex)(parseInt(reference, 10)));
66
- }
67
- }
68
- if (!networkClientId) {
69
- console.error('failed to resolve network client for wallet_invokeMethod', request);
70
- return end(rpc_errors_1.rpcErrors.internal());
71
- }
72
- Object.assign(request, {
73
- ...unwrappedRequest,
74
- networkClientId,
75
- });
76
- return next();
77
- }
78
- try {
79
- response.result = await hooks.handleNonEvmRequestForOrigin({
80
- connectedAddresses: scopeObject.accounts,
81
- // Type assertion: We know that scope is not "wallet" by now because it
82
- // is already being handled above.
83
- scope: scope,
84
- request: unwrappedRequest,
85
- });
86
- }
87
- catch (err) {
88
- return end(err);
89
- }
90
- return end();
91
- }
92
- exports.walletInvokeMethodHandler = {
93
- implementation: handleWalletInvokeMethod,
94
- hookNames: {
95
- getCaveatForOrigin: true,
96
- findNetworkClientIdByChainId: true,
97
- getSelectedNetworkClientId: true,
98
- getNonEvmSupportedMethods: true,
99
- sortAccountIdsByLastSelected: true,
100
- handleNonEvmRequestForOrigin: true,
101
- },
102
- };
103
- //# sourceMappingURL=wallet-invokeMethod.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wallet-invokeMethod.cjs","sourceRoot":"","sources":["../../src/handlers/wallet-invokeMethod.ts"],"names":[],"mappings":";;;AACA,mFAM6C;AAU7C,qDAAiE;AAEjE,2CAA4E;AAsC5E;;;;;;;;;;;;;;;;;GAiBG;AACH,KAAK,UAAU,wBAAwB,CACrC,OAAkC,EAClC,QAAsC,EACtC,IAA+B,EAC/B,GAA6B,EAC7B,KAA8B;IAE9B,IAAI,CAAC,IAAA,gBAAQ,EAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAC9B,OAAO,GAAG,CAAC,sBAAS,CAAC,aAAa,CAAC,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAC7D,CAAC;IAED,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC;IAC1D,IAAA,uDAA2B,EAAC,KAAK,CAAC,CAAC;IAEnC,IAAI,MAAgC,CAAC;IACrC,IAAI,CAAC;QACH,MAAM,GAAG,KAAK,CAAC,kBAAkB,CAC/B,yDAA6B,EAC7B,4CAAgB,CACW,CA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ClD,IAAA,mBAAW,EAAC,QAAQ,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,CACrC,CAAC;YACJ,CAAC;QACH,CAAC;QAED,IAAI,CAAC,eAAe,EAAE,CAAC;YACrB,OAAO,CAAC,KAAK,CACX,0DAA0D,EAC1D,OAAO,CACR,CAAC;YACF,OAAO,GAAG,CAAC,sBAAS,CAAC,QAAQ,EAAE,CAAC,CAAC;QACnC,CAAC;QAED,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE;YACrB,GAAG,gBAAgB;YACnB,eAAe;SAChB,CAAC,CAAC;QACH,OAAO,IAAI,EAAE,CAAC;IAChB,CAAC;IAED,IAAI,CAAC;QACH,QAAQ,CAAC,MAAM,GAAG,MAAM,KAAK,CAAC,4BAA4B,CAAC;YACzD,kBAAkB,EAAE,WAAW,CAAC,QAAQ;YACxC,uEAAuE;YACvE,kCAAkC;YAClC,KAAK,EAAE,KAAoB;YAC3B,OAAO,EAAE,gBAAgB;SAC1B,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,GAAG,CAAC,GAAY,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,GAAG,EAAE,CAAC;AACf,CAAC;AAUY,QAAA,yBAAyB,GAAG;IACvC,cAAc,EAAE,wBAAwB;IACxC,SAAS,EAAE;QACT,kBAAkB,EAAE,IAAI;QACxB,4BAA4B,EAAE,IAAI;QAClC,0BAA0B,EAAE,IAAI;QAChC,yBAAyB,EAAE,IAAI;QAC/B,4BAA4B,EAAE,IAAI;QAClC,4BAA4B,EAAE,IAAI;KACnC;CACkC,CAAC","sourcesContent":["import type { ExternalScopeString } from '@metamask/chain-agnostic-permission';\nimport {\n Caip25CaveatType,\n Caip25EndowmentPermissionName,\n assertIsInternalScopeString,\n getSessionScopes,\n parseScopeString,\n} from '@metamask/chain-agnostic-permission';\nimport type {\n JsonRpcEngineEndCallback,\n JsonRpcEngineNextCallback,\n MethodHandler,\n} from '@metamask/json-rpc-engine';\nimport type {\n NetworkClientId,\n NetworkController,\n} from '@metamask/network-controller';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { MultichainRoutingService } from '@metamask/snaps-controllers';\nimport { isObject, KnownCaipNamespace, numberToHex } from '@metamask/utils';\nimport type {\n CaipAccountId,\n CaipChainId,\n Json,\n JsonRpcRequest,\n PendingJsonRpcResponse,\n} from '@metamask/utils';\n\nimport type {\n Caip25Caveat,\n GetCaveatForOriginHook,\n GetNonEvmSupportedMethodsHook,\n SortAccountIdsByLastSelectedHook,\n} from './types.js';\n\nexport type WalletInvokeMethodParams = {\n scope: ExternalScopeString;\n request: Pick<JsonRpcRequest, 'method' | 'params'>;\n};\n\nexport type WalletInvokeMethodRequest =\n JsonRpcRequest<WalletInvokeMethodParams> & {\n origin: string;\n };\n\nexport type WalletInvokeMethodHooks = GetCaveatForOriginHook &\n GetNonEvmSupportedMethodsHook &\n SortAccountIdsByLastSelectedHook & {\n findNetworkClientIdByChainId: NetworkController['findNetworkClientIdByChainId'];\n getSelectedNetworkClientId: () => NetworkClientId;\n handleNonEvmRequestForOrigin: (params: {\n connectedAddresses: CaipAccountId[];\n scope: CaipChainId;\n request: JsonRpcRequest;\n }) => ReturnType<MultichainRoutingService['handleRequest']>;\n };\n\n/**\n * Handler for the `wallet_invokeMethod` RPC method as specified by [CAIP-27](https://chainagnostic.org/CAIPs/caip-27).\n * The implementation below deviates from the linked spec in that it ignores the `sessionId` param\n * and instead uses the singular session for the origin if available.\n *\n * @param request - The request object.\n * @param response - The response object. Unused.\n * @param next - The next middleware function.\n * @param end - The end function.\n * @param hooks - The hooks object.\n * @param hooks.getCaveatForOrigin - the hook for getting a caveat from a permission for an origin.\n * @param hooks.findNetworkClientIdByChainId - the hook for finding the networkClientId for a chainId.\n * @param hooks.getSelectedNetworkClientId - the hook for getting the current globally selected networkClientId.\n * @param hooks.getNonEvmSupportedMethods - A function that returns the supported methods for a non EVM scope.\n * @param hooks.sortAccountIdsByLastSelected - A function that sorts accounts by their last selected order.\n * @param hooks.handleNonEvmRequestForOrigin - A function that sends a request to the MultichainRouter for processing.\n * @returns Nothing.\n */\nasync function handleWalletInvokeMethod(\n request: WalletInvokeMethodRequest,\n response: PendingJsonRpcResponse<Json>,\n next: JsonRpcEngineNextCallback,\n end: JsonRpcEngineEndCallback,\n hooks: WalletInvokeMethodHooks,\n) {\n if (!isObject(request.params)) {\n return end(rpcErrors.invalidParams({ data: { request } }));\n }\n\n const { scope, request: wrappedRequest } = request.params;\n assertIsInternalScopeString(scope);\n\n let caveat: Caip25Caveat | undefined;\n try {\n caveat = hooks.getCaveatForOrigin(\n Caip25EndowmentPermissionName,\n Caip25CaveatType,\n ) as Caip25Caveat | undefined;\n } catch {\n // noop\n }\n if (!caveat) {\n return end(providerErrors.unauthorized());\n }\n\n const scopeObject = getSessionScopes(caveat.value, {\n getNonEvmSupportedMethods: hooks.getNonEvmSupportedMethods,\n sortAccountIdsByLastSelected: hooks.sortAccountIdsByLastSelected,\n })[scope];\n\n if (!scopeObject?.methods?.includes(wrappedRequest.method)) {\n return end(providerErrors.unauthorized());\n }\n\n const { namespace, reference } = parseScopeString(scope);\n\n const isEvmRequest =\n (namespace === KnownCaipNamespace.Wallet &&\n (!reference || reference === KnownCaipNamespace.Eip155)) ||\n namespace === KnownCaipNamespace.Eip155;\n\n const unwrappedRequest = {\n ...request,\n scope,\n method: wrappedRequest.method,\n params: wrappedRequest.params,\n };\n\n if (isEvmRequest) {\n let networkClientId;\n if (namespace === KnownCaipNamespace.Wallet) {\n networkClientId = hooks.getSelectedNetworkClientId();\n } else if (namespace === KnownCaipNamespace.Eip155) {\n if (reference) {\n networkClientId = hooks.findNetworkClientIdByChainId(\n numberToHex(parseInt(reference, 10)),\n );\n }\n }\n\n if (!networkClientId) {\n console.error(\n 'failed to resolve network client for wallet_invokeMethod',\n request,\n );\n return end(rpcErrors.internal());\n }\n\n Object.assign(request, {\n ...unwrappedRequest,\n networkClientId,\n });\n return next();\n }\n\n try {\n response.result = await hooks.handleNonEvmRequestForOrigin({\n connectedAddresses: scopeObject.accounts,\n // Type assertion: We know that scope is not \"wallet\" by now because it\n // is already being handled above.\n scope: scope as CaipChainId,\n request: unwrappedRequest,\n });\n } catch (err) {\n return end(err as Error);\n }\n return end();\n}\n\nexport type WalletInvokeMethodHandler = MethodHandler<\n WalletInvokeMethodHooks,\n never,\n WalletInvokeMethodParams,\n Json,\n { origin: string }\n>;\n\nexport const walletInvokeMethodHandler = {\n implementation: handleWalletInvokeMethod,\n hookNames: {\n getCaveatForOrigin: true,\n findNetworkClientIdByChainId: true,\n getSelectedNetworkClientId: true,\n getNonEvmSupportedMethods: true,\n sortAccountIdsByLastSelected: true,\n handleNonEvmRequestForOrigin: true,\n },\n} satisfies WalletInvokeMethodHandler;\n"]}