@metamask/snaps-execution-environments 3.4.2 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -1
- package/dist/browserify/iframe/bundle.js +5 -5
- package/dist/browserify/iframe/index.html +1134 -389
- package/dist/browserify/node-process/bundle.js +1135 -392
- package/dist/browserify/node-thread/bundle.js +1135 -392
- package/dist/browserify/offscreen/bundle.js +5 -5
- package/dist/browserify/offscreen/index.html +1134 -389
- package/dist/browserify/worker-executor/bundle.js +1136 -393
- package/dist/browserify/worker-pool/bundle.js +5 -5
- package/dist/browserify/worker-pool/index.html +1134 -389
- package/dist/cjs/common/commands.js +9 -0
- package/dist/cjs/common/commands.js.map +1 -1
- package/dist/cjs/common/validation.js +13 -0
- package/dist/cjs/common/validation.js.map +1 -1
- package/dist/cjs/offscreen/index.js +2 -2
- package/dist/cjs/offscreen/index.js.map +1 -1
- package/dist/cjs/{offscreen/OffscreenSnapExecutor.js → proxy/ProxySnapExecutor.js} +25 -15
- package/dist/cjs/proxy/ProxySnapExecutor.js.map +1 -0
- package/dist/esm/common/commands.js +10 -1
- package/dist/esm/common/commands.js.map +1 -1
- package/dist/esm/common/validation.js +14 -0
- package/dist/esm/common/validation.js.map +1 -1
- package/dist/esm/offscreen/index.js +2 -2
- package/dist/esm/offscreen/index.js.map +1 -1
- package/dist/esm/{offscreen/OffscreenSnapExecutor.js → proxy/ProxySnapExecutor.js} +24 -19
- package/dist/esm/proxy/ProxySnapExecutor.js.map +1 -0
- package/dist/types/common/validation.d.ts +17 -0
- package/dist/types/{offscreen/OffscreenSnapExecutor.d.ts → proxy/ProxySnapExecutor.d.ts} +9 -9
- package/package.json +12 -12
- package/dist/cjs/offscreen/OffscreenSnapExecutor.js.map +0 -1
- package/dist/esm/offscreen/OffscreenSnapExecutor.js.map +0 -1
|
@@ -32,6 +32,15 @@ function getHandlerArguments(origin, handler, request) {
|
|
|
32
32
|
transactionOrigin
|
|
33
33
|
};
|
|
34
34
|
}
|
|
35
|
+
case _snapsutils.HandlerType.OnSignature:
|
|
36
|
+
{
|
|
37
|
+
(0, _validation.assertIsOnSignatureRequestArguments)(request.params);
|
|
38
|
+
const { signature, signatureOrigin } = request.params;
|
|
39
|
+
return {
|
|
40
|
+
signature,
|
|
41
|
+
signatureOrigin
|
|
42
|
+
};
|
|
43
|
+
}
|
|
35
44
|
case _snapsutils.HandlerType.OnNameLookup:
|
|
36
45
|
{
|
|
37
46
|
(0, _validation.assertIsOnNameLookupRequestArguments)(request.params);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnSignatureRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnSignature: {\n assertIsOnSignatureRequestArguments(request.params);\n\n const { signature, signatureOrigin } = request.params;\n return { signature, signatureOrigin };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnSignature","assertIsOnSignatureRequestArguments","signature","signatureOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAiCgBA,mBAAmB;eAAnBA;;IAsEAC,+BAA+B;eAA/BA;;;4BAvGY;uBACK;4BAe1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,WAAW;YAAE;gBAC5BC,IAAAA,+CAAmC,EAACT,QAAQI,MAAM;gBAElD,MAAM,EAAEM,SAAS,EAAEC,eAAe,EAAE,GAAGX,QAAQI,MAAM;gBACrD,OAAO;oBAAEM;oBAAWC;gBAAgB;YACtC;QACA,KAAKV,uBAAW,CAACW,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACb,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEQ,MAAM,EAAEC,OAAO,EAAE,GAChCf,QAAQI,MAAM;gBAEhB,OAAOU,SACH;oBACER;oBACAQ;gBACF,IACA;oBACER;oBACAS;gBACF;YACN;QACA,KAAKd,uBAAW,CAACe,YAAY;QAC7B,KAAKf,uBAAW,CAACgB,gBAAgB;YAC/B,OAAO;gBAAEnB;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACiB,SAAS;QAC1B,KAAKjB,uBAAW,CAACkB,SAAS;QAC1B,KAAKlB,uBAAW,CAACmB,QAAQ;YACvB,OAAO;gBAAEpB;YAAQ;QAEnB,KAAKC,uBAAW,CAACoB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOC,IAAAA,uBAAgB,EAACvB;IAC5B;AACF;AAaO,SAASF,gCACd0B,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQpC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMwB,WACLW,QACApC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
|
|
@@ -39,6 +39,12 @@ _export(exports, {
|
|
|
39
39
|
assertIsOnTransactionRequestArguments: function() {
|
|
40
40
|
return assertIsOnTransactionRequestArguments;
|
|
41
41
|
},
|
|
42
|
+
OnSignatureRequestArgumentsStruct: function() {
|
|
43
|
+
return OnSignatureRequestArgumentsStruct;
|
|
44
|
+
},
|
|
45
|
+
assertIsOnSignatureRequestArguments: function() {
|
|
46
|
+
return assertIsOnSignatureRequestArguments;
|
|
47
|
+
},
|
|
42
48
|
OnNameLookupRequestArgumentsStruct: function() {
|
|
43
49
|
return OnNameLookupRequestArgumentsStruct;
|
|
44
50
|
},
|
|
@@ -94,6 +100,13 @@ const OnTransactionRequestArgumentsStruct = (0, _superstruct.object)({
|
|
|
94
100
|
function assertIsOnTransactionRequestArguments(value) {
|
|
95
101
|
(0, _utils.assertStruct)(value, OnTransactionRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
|
|
96
102
|
}
|
|
103
|
+
const OnSignatureRequestArgumentsStruct = (0, _superstruct.object)({
|
|
104
|
+
signature: (0, _superstruct.record)((0, _superstruct.string)(), _utils.JsonStruct),
|
|
105
|
+
signatureOrigin: (0, _superstruct.nullable)((0, _superstruct.string)())
|
|
106
|
+
});
|
|
107
|
+
function assertIsOnSignatureRequestArguments(value) {
|
|
108
|
+
(0, _utils.assertStruct)(value, OnSignatureRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
|
|
109
|
+
}
|
|
97
110
|
const baseNameLookupArgs = {
|
|
98
111
|
chainId: _snapsutils.ChainIdStruct
|
|
99
112
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcSuccessStruct,\n JsonRpcVersionStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: OkStruct,\n});\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","object","jsonrpc","optional","JsonRpcVersionStruct","id","JsonRpcIdStruct","method","string","params","JsonRpcParamsStruct","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","assign","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","result","SnapRpcResponse","JsonRpcSuccessStruct"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAqBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcSuccessStruct,\n JsonRpcVersionStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nexport const OnSignatureRequestArgumentsStruct = object({\n signature: record(string(), JsonStruct),\n signatureOrigin: nullable(string()),\n});\n\nexport type OnSignatureRequestArguments = Infer<\n typeof OnSignatureRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnSignatureRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnSignatureRequestArguments}\n * object.\n */\nexport function assertIsOnSignatureRequestArguments(\n value: unknown,\n): asserts value is OnSignatureRequestArguments {\n assertStruct(\n value,\n OnSignatureRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: OkStruct,\n});\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnSignatureRequestArgumentsStruct","assertIsOnSignatureRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","object","jsonrpc","optional","JsonRpcVersionStruct","id","JsonRpcIdStruct","method","string","params","JsonRpcParamsStruct","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","assign","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","signature","signatureOrigin","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","result","SnapRpcResponse","JsonRpcSuccessStruct"],"mappings":";;;;;;;;;;;IA2BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAWHC,iCAAiC;eAAjCA;;IAiBGC,mCAAmC;eAAnCA;;IAqBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;2BAvMU;4BACiB;uBASpC;6BAeA;AAEA,MAAMb,gCAAgCc,IAAAA,mBAAM,EAAC;IAClDC,SAASC,IAAAA,qBAAQ,EAACC,2BAAoB;IACtCC,IAAIF,IAAAA,qBAAQ,EAACG,sBAAe;IAC5BC,QAAQC,IAAAA,mBAAM;IACdC,QAAQN,IAAAA,qBAAQ,EAACO,0BAAmB;AACtC;AAMO,MAAMtB,kBAAkBoB,IAAAA,mBAAM;AAS9B,SAASnB,YAAYsB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAOvB;AACnB;AAQO,SAASE,kBAAkBqB,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAAC1B;AAC7C;AAEA,MAAM2B,WAAWC,IAAAA,oBAAO,EAAC;AAElB,MAAM1B,6BAA6BY,IAAAA,qBAAQ,EAChDe,IAAA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S,sBAAsBvC,IAAAA,mBAAM,EAAC;IACjC,GAAGsC,kBAAkB;IACrBE,SAASjC,IAAAA,mBAAM;AACjB;AACA,MAAMkC,uBAAuBzC,IAAAA,mBAAM,EAAC;IAClC,GAAGsC,kBAAkB;IACrBI,QAAQnC,IAAAA,mBAAM;AAChB;AAEO,MAAMT,qCAAqCmB,IAAAA,kBAAK,EAAC;IACtDsB;IACAE;CACD;AAmBM,SAAS1C,qCACdW,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAZ,oCACA,0BACAoC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMQ,mBAAmB3C,IAAAA,mBAAM,EAAC;IAC9BI,IAAIC,sBAAe;IACnBJ,SAASE,2BAAoB;IAC7ByC,QAAQ7B;AACV;AAEA,MAAM8B,kBAAkBC,2BAAoB"}
|
|
@@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
const _postmessagestream = require("@metamask/post-message-stream");
|
|
6
6
|
const _lockdownevents = require("../common/lockdown/lockdown-events");
|
|
7
7
|
const _lockdownmore = require("../common/lockdown/lockdown-more");
|
|
8
|
-
const
|
|
8
|
+
const _ProxySnapExecutor = require("../proxy/ProxySnapExecutor");
|
|
9
9
|
// Lockdown is already applied in LavaMoat
|
|
10
10
|
(0, _lockdownmore.executeLockdownMore)();
|
|
11
11
|
(0, _lockdownevents.executeLockdownEvents)();
|
|
@@ -14,6 +14,6 @@ const parentStream = new _postmessagestream.BrowserRuntimePostMessageStream({
|
|
|
14
14
|
name: 'child',
|
|
15
15
|
target: 'parent'
|
|
16
16
|
});
|
|
17
|
-
|
|
17
|
+
_ProxySnapExecutor.ProxySnapExecutor.initialize(parentStream);
|
|
18
18
|
|
|
19
19
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/offscreen/index.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\n\nimport { executeLockdownEvents } from '../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../common/lockdown/lockdown-more';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/offscreen/index.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\n\nimport { executeLockdownEvents } from '../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../common/lockdown/lockdown-more';\nimport { ProxySnapExecutor } from '../proxy/ProxySnapExecutor';\n\n// Lockdown is already applied in LavaMoat\nexecuteLockdownMore();\nexecuteLockdownEvents();\n\n// The stream from the offscreen document to the execution service.\nconst parentStream = new BrowserRuntimePostMessageStream({\n name: 'child',\n target: 'parent',\n});\n\nProxySnapExecutor.initialize(parentStream);\n"],"names":["executeLockdownMore","executeLockdownEvents","parentStream","BrowserRuntimePostMessageStream","name","target","ProxySnapExecutor","initialize"],"mappings":";;;;mCAAgD;gCAEV;8BACF;mCACF;AAElC,0CAA0C;AAC1CA,IAAAA,iCAAmB;AACnBC,IAAAA,qCAAqB;AAErB,mEAAmE;AACnE,MAAMC,eAAe,IAAIC,kDAA+B,CAAC;IACvDC,MAAM;IACNC,QAAQ;AACV;AAEAC,oCAAiB,CAACC,UAAU,CAACL"}
|
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", {
|
|
3
3
|
value: true
|
|
4
4
|
});
|
|
5
|
-
Object.defineProperty(exports, "
|
|
5
|
+
Object.defineProperty(exports, "ProxySnapExecutor", {
|
|
6
6
|
enumerable: true,
|
|
7
7
|
get: function() {
|
|
8
|
-
return
|
|
8
|
+
return ProxySnapExecutor;
|
|
9
9
|
}
|
|
10
10
|
});
|
|
11
11
|
const _postmessagestream = require("@metamask/post-message-stream");
|
|
12
|
+
const _packagejson = /*#__PURE__*/ _interop_require_default(require("@metamask/snaps-execution-environments/package.json"));
|
|
12
13
|
const _snapsutils = require("@metamask/snaps-utils");
|
|
13
14
|
const _utils = require("@metamask/utils");
|
|
14
15
|
function _check_private_redeclaration(obj, privateCollection) {
|
|
@@ -74,7 +75,13 @@ function _define_property(obj, key, value) {
|
|
|
74
75
|
}
|
|
75
76
|
return obj;
|
|
76
77
|
}
|
|
77
|
-
|
|
78
|
+
function _interop_require_default(obj) {
|
|
79
|
+
return obj && obj.__esModule ? obj : {
|
|
80
|
+
default: obj
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const IFRAME_URL = `https://execution.metamask.io/${_packagejson.default.version}/index.html`;
|
|
84
|
+
var _stream = /*#__PURE__*/ new WeakMap(), _frameUrl = /*#__PURE__*/ new WeakMap(), /**
|
|
78
85
|
* Handle an incoming message from the `OffscreenExecutionService`. This
|
|
79
86
|
* assumes that the message contains a `jobId` property, and a JSON-RPC
|
|
80
87
|
* request in the `data` property.
|
|
@@ -82,49 +89,52 @@ var _stream = /*#__PURE__*/ new WeakMap(), /**
|
|
|
82
89
|
* @param data - The message data.
|
|
83
90
|
* @param data.data - The JSON-RPC request.
|
|
84
91
|
* @param data.jobId - The job ID.
|
|
85
|
-
* @param data.extra - Extra data.
|
|
86
|
-
* @param data.extra.frameUrl - The URL to load in the iframe.
|
|
87
92
|
*/ _onData = /*#__PURE__*/ new WeakSet(), _initializeJob = /*#__PURE__*/ new WeakSet(), /**
|
|
88
93
|
* Terminate the job with the given ID. This will close the iframe and delete
|
|
89
94
|
* the job from the internal job map.
|
|
90
95
|
*
|
|
91
96
|
* @param jobId - The job ID.
|
|
92
97
|
*/ _terminateJob = /*#__PURE__*/ new WeakSet();
|
|
93
|
-
class
|
|
98
|
+
class ProxySnapExecutor {
|
|
94
99
|
/**
|
|
95
100
|
* Initialize the executor with the given stream. This is a wrapper around the
|
|
96
101
|
* constructor.
|
|
97
102
|
*
|
|
98
103
|
* @param stream - The stream to use for communication.
|
|
104
|
+
* @param frameUrl - An optional URL for the iframe to use.
|
|
99
105
|
* @returns The initialized executor.
|
|
100
|
-
*/ static initialize(stream) {
|
|
101
|
-
return new
|
|
106
|
+
*/ static initialize(stream, frameUrl = IFRAME_URL) {
|
|
107
|
+
return new ProxySnapExecutor(stream, frameUrl);
|
|
102
108
|
}
|
|
103
|
-
constructor(stream){
|
|
109
|
+
constructor(stream, frameUrl){
|
|
104
110
|
_class_private_method_init(this, _onData);
|
|
105
111
|
/**
|
|
106
112
|
* Create a new iframe and set up a stream to communicate with it.
|
|
107
113
|
*
|
|
108
114
|
* @param jobId - The job ID.
|
|
109
|
-
* @param frameUrl - The URL to load in the iframe.
|
|
110
115
|
*/ _class_private_method_init(this, _initializeJob);
|
|
111
116
|
_class_private_method_init(this, _terminateJob);
|
|
112
117
|
_class_private_field_init(this, _stream, {
|
|
113
118
|
writable: true,
|
|
114
119
|
value: void 0
|
|
115
120
|
});
|
|
121
|
+
_class_private_field_init(this, _frameUrl, {
|
|
122
|
+
writable: true,
|
|
123
|
+
value: void 0
|
|
124
|
+
});
|
|
116
125
|
_define_property(this, "jobs", {});
|
|
117
126
|
_class_private_field_set(this, _stream, stream);
|
|
118
127
|
_class_private_field_get(this, _stream).on('data', _class_private_method_get(this, _onData, onData).bind(this));
|
|
128
|
+
_class_private_field_set(this, _frameUrl, frameUrl);
|
|
119
129
|
}
|
|
120
130
|
}
|
|
121
131
|
function onData(data) {
|
|
122
|
-
const { jobId,
|
|
132
|
+
const { jobId, data: request } = data;
|
|
123
133
|
if (!this.jobs[jobId]) {
|
|
124
134
|
// This ensures that a job is initialized before it is used. To avoid
|
|
125
135
|
// code duplication, we call the `#onData` method again, which will
|
|
126
136
|
// run the rest of the logic after initialization.
|
|
127
|
-
_class_private_method_get(this, _initializeJob, initializeJob).call(this, jobId
|
|
137
|
+
_class_private_method_get(this, _initializeJob, initializeJob).call(this, jobId).then(()=>{
|
|
128
138
|
_class_private_method_get(this, _onData, onData).call(this, data);
|
|
129
139
|
}).catch((error)=>{
|
|
130
140
|
(0, _snapsutils.logError)('[Worker] Error initializing job:', error);
|
|
@@ -139,8 +149,8 @@ function onData(data) {
|
|
|
139
149
|
}
|
|
140
150
|
this.jobs[jobId].stream.write(request);
|
|
141
151
|
}
|
|
142
|
-
async function initializeJob(jobId
|
|
143
|
-
const window = await (0, _snapsutils.createWindow)(
|
|
152
|
+
async function initializeJob(jobId) {
|
|
153
|
+
const window = await (0, _snapsutils.createWindow)(_class_private_field_get(this, _frameUrl), jobId);
|
|
144
154
|
const jobStream = new _postmessagestream.WindowPostMessageStream({
|
|
145
155
|
name: 'parent',
|
|
146
156
|
target: 'child',
|
|
@@ -170,4 +180,4 @@ function terminateJob(jobId) {
|
|
|
170
180
|
delete this.jobs[jobId];
|
|
171
181
|
}
|
|
172
182
|
|
|
173
|
-
//# sourceMappingURL=
|
|
183
|
+
//# sourceMappingURL=ProxySnapExecutor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/proxy/ProxySnapExecutor.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport packageJson from '@metamask/snaps-execution-environments/package.json';\nimport { createWindow, logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\ntype ExecutorJob = {\n id: string;\n window: Window;\n stream: WindowPostMessageStream;\n};\n\nconst IFRAME_URL = `https://execution.metamask.io/${packageJson.version}/index.html`;\n\n/**\n * A \"proxy\" snap executor that uses a level of indirection to execute snaps.\n *\n * Useful for multiple execution environments.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates an iframe window for each snap execution, and sends the\n * snap execution request to the iframe window. The iframe window is responsible\n * for executing the snap.\n *\n * This executor is persisted between snap executions. The executor essentially\n * acts as a proxy between the client and the iframe execution environment.\n */\nexport class ProxySnapExecutor {\n readonly #stream: BasePostMessageStream;\n\n readonly #frameUrl: string;\n\n readonly jobs: Record<string, ExecutorJob> = {};\n\n /**\n * Initialize the executor with the given stream. This is a wrapper around the\n * constructor.\n *\n * @param stream - The stream to use for communication.\n * @param frameUrl - An optional URL for the iframe to use.\n * @returns The initialized executor.\n */\n static initialize(stream: BasePostMessageStream, frameUrl = IFRAME_URL) {\n return new ProxySnapExecutor(stream, frameUrl);\n }\n\n constructor(stream: BasePostMessageStream, frameUrl: string) {\n this.#stream = stream;\n this.#stream.on('data', this.#onData.bind(this));\n this.#frameUrl = frameUrl;\n }\n\n /**\n * Handle an incoming message from the `OffscreenExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n if (!this.jobs[jobId]) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error);\n });\n\n return;\n }\n\n // This is a method specific to the `OffscreenSnapExecutor`, as the service\n // itself does not have access to the iframes directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n this.jobs[jobId].stream.write(request);\n }\n\n /**\n * Create a new iframe and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const window = await createWindow(this.#frameUrl, jobId);\n const jobStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n\n // Write messages from the iframe to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n this.jobs[jobId] = { id: jobId, window, stream: jobStream };\n return this.jobs[jobId];\n }\n\n /**\n * Terminate the job with the given ID. This will close the iframe and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n assert(this.jobs[jobId], `Job \"${jobId}\" not found.`);\n\n const iframe = document.getElementById(jobId);\n assert(iframe, `Iframe with ID \"${jobId}\" not found.`);\n\n iframe.remove();\n this.jobs[jobId].stream.destroy();\n delete this.jobs[jobId];\n }\n}\n"],"names":["ProxySnapExecutor","IFRAME_URL","packageJson","version","initialize","stream","frameUrl","constructor","jobs","on","onData","bind","data","jobId","request","initializeJob","then","catch","error","logError","method","terminateJob","write","window","createWindow","jobStream","WindowPostMessageStream","name","target","targetWindow","targetOrigin","id","assert","iframe","document","getElementById","remove","destroy"],"mappings":";;;;+BA6BaA;;;eAAAA;;;mCA5B2B;oEAEhB;4BACe;uBAEhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQvB,MAAMC,aAAa,CAAC,8BAA8B,EAAEC,oBAAW,CAACC,OAAO,CAAC,WAAW,CAAC;IAgBzE,uCAEA,yCAsBT;;;;;;;;GAQC,GACD,uCAiCM,8CAkBN;;;;;GAKC,GACD;AA3FK,MAAMH;IAOX;;;;;;;GAOC,GACD,OAAOI,WAAWC,MAA6B,EAAEC,WAAWL,UAAU,EAAE;QACtE,OAAO,IAAID,kBAAkBK,QAAQC;IACvC;IAEAC,YAAYF,MAA6B,EAAEC,QAAgB,CAAE;QAe7D,iCAAA;QA4BA;;;;GAIC,GACD,iCAAM;QAwBN,iCAAA;QA1FA,gCAAS;;mBAAT,KAAA;;QAEA,gCAAS;;mBAAT,KAAA;;QAEA,uBAASE,QAAoC,CAAC;uCAetCH,SAASA;QACf,yBAAA,IAAI,EAAEA,SAAOI,EAAE,CAAC,QAAQ,0BAAA,IAAI,EAAEC,SAAAA,QAAOC,IAAI,CAAC,IAAI;uCACxCL,WAAWA;IACnB;AA8EF;AAnEE,SAAA,OAAQM,IAA6C;IACnD,MAAM,EAAEC,KAAK,EAAED,MAAME,OAAO,EAAE,GAAGF;IAEjC,IAAI,CAAC,IAAI,CAACJ,IAAI,CAACK,MAAM,EAA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M,CAACR,MAAM,CAACgC,OAAO;IAC/B,OAAO,IAAI,CAAC7B,IAAI,CAACK,MAAM;AACzB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { HandlerType } from '@metamask/snaps-utils';
|
|
2
2
|
import { assertExhaustive } from '@metamask/utils';
|
|
3
|
-
import { assertIsOnTransactionRequestArguments, assertIsOnNameLookupRequestArguments } from './validation';
|
|
3
|
+
import { assertIsOnTransactionRequestArguments, assertIsOnSignatureRequestArguments, assertIsOnNameLookupRequestArguments } from './validation';
|
|
4
4
|
/**
|
|
5
5
|
* Formats the arguments for the given handler.
|
|
6
6
|
*
|
|
@@ -21,6 +21,15 @@ import { assertIsOnTransactionRequestArguments, assertIsOnNameLookupRequestArgum
|
|
|
21
21
|
transactionOrigin
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
|
+
case HandlerType.OnSignature:
|
|
25
|
+
{
|
|
26
|
+
assertIsOnSignatureRequestArguments(request.params);
|
|
27
|
+
const { signature, signatureOrigin } = request.params;
|
|
28
|
+
return {
|
|
29
|
+
signature,
|
|
30
|
+
signatureOrigin
|
|
31
|
+
};
|
|
32
|
+
}
|
|
24
33
|
case HandlerType.OnNameLookup:
|
|
25
34
|
{
|
|
26
35
|
assertIsOnNameLookupRequestArguments(request.params);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnNameLookup","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":"AAAA,SAASA,WAAW,QAAQ,wBAAwB;AACpD,SAASC,gBAAgB,QAAQ,kBAAkB;AAWnD,SACEC,qCAAqC,EACrCC,oCAAoC,QAC/B,eAAe;AAStB;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,
|
|
1
|
+
{"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnSignatureRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnSignature: {\n assertIsOnSignatureRequestArguments(request.params);\n\n const { signature, signatureOrigin } = request.params;\n return { signature, signatureOrigin };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["HandlerType","assertExhaustive","assertIsOnTransactionRequestArguments","assertIsOnSignatureRequestArguments","assertIsOnNameLookupRequestArguments","getHandlerArguments","origin","handler","request","OnTransaction","params","transaction","chainId","transactionOrigin","OnSignature","signature","signatureOrigin","OnNameLookup","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","getCommandMethodImplementations","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":"AAAA,SAASA,WAAW,QAAQ,wBAAwB;AACpD,SAASC,gBAAgB,QAAQ,kBAAkB;AAWnD,SACEC,qCAAqC,EACrCC,mCAAmC,EACnCC,oCAAoC,QAC/B,eAAe;AAStB;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKP,YAAYS,aAAa;YAAE;gBAC9BP,sCAAsCM,QAAQE,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGL,QAAQE,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKb,YAAYc,WAAW;YAAE;gBAC5BX,oCAAoCK,QAAQE,MAAM;gBAElD,MAAM,EAAEK,SAAS,EAAEC,eAAe,EAAE,GAAGR,QAAQE,MAAM;gBACrD,OAAO;oBAAEK;oBAAWC;gBAAgB;YACtC;QACA,KAAKhB,YAAYiB,YAAY;YAAE;gBAC7Bb,qCAAqCI,QAAQE,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEM,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQE,MAAM;gBAEhB,OAAOQ,SACH;oBACEN;oBACAM;gBACF,IACA;oBACEN;oBACAO;gBACF;YACN;QACA,KAAKnB,YAAYoB,YAAY;QAC7B,KAAKpB,YAAYqB,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKR,YAAYsB,SAAS;QAC1B,KAAKtB,YAAYuB,SAAS;QAC1B,KAAKvB,YAAYwB,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB,KAAKR,YAAYyB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOxB,iBAAiBM;IAC5B;AACF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASmB,gCACdC,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQhC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMoB,WACLW,QACAhC,SACAF,oBAAoBC,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
|
|
@@ -63,6 +63,20 @@ export const OnTransactionRequestArgumentsStruct = object({
|
|
|
63
63
|
*/ export function assertIsOnTransactionRequestArguments(value) {
|
|
64
64
|
assertStruct(value, OnTransactionRequestArgumentsStruct, 'Invalid request params', rpcErrors.invalidParams);
|
|
65
65
|
}
|
|
66
|
+
export const OnSignatureRequestArgumentsStruct = object({
|
|
67
|
+
signature: record(string(), JsonStruct),
|
|
68
|
+
signatureOrigin: nullable(string())
|
|
69
|
+
});
|
|
70
|
+
/**
|
|
71
|
+
* Asserts that the given value is a valid {@link OnSignatureRequestArguments}
|
|
72
|
+
* object.
|
|
73
|
+
*
|
|
74
|
+
* @param value - The value to validate.
|
|
75
|
+
* @throws If the value is not a valid {@link OnSignatureRequestArguments}
|
|
76
|
+
* object.
|
|
77
|
+
*/ export function assertIsOnSignatureRequestArguments(value) {
|
|
78
|
+
assertStruct(value, OnSignatureRequestArgumentsStruct, 'Invalid request params', rpcErrors.invalidParams);
|
|
79
|
+
}
|
|
66
80
|
const baseNameLookupArgs = {
|
|
67
81
|
chainId: ChainIdStruct
|
|
68
82
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcSuccessStruct,\n JsonRpcVersionStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: OkStruct,\n});\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["rpcErrors","ChainIdStruct","HandlerType","assertStruct","JsonRpcIdStruct","JsonRpcParamsStruct","JsonRpcSuccessStruct","JsonRpcVersionStruct","JsonStruct","array","assign","enums","is","literal","nullable","object","optional","record","string","tuple","union","JsonRpcRequestWithoutIdStruct","jsonrpc","id","method","params","EndowmentStruct","isEndowment","value","isEndowmentsArray","Array","isArray","every","OkStruct","PingRequestArgumentsStruct","undefined","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","Object","values","OnTransactionRequestArgumentsStruct","transaction","chainId","transactionOrigin","assertIsOnTransactionRequestArguments","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","OkResponseStruct","result","SnapRpcResponse"],"mappings":"AAAA,SAASA,SAAS,QAA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C9B,GAAG;AAMH;;;;;;;CAOC,GACD,OAAO,SAAS2B,sCACdjB,KAAc;IAEdzB,aACEyB,OACAa,qCACA,0BACAzC,UAAU8C,aAAa;AAE3B;AAEA,MAAMC,qBAAqB;
|
|
1
|
+
{"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcSuccessStruct,\n JsonRpcVersionStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n array(EndowmentStruct),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nexport const OnSignatureRequestArgumentsStruct = object({\n signature: record(string(), JsonStruct),\n signatureOrigin: nullable(string()),\n});\n\nexport type OnSignatureRequestArguments = Infer<\n typeof OnSignatureRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnSignatureRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnSignatureRequestArguments}\n * object.\n */\nexport function assertIsOnSignatureRequestArguments(\n value: unknown,\n): asserts value is OnSignatureRequestArguments {\n assertStruct(\n value,\n OnSignatureRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = object({\n id: JsonRpcIdStruct,\n jsonrpc: JsonRpcVersionStruct,\n result: OkStruct,\n});\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["rpcErrors","ChainIdStruct","HandlerType","assertStruct","JsonRpcIdStruct","JsonRpcParamsStruct","JsonRpcSuccessStruct","JsonRpcVersionStruct","JsonStruct","array","assign","enums","is","literal","nullable","object","optional","record","string","tuple","union","JsonRpcRequestWithoutIdStruct","jsonrpc","id","method","params","EndowmentStruct","isEndowment","value","isEndowmentsArray","Array","isArray","every","OkStruct","PingRequestArgumentsStruct","undefined","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","Object","values","OnTransactionRequestArgumentsStruct","transaction","chainId","transactionOrigin","assertIsOnTransactionRequestArguments","invalidParams","OnSignatureRequestArgumentsStruct","signature","signatureOrigin","assertIsOnSignatureRequestArguments","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","OkResponseStruct","result","SnapRpcResponse"],"mappings":"AAAA,SAASA,SAAS,QAAQ,uBAAuB;AACjD,SAASC,aAAa,EAAEC,WAAW,QAAQ,wBAAwB;AAEnE,SACEC,YAAY,EACZC,eAAe,EACfC,mBAAmB,EACnBC,oBAAoB,EACpBC,oBAAoB,EACpBC,UAAU,QACL,kBAAkB;AAEzB,SACEC,KAAK,EACLC,MAAM,EACNC,KAAK,EACLC,EAAE,EACFC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,KAAK,EACLC,KAAK,QACA,cAAc;AAErB,OAAO,MAAMC,gCAAgCN,OAAO;IAClDO,SAASN,SAAST;IAClBgB,IAAIP,SAASZ;IACboB,QAAQN;IACRO,QAAQT,SAASX;AACnB,GAAG;AAMH,OAAO,MAAMqB,kBAAkBR,SAAS;AAGxC;;;;;CAKC,GACD,OAAO,SAASS,YAAYC,KAAc;IACxC,OAAOhB,GAAGgB,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,kBAAkBD,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAACL;A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AU8C,aAAa;AAE3B;AAEA,MAAMY,mBAAmB3C,OAAO;IAC9BQ,IAAInB;IACJkB,SAASf;IACToD,QAAQ1B;AACV;AAEA,MAAM2B,kBAAkBtD"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';
|
|
2
2
|
import { executeLockdownEvents } from '../common/lockdown/lockdown-events';
|
|
3
3
|
import { executeLockdownMore } from '../common/lockdown/lockdown-more';
|
|
4
|
-
import {
|
|
4
|
+
import { ProxySnapExecutor } from '../proxy/ProxySnapExecutor';
|
|
5
5
|
// Lockdown is already applied in LavaMoat
|
|
6
6
|
executeLockdownMore();
|
|
7
7
|
executeLockdownEvents();
|
|
@@ -10,6 +10,6 @@ const parentStream = new BrowserRuntimePostMessageStream({
|
|
|
10
10
|
name: 'child',
|
|
11
11
|
target: 'parent'
|
|
12
12
|
});
|
|
13
|
-
|
|
13
|
+
ProxySnapExecutor.initialize(parentStream);
|
|
14
14
|
|
|
15
15
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/offscreen/index.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\n\nimport { executeLockdownEvents } from '../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../common/lockdown/lockdown-more';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/offscreen/index.ts"],"sourcesContent":["import { BrowserRuntimePostMessageStream } from '@metamask/post-message-stream';\n\nimport { executeLockdownEvents } from '../common/lockdown/lockdown-events';\nimport { executeLockdownMore } from '../common/lockdown/lockdown-more';\nimport { ProxySnapExecutor } from '../proxy/ProxySnapExecutor';\n\n// Lockdown is already applied in LavaMoat\nexecuteLockdownMore();\nexecuteLockdownEvents();\n\n// The stream from the offscreen document to the execution service.\nconst parentStream = new BrowserRuntimePostMessageStream({\n name: 'child',\n target: 'parent',\n});\n\nProxySnapExecutor.initialize(parentStream);\n"],"names":["BrowserRuntimePostMessageStream","executeLockdownEvents","executeLockdownMore","ProxySnapExecutor","parentStream","name","target","initialize"],"mappings":"AAAA,SAASA,+BAA+B,QAAQ,gCAAgC;AAEhF,SAASC,qBAAqB,QAAQ,qCAAqC;AAC3E,SAASC,mBAAmB,QAAQ,mCAAmC;AACvE,SAASC,iBAAiB,QAAQ,6BAA6B;AAE/D,0CAA0C;AAC1CD;AACAD;AAEA,mEAAmE;AACnE,MAAMG,eAAe,IAAIJ,gCAAgC;IACvDK,MAAM;IACNC,QAAQ;AACV;AAEAH,kBAAkBI,UAAU,CAACH"}
|
|
@@ -62,9 +62,12 @@ function _define_property(obj, key, value) {
|
|
|
62
62
|
return obj;
|
|
63
63
|
}
|
|
64
64
|
import { WindowPostMessageStream } from '@metamask/post-message-stream';
|
|
65
|
+
// eslint-disable-next-line import/no-extraneous-dependencies
|
|
66
|
+
import packageJson from '@metamask/snaps-execution-environments/package.json';
|
|
65
67
|
import { createWindow, logError } from '@metamask/snaps-utils';
|
|
66
68
|
import { assert } from '@metamask/utils';
|
|
67
|
-
|
|
69
|
+
const IFRAME_URL = `https://execution.metamask.io/${packageJson.version}/index.html`;
|
|
70
|
+
var _stream = /*#__PURE__*/ new WeakMap(), _frameUrl = /*#__PURE__*/ new WeakMap(), /**
|
|
68
71
|
* Handle an incoming message from the `OffscreenExecutionService`. This
|
|
69
72
|
* assumes that the message contains a `jobId` property, and a JSON-RPC
|
|
70
73
|
* request in the `data` property.
|
|
@@ -72,8 +75,6 @@ var _stream = /*#__PURE__*/ new WeakMap(), /**
|
|
|
72
75
|
* @param data - The message data.
|
|
73
76
|
* @param data.data - The JSON-RPC request.
|
|
74
77
|
* @param data.jobId - The job ID.
|
|
75
|
-
* @param data.extra - Extra data.
|
|
76
|
-
* @param data.extra.frameUrl - The URL to load in the iframe.
|
|
77
78
|
*/ _onData = /*#__PURE__*/ new WeakSet(), _initializeJob = /*#__PURE__*/ new WeakSet(), /**
|
|
78
79
|
* Terminate the job with the given ID. This will close the iframe and delete
|
|
79
80
|
* the job from the internal job map.
|
|
@@ -81,53 +82,57 @@ var _stream = /*#__PURE__*/ new WeakMap(), /**
|
|
|
81
82
|
* @param jobId - The job ID.
|
|
82
83
|
*/ _terminateJob = /*#__PURE__*/ new WeakSet();
|
|
83
84
|
/**
|
|
84
|
-
* A snap executor
|
|
85
|
+
* A "proxy" snap executor that uses a level of indirection to execute snaps.
|
|
86
|
+
*
|
|
87
|
+
* Useful for multiple execution environments.
|
|
85
88
|
*
|
|
86
89
|
* This is not a traditional snap executor, as it does not execute snaps itself.
|
|
87
90
|
* Instead, it creates an iframe window for each snap execution, and sends the
|
|
88
91
|
* snap execution request to the iframe window. The iframe window is responsible
|
|
89
92
|
* for executing the snap.
|
|
90
93
|
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
|
|
94
|
-
*
|
|
95
|
-
* @see https://developer.chrome.com/docs/extensions/reference/offscreen/
|
|
96
|
-
*/ export class OffscreenSnapExecutor {
|
|
94
|
+
* This executor is persisted between snap executions. The executor essentially
|
|
95
|
+
* acts as a proxy between the client and the iframe execution environment.
|
|
96
|
+
*/ export class ProxySnapExecutor {
|
|
97
97
|
/**
|
|
98
98
|
* Initialize the executor with the given stream. This is a wrapper around the
|
|
99
99
|
* constructor.
|
|
100
100
|
*
|
|
101
101
|
* @param stream - The stream to use for communication.
|
|
102
|
+
* @param frameUrl - An optional URL for the iframe to use.
|
|
102
103
|
* @returns The initialized executor.
|
|
103
|
-
*/ static initialize(stream) {
|
|
104
|
-
return new
|
|
104
|
+
*/ static initialize(stream, frameUrl = IFRAME_URL) {
|
|
105
|
+
return new ProxySnapExecutor(stream, frameUrl);
|
|
105
106
|
}
|
|
106
|
-
constructor(stream){
|
|
107
|
+
constructor(stream, frameUrl){
|
|
107
108
|
_class_private_method_init(this, _onData);
|
|
108
109
|
/**
|
|
109
110
|
* Create a new iframe and set up a stream to communicate with it.
|
|
110
111
|
*
|
|
111
112
|
* @param jobId - The job ID.
|
|
112
|
-
* @param frameUrl - The URL to load in the iframe.
|
|
113
113
|
*/ _class_private_method_init(this, _initializeJob);
|
|
114
114
|
_class_private_method_init(this, _terminateJob);
|
|
115
115
|
_class_private_field_init(this, _stream, {
|
|
116
116
|
writable: true,
|
|
117
117
|
value: void 0
|
|
118
118
|
});
|
|
119
|
+
_class_private_field_init(this, _frameUrl, {
|
|
120
|
+
writable: true,
|
|
121
|
+
value: void 0
|
|
122
|
+
});
|
|
119
123
|
_define_property(this, "jobs", {});
|
|
120
124
|
_class_private_field_set(this, _stream, stream);
|
|
121
125
|
_class_private_field_get(this, _stream).on('data', _class_private_method_get(this, _onData, onData).bind(this));
|
|
126
|
+
_class_private_field_set(this, _frameUrl, frameUrl);
|
|
122
127
|
}
|
|
123
128
|
}
|
|
124
129
|
function onData(data) {
|
|
125
|
-
const { jobId,
|
|
130
|
+
const { jobId, data: request } = data;
|
|
126
131
|
if (!this.jobs[jobId]) {
|
|
127
132
|
// This ensures that a job is initialized before it is used. To avoid
|
|
128
133
|
// code duplication, we call the `#onData` method again, which will
|
|
129
134
|
// run the rest of the logic after initialization.
|
|
130
|
-
_class_private_method_get(this, _initializeJob, initializeJob).call(this, jobId
|
|
135
|
+
_class_private_method_get(this, _initializeJob, initializeJob).call(this, jobId).then(()=>{
|
|
131
136
|
_class_private_method_get(this, _onData, onData).call(this, data);
|
|
132
137
|
}).catch((error)=>{
|
|
133
138
|
logError('[Worker] Error initializing job:', error);
|
|
@@ -142,8 +147,8 @@ function onData(data) {
|
|
|
142
147
|
}
|
|
143
148
|
this.jobs[jobId].stream.write(request);
|
|
144
149
|
}
|
|
145
|
-
async function initializeJob(jobId
|
|
146
|
-
const window = await createWindow(
|
|
150
|
+
async function initializeJob(jobId) {
|
|
151
|
+
const window = await createWindow(_class_private_field_get(this, _frameUrl), jobId);
|
|
147
152
|
const jobStream = new WindowPostMessageStream({
|
|
148
153
|
name: 'parent',
|
|
149
154
|
target: 'child',
|
|
@@ -173,4 +178,4 @@ function terminateJob(jobId) {
|
|
|
173
178
|
delete this.jobs[jobId];
|
|
174
179
|
}
|
|
175
180
|
|
|
176
|
-
//# sourceMappingURL=
|
|
181
|
+
//# sourceMappingURL=ProxySnapExecutor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/proxy/ProxySnapExecutor.ts"],"sourcesContent":["import type { BasePostMessageStream } from '@metamask/post-message-stream';\nimport { WindowPostMessageStream } from '@metamask/post-message-stream';\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport packageJson from '@metamask/snaps-execution-environments/package.json';\nimport { createWindow, logError } from '@metamask/snaps-utils';\nimport type { JsonRpcRequest } from '@metamask/utils';\nimport { assert } from '@metamask/utils';\n\ntype ExecutorJob = {\n id: string;\n window: Window;\n stream: WindowPostMessageStream;\n};\n\nconst IFRAME_URL = `https://execution.metamask.io/${packageJson.version}/index.html`;\n\n/**\n * A \"proxy\" snap executor that uses a level of indirection to execute snaps.\n *\n * Useful for multiple execution environments.\n *\n * This is not a traditional snap executor, as it does not execute snaps itself.\n * Instead, it creates an iframe window for each snap execution, and sends the\n * snap execution request to the iframe window. The iframe window is responsible\n * for executing the snap.\n *\n * This executor is persisted between snap executions. The executor essentially\n * acts as a proxy between the client and the iframe execution environment.\n */\nexport class ProxySnapExecutor {\n readonly #stream: BasePostMessageStream;\n\n readonly #frameUrl: string;\n\n readonly jobs: Record<string, ExecutorJob> = {};\n\n /**\n * Initialize the executor with the given stream. This is a wrapper around the\n * constructor.\n *\n * @param stream - The stream to use for communication.\n * @param frameUrl - An optional URL for the iframe to use.\n * @returns The initialized executor.\n */\n static initialize(stream: BasePostMessageStream, frameUrl = IFRAME_URL) {\n return new ProxySnapExecutor(stream, frameUrl);\n }\n\n constructor(stream: BasePostMessageStream, frameUrl: string) {\n this.#stream = stream;\n this.#stream.on('data', this.#onData.bind(this));\n this.#frameUrl = frameUrl;\n }\n\n /**\n * Handle an incoming message from the `OffscreenExecutionService`. This\n * assumes that the message contains a `jobId` property, and a JSON-RPC\n * request in the `data` property.\n *\n * @param data - The message data.\n * @param data.data - The JSON-RPC request.\n * @param data.jobId - The job ID.\n */\n #onData(data: { data: JsonRpcRequest; jobId: string }) {\n const { jobId, data: request } = data;\n\n if (!this.jobs[jobId]) {\n // This ensures that a job is initialized before it is used. To avoid\n // code duplication, we call the `#onData` method again, which will\n // run the rest of the logic after initialization.\n this.#initializeJob(jobId)\n .then(() => {\n this.#onData(data);\n })\n .catch((error) => {\n logError('[Worker] Error initializing job:', error);\n });\n\n return;\n }\n\n // This is a method specific to the `OffscreenSnapExecutor`, as the service\n // itself does not have access to the iframes directly.\n if (request.method === 'terminateJob') {\n this.#terminateJob(jobId);\n return;\n }\n\n this.jobs[jobId].stream.write(request);\n }\n\n /**\n * Create a new iframe and set up a stream to communicate with it.\n *\n * @param jobId - The job ID.\n */\n async #initializeJob(jobId: string): Promise<ExecutorJob> {\n const window = await createWindow(this.#frameUrl, jobId);\n const jobStream = new WindowPostMessageStream({\n name: 'parent',\n target: 'child',\n targetWindow: window,\n targetOrigin: '*',\n });\n\n // Write messages from the iframe to the parent, wrapped with the job ID.\n jobStream.on('data', (data) => {\n this.#stream.write({ data, jobId });\n });\n\n this.jobs[jobId] = { id: jobId, window, stream: jobStream };\n return this.jobs[jobId];\n }\n\n /**\n * Terminate the job with the given ID. This will close the iframe and delete\n * the job from the internal job map.\n *\n * @param jobId - The job ID.\n */\n #terminateJob(jobId: string) {\n assert(this.jobs[jobId], `Job \"${jobId}\" not found.`);\n\n const iframe = document.getElementById(jobId);\n assert(iframe, `Iframe with ID \"${jobId}\" not found.`);\n\n iframe.remove();\n this.jobs[jobId].stream.destroy();\n delete this.jobs[jobId];\n }\n}\n"],"names":["WindowPostMessageStream","packageJson","createWindow","logError","assert","IFRAME_URL","version","ProxySnapExecutor","initialize","stream","frameUrl","constructor","jobs","on","onData","bind","data","jobId","request","initializeJob","then","catch","error","method","terminateJob","write","window","jobStream","name","target","target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,EAASE;QACf,GACCK,KAAK,CAAC,CAACC;YACNnB,SAAS,oCAAoCmB;QAC/C;QAEF;IACF;IAEA,2EAA2E;IAC3E,uDAAuD;IACvD,IAAIJ,QAAQK,MAAM,KAAK,gBAAgB;QACrC,0BAAA,IAAI,EAAEC,eAAAA,mBAAN,IAAI,EAAeP;QACnB;IACF;IAEA,IAAI,CAACL,IAAI,CAACK,MAAM,CAACR,MAAM,CAACgB,KAAK,CAACP;AAChC;AAOA,eAAA,cAAqBD,KAAa;IAChC,MAAMS,SAAS,MAAMxB,sCAAa,IAAI,EAAEQ,YAAUO;IAClD,MAAMU,YAAY,IAAI3B,wBAAwB;QAC5C4B,MAAM;QACNC,QAAQ;QACRC,cAAcJ;QACdK,cAAc;IAChB;IAEA,yEAAyE;IACzEJ,UAAUd,EAAE,CAAC,QAAQ,CAACG;QACpB,yBAAA,IAAI,EAAEP,SAAOgB,KAAK,CAAC;YAAET;YAAMC;QAAM;IACnC;IAEA,IAAI,CAACL,IAAI,CAACK,MAAM,GAAG;QAAEe,IAAIf;QAAOS;QAAQjB,QAAQkB;IAAU;IAC1D,OAAO,IAAI,CAACf,IAAI,CAACK,MAAM;AACzB;AAQA,SAAA,aAAcA,KAAa;IACzBb,OAAO,IAAI,CAACQ,IAAI,CAACK,MAAM,EAAE,CAAC,KAAK,EAAEA,MAAM,YAAY,CAAC;IAEpD,MAAMgB,SAASC,SAASC,cAAc,CAAClB;IACvCb,OAAO6B,QAAQ,CAAC,gBAAgB,EAAEhB,MAAM,YAAY,CAAC;IAErDgB,OAAOG,MAAM;IACb,IAAI,CAACxB,IAAI,CAACK,MAAM,CAACR,MAAM,CAAC4B,OAAO;IAC/B,OAAO,IAAI,CAACzB,IAAI,CAACK,MAAM;AACzB"}
|
|
@@ -62,6 +62,23 @@ export declare type OnTransactionRequestArguments = Infer<typeof OnTransactionRe
|
|
|
62
62
|
* object.
|
|
63
63
|
*/
|
|
64
64
|
export declare function assertIsOnTransactionRequestArguments(value: unknown): asserts value is OnTransactionRequestArguments;
|
|
65
|
+
export declare const OnSignatureRequestArgumentsStruct: import("superstruct").Struct<{
|
|
66
|
+
signature: Record<string, Json>;
|
|
67
|
+
signatureOrigin: string | null;
|
|
68
|
+
}, {
|
|
69
|
+
signature: import("superstruct").Struct<Record<string, Json>, null>;
|
|
70
|
+
signatureOrigin: import("superstruct").Struct<string | null, null>;
|
|
71
|
+
}>;
|
|
72
|
+
export declare type OnSignatureRequestArguments = Infer<typeof OnSignatureRequestArgumentsStruct>;
|
|
73
|
+
/**
|
|
74
|
+
* Asserts that the given value is a valid {@link OnSignatureRequestArguments}
|
|
75
|
+
* object.
|
|
76
|
+
*
|
|
77
|
+
* @param value - The value to validate.
|
|
78
|
+
* @throws If the value is not a valid {@link OnSignatureRequestArguments}
|
|
79
|
+
* object.
|
|
80
|
+
*/
|
|
81
|
+
export declare function assertIsOnSignatureRequestArguments(value: unknown): asserts value is OnSignatureRequestArguments;
|
|
65
82
|
declare const baseNameLookupArgs: {
|
|
66
83
|
chainId: import("superstruct").Struct<`${string}:${string}`, null>;
|
|
67
84
|
};
|