@metamask/snaps-jest 0.35.1-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +587 -0
- package/dist/cjs/environment.js +205 -0
- package/dist/cjs/environment.js.map +1 -0
- package/dist/cjs/helpers.js +67 -0
- package/dist/cjs/helpers.js.map +1 -0
- package/dist/cjs/index.js +42 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/internals/environment.js +19 -0
- package/dist/cjs/internals/environment.js.map +1 -0
- package/dist/cjs/internals/index.js +28 -0
- package/dist/cjs/internals/index.js.map +1 -0
- package/dist/cjs/internals/interface.js +103 -0
- package/dist/cjs/internals/interface.js.map +1 -0
- package/dist/cjs/internals/logger.js +14 -0
- package/dist/cjs/internals/logger.js.map +1 -0
- package/dist/cjs/internals/network.js +146 -0
- package/dist/cjs/internals/network.js.map +1 -0
- package/dist/cjs/internals/request.js +121 -0
- package/dist/cjs/internals/request.js.map +1 -0
- package/dist/cjs/internals/server.js +75 -0
- package/dist/cjs/internals/server.js.map +1 -0
- package/dist/cjs/internals/structs.js +124 -0
- package/dist/cjs/internals/structs.js.map +1 -0
- package/dist/cjs/internals/types.js +6 -0
- package/dist/cjs/internals/types.js.map +1 -0
- package/dist/cjs/internals/wait-for.js +63 -0
- package/dist/cjs/internals/wait-for.js.map +1 -0
- package/dist/cjs/matchers.js +117 -0
- package/dist/cjs/matchers.js.map +1 -0
- package/dist/cjs/options.js +29 -0
- package/dist/cjs/options.js.map +1 -0
- package/dist/cjs/setup.js +10 -0
- package/dist/cjs/setup.js.map +1 -0
- package/dist/cjs/types.js +13 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/esm/environment.js +182 -0
- package/dist/esm/environment.js.map +1 -0
- package/dist/esm/helpers.js +82 -0
- package/dist/esm/helpers.js.map +1 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/internals/environment.js +14 -0
- package/dist/esm/internals/environment.js.map +1 -0
- package/dist/esm/internals/index.js +12 -0
- package/dist/esm/internals/index.js.map +1 -0
- package/dist/esm/internals/interface.js +100 -0
- package/dist/esm/internals/interface.js.map +1 -0
- package/dist/esm/internals/logger.js +4 -0
- package/dist/esm/internals/logger.js.map +1 -0
- package/dist/esm/internals/network.js +141 -0
- package/dist/esm/internals/network.js.map +1 -0
- package/dist/esm/internals/request.js +120 -0
- package/dist/esm/internals/request.js.map +1 -0
- package/dist/esm/internals/server.js +68 -0
- package/dist/esm/internals/server.js.map +1 -0
- package/dist/esm/internals/structs.js +100 -0
- package/dist/esm/internals/structs.js.map +1 -0
- package/dist/esm/internals/types.js +3 -0
- package/dist/esm/internals/types.js.map +1 -0
- package/dist/esm/internals/wait-for.js +63 -0
- package/dist/esm/internals/wait-for.js.map +1 -0
- package/dist/esm/matchers.js +108 -0
- package/dist/esm/matchers.js.map +1 -0
- package/dist/esm/options.js +26 -0
- package/dist/esm/options.js.map +1 -0
- package/dist/esm/setup.js +6 -0
- package/dist/esm/setup.js.map +1 -0
- package/dist/esm/types.js +3 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/types/environment.d.ts +53 -0
- package/dist/types/helpers.d.ts +28 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/internals/environment.d.ts +7 -0
- package/dist/types/internals/index.d.ts +9 -0
- package/dist/types/internals/interface.d.ts +25 -0
- package/dist/types/internals/logger.d.ts +2 -0
- package/dist/types/internals/network.d.ts +87 -0
- package/dist/types/internals/request.d.ts +58 -0
- package/dist/types/internals/server.d.ts +14 -0
- package/dist/types/internals/structs.d.ts +164 -0
- package/dist/types/internals/types.d.ts +19 -0
- package/dist/types/internals/wait-for.d.ts +38 -0
- package/dist/types/matchers.d.ts +29 -0
- package/dist/types/options.d.ts +92 -0
- package/dist/types/setup.d.ts +1 -0
- package/dist/types/types.d.ts +241 -0
- package/jest-preset.js +18 -0
- package/package.json +120 -0
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { DialogType } from '@metamask/rpc-methods';
|
|
2
|
+
import { assert } from '@metamask/utils';
|
|
3
|
+
import { create } from 'superstruct';
|
|
4
|
+
import { SnapOptionsStruct } from './structs';
|
|
5
|
+
import { waitFor } from './wait-for';
|
|
6
|
+
/**
|
|
7
|
+
* Get the current snap user interface (i.e., dialog). This will throw an error
|
|
8
|
+
* if the snap does not show a user interface within the timeout.
|
|
9
|
+
*
|
|
10
|
+
* @param page - The page to get the interface from.
|
|
11
|
+
* @param options - The options to use.
|
|
12
|
+
* @param options.timeout - The timeout in milliseconds to use. Defaults to
|
|
13
|
+
* `1000`.
|
|
14
|
+
* @returns The user interface object.
|
|
15
|
+
*/ export async function getInterface(page, options = {}) {
|
|
16
|
+
const { timeout } = create(options, SnapOptionsStruct);
|
|
17
|
+
const { type, node: content } = await waitFor(async ()=>{
|
|
18
|
+
const ui = await page.evaluate(()=>{
|
|
19
|
+
const state = window.__SIMULATOR_API__.getState();
|
|
20
|
+
return state.simulation.ui;
|
|
21
|
+
});
|
|
22
|
+
assert(ui);
|
|
23
|
+
return ui;
|
|
24
|
+
}, {
|
|
25
|
+
timeout,
|
|
26
|
+
message: 'Timed out waiting for snap interface to be shown.'
|
|
27
|
+
});
|
|
28
|
+
switch(type){
|
|
29
|
+
case DialogType.Alert:
|
|
30
|
+
return {
|
|
31
|
+
type: 'alert',
|
|
32
|
+
content,
|
|
33
|
+
ok: async ()=>{
|
|
34
|
+
await page.evaluate(()=>{
|
|
35
|
+
window.__SIMULATOR_API__.dispatch({
|
|
36
|
+
type: 'simulation/resolveUserInterface',
|
|
37
|
+
payload: null
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
case DialogType.Confirmation:
|
|
43
|
+
return {
|
|
44
|
+
type: 'confirmation',
|
|
45
|
+
content,
|
|
46
|
+
ok: async ()=>{
|
|
47
|
+
await page.evaluate(()=>{
|
|
48
|
+
window.__SIMULATOR_API__.dispatch({
|
|
49
|
+
type: 'simulation/resolveUserInterface',
|
|
50
|
+
payload: true
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
cancel: async ()=>{
|
|
55
|
+
await page.evaluate(()=>{
|
|
56
|
+
window.__SIMULATOR_API__.dispatch({
|
|
57
|
+
type: 'simulation/resolveUserInterface',
|
|
58
|
+
payload: false
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
case DialogType.Prompt:
|
|
64
|
+
return {
|
|
65
|
+
type: 'prompt',
|
|
66
|
+
content,
|
|
67
|
+
ok: async (value)=>{
|
|
68
|
+
await page.evaluate((payload)=>{
|
|
69
|
+
window.__SIMULATOR_API__.dispatch({
|
|
70
|
+
type: 'simulation/resolveUserInterface',
|
|
71
|
+
payload
|
|
72
|
+
});
|
|
73
|
+
}, value);
|
|
74
|
+
},
|
|
75
|
+
cancel: async ()=>{
|
|
76
|
+
await page.evaluate(()=>{
|
|
77
|
+
window.__SIMULATOR_API__.dispatch({
|
|
78
|
+
type: 'simulation/resolveUserInterface',
|
|
79
|
+
payload: null
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
default:
|
|
85
|
+
throw new Error(`Unknown or unsupported dialog type: ${String(type)}.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Get the text of the notifications.
|
|
90
|
+
*
|
|
91
|
+
* @param page - The page to get the notifications from.
|
|
92
|
+
* @param requestId - The ID of the request to get the notifications for.
|
|
93
|
+
* @returns The text of the notifications, in order of appearance.
|
|
94
|
+
*/ export async function getNotifications(page, requestId) {
|
|
95
|
+
return await page.evaluate((id)=>{
|
|
96
|
+
return window.__SIMULATOR_API__.getNotifications(id);
|
|
97
|
+
}, requestId);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
//# sourceMappingURL=interface.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/interface.ts"],"sourcesContent":["import { DialogType } from '@metamask/rpc-methods';\nimport { assert } from '@metamask/utils';\nimport { Page } from 'puppeteer';\nimport { create } from 'superstruct';\n\nimport { SnapInterface, SnapOptions } from '../types';\nimport { SnapOptionsStruct } from './structs';\nimport { waitFor } from './wait-for';\n\n/**\n * Get the current snap user interface (i.e., dialog). This will throw an error\n * if the snap does not show a user interface within the timeout.\n *\n * @param page - The page to get the interface from.\n * @param options - The options to use.\n * @param options.timeout - The timeout in milliseconds to use. Defaults to\n * `1000`.\n * @returns The user interface object.\n */\nexport async function getInterface(\n page: Page,\n options: SnapOptions = {},\n): Promise<SnapInterface> {\n const { timeout } = create(options, SnapOptionsStruct);\n\n const { type, node: content } = await waitFor(\n async () => {\n const ui = await page.evaluate(() => {\n const state = window.__SIMULATOR_API__.getState();\n return state.simulation.ui;\n });\n\n assert(ui);\n return ui;\n },\n {\n timeout,\n message: 'Timed out waiting for snap interface to be shown.',\n },\n );\n\n switch (type) {\n case DialogType.Alert:\n return {\n type: 'alert',\n content,\n\n ok: async () => {\n await page.evaluate(() => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/resolveUserInterface',\n payload: null,\n });\n });\n },\n };\n\n case DialogType.Confirmation:\n return {\n type: 'confirmation',\n content,\n\n ok: async () => {\n await page.evaluate(() => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/resolveUserInterface',\n payload: true,\n });\n });\n },\n\n cancel: async () => {\n await page.evaluate(() => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/resolveUserInterface',\n payload: false,\n });\n });\n },\n };\n\n case DialogType.Prompt:\n return {\n type: 'prompt',\n content,\n\n ok: async (value) => {\n await page.evaluate((payload) => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/resolveUserInterface',\n payload,\n });\n }, value);\n },\n\n cancel: async () => {\n await page.evaluate(() => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/resolveUserInterface',\n payload: null,\n });\n });\n },\n };\n\n default:\n throw new Error(`Unknown or unsupported dialog type: ${String(type)}.`);\n }\n}\n\n/**\n * Get the text of the notifications.\n *\n * @param page - The page to get the notifications from.\n * @param requestId - The ID of the request to get the notifications for.\n * @returns The text of the notifications, in order of appearance.\n */\nexport async function getNotifications(page: Page, requestId: string) {\n return await page.evaluate((id) => {\n return window.__SIMULATOR_API__.getNotifications(id);\n }, requestId);\n}\n"],"names":["DialogType","assert","create","SnapOptionsStruct","waitFor","getInterface","page","options","timeout","type","node","content","ui","evaluate","state","window","__SIMULATOR_API__","getState","simulation","message","Alert","ok","dispatch","payload","Confirmation","cancel","Prompt","value","Error","String","getNotifications","requestId","id"],"mappings":"AAAA,SAASA,UAAU,QAAQ,wBAAwB;AACnD,SAASC,MAAM,QAAQ,kBAAkB;AAEzC,SAASC,MAAM,QAAQ,cAAc;AAGrC,SAASC,iBAAiB,QAAQ,YAAY;AAC9C,SAASC,OAAO,QAAQ,aAAa;AAErC;;;;;;;;;CASC,GACD,OAAO,eAAeC,aACpBC,IAAU,EACVC,UAAuB,CAAC,CAAC;IAEzB,MAAM,EAAEC,OAAO,EAAE,GAAGN,OAAOK,SAASJ;IAEpC,MAAM,EAAEM,IAAI,EAAEC,MAAMC,OAAO,EAAE,GAAG,MAAMP,QACpC;QACE,MAAMQ,KAAK,MAAMN,KAAKO,QAAQ,CAAC;YAC7B,MAAMC,QAAQC,OAAOC,iBAAiB,CAACC,QAAQ;YAC/C,OAAOH,MAAMI,UAAU,CAACN,EAAE;QAC5B;QAEAX,OAAOW;QACP,OAAOA;IACT,GACA;QACEJ;QACAW,SAAS;IACX;IAGF,OAAQV;QACN,KAAKT,WAAWoB,KAAK;YACnB,OAAO;gBACLX,MAAM;gBACNE;gBAEAU,IAAI;oBACF,MAAMf,KAAKO,QAAQ,CAAC;wBAClBE,OAAOC,iBAAiB,CAACM,QAAQ,CAAC;4BAChCb,MAAM;4BACNc,SAAS;wBACX;oBACF;gBACF;YACF;QAEF,KAAKvB,WAAWwB,YAAY;YAC1B,OAAO;gBACLf,MAAM;gBACNE;gBAEAU,IAAI;oBACF,MAAMf,KAAKO,QAAQ,CAAC;wBAClBE,OAAOC,iBAAiB,CAACM,QAAQ,CAAC;4BAChCb,MAAM;4BACNc,SAAS;wBACX;oBACF;gBACF;gBAEAE,QAAQ;oBACN,MAAMnB,KAAKO,QAAQ,CAAC;wBAClBE,OAAOC,iBAAiB,CAACM,QAAQ,CAAC;4BAChCb,MAAM;4BACNc,SAAS;wBACX;oBACF;gBACF;YACF;QAEF,KAAKvB,WAAW0B,MAAM;YACpB,OAAO;gBACLjB,MAAM;gBACNE;gBAEAU,IAAI,OAAOM;oBACT,MAAMrB,KAAKO,QAAQ,CAAC,CAACU;wBACnBR,OAAOC,iBAAiB,CAACM,QAAQ,CAAC;4BAChCb,MAAM;4BACNc;wBACF;oBACF,GAAGI;gBACL;gBAEAF,QAAQ;oBACN,MAAMnB,KAAKO,QAAQ,CAAC;wBAClBE,OAAOC,iBAAiB,CAACM,QAAQ,CAAC;4BAChCb,MAAM;4BACNc,SAAS;wBACX;oBACF;gBACF;YACF;QAEF;YACE,MAAM,IAAIK,MAAM,CAAC,oCAAoC,EAAEC,OAAOpB,MAAM,CAAC,CAAC;IAC1E;AACF;AAEA;;;;;;CAMC,GACD,OAAO,eAAeqB,iBAAiBxB,IAAU,EAAEyB,SAAiB;IAClE,OAAO,MAAMzB,KAAKO,QAAQ,CAAC,CAACmB;QAC1B,OAAOjB,OAAOC,iBAAiB,CAACc,gBAAgB,CAACE;IACnD,GAAGD;AACL"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/logger.ts"],"sourcesContent":["import { createProjectLogger } from '@metamask/utils';\n\nexport const rootLogger = createProjectLogger('snaps-jest');\n"],"names":["createProjectLogger","rootLogger"],"mappings":"AAAA,SAASA,mBAAmB,QAAQ,kBAAkB;AAEtD,OAAO,MAAMC,aAAaD,oBAAoB,cAAc"}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';
|
|
2
|
+
import { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';
|
|
3
|
+
import { assign, boolean, create, defaulted, number, object, optional, record, regexp, string, union, unknown, func } from 'superstruct';
|
|
4
|
+
import { rootLogger } from './logger';
|
|
5
|
+
/**
|
|
6
|
+
* The default headers to use for mocked responses. These headers are used to
|
|
7
|
+
* enable CORS.
|
|
8
|
+
*/ const DEFAULT_HEADERS = {
|
|
9
|
+
/* eslint-disable @typescript-eslint/naming-convention */ 'Access-Control-Allow-Origin': '*',
|
|
10
|
+
'Access-Control-Allow-Credentials': 'true',
|
|
11
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
12
|
+
'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'
|
|
13
|
+
};
|
|
14
|
+
const log = createModuleLogger(rootLogger, 'network');
|
|
15
|
+
const MockOptionsBaseStruct = object({
|
|
16
|
+
response: defaulted(object({
|
|
17
|
+
status: defaulted(number(), 200),
|
|
18
|
+
headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),
|
|
19
|
+
contentType: defaulted(string(), 'text/plain'),
|
|
20
|
+
body: defaulted(string(), '')
|
|
21
|
+
}), {})
|
|
22
|
+
});
|
|
23
|
+
const MockOptionsUrlStruct = object({
|
|
24
|
+
url: union([
|
|
25
|
+
string(),
|
|
26
|
+
regexp()
|
|
27
|
+
]),
|
|
28
|
+
partial: optional(boolean())
|
|
29
|
+
});
|
|
30
|
+
const MockOptionsConditionStruct = object({
|
|
31
|
+
condition: func()
|
|
32
|
+
});
|
|
33
|
+
export const MockOptionsStruct = union([
|
|
34
|
+
assign(MockOptionsBaseStruct, MockOptionsUrlStruct),
|
|
35
|
+
assign(MockOptionsBaseStruct, MockOptionsConditionStruct)
|
|
36
|
+
]);
|
|
37
|
+
/**
|
|
38
|
+
* Check if the given URL matches the given request, or if the condition
|
|
39
|
+
* function returns `true`.
|
|
40
|
+
*
|
|
41
|
+
* @param request - The request to check.
|
|
42
|
+
* @param options - The options for the network mocking.
|
|
43
|
+
* @returns Whether the URL matches the request.
|
|
44
|
+
*/ function matches(request, options) {
|
|
45
|
+
if ('url' in options) {
|
|
46
|
+
const { url, partial } = options;
|
|
47
|
+
if (typeof url === 'string') {
|
|
48
|
+
if (partial) {
|
|
49
|
+
return request.url().startsWith(url);
|
|
50
|
+
}
|
|
51
|
+
return url === request.url();
|
|
52
|
+
}
|
|
53
|
+
return url.test(request.url());
|
|
54
|
+
}
|
|
55
|
+
const { condition } = options;
|
|
56
|
+
return condition(request);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Enable network mocking for the given page, and all its sub-frames.
|
|
60
|
+
*
|
|
61
|
+
* @param page - The page to enable network mocking on.
|
|
62
|
+
* @param options - The options for the network mocking.
|
|
63
|
+
* @returns A {@link Mock} object, with an `unmock` function.
|
|
64
|
+
*/ export async function mock(page, options) {
|
|
65
|
+
await page.setRequestInterception(true);
|
|
66
|
+
const parsedOptions = create(options, MockOptionsStruct);
|
|
67
|
+
/**
|
|
68
|
+
* The mock handler.
|
|
69
|
+
*
|
|
70
|
+
* @param request - The request to handle.
|
|
71
|
+
*/ function handler(request) {
|
|
72
|
+
// If the request is already handled, Puppeteer will throw an error if we
|
|
73
|
+
// try to continue the request.
|
|
74
|
+
if (request.isInterceptResolutionHandled()) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (!matches(request, parsedOptions)) {
|
|
78
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
79
|
+
request.continue();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
log('Mocking request to %s', request.url());
|
|
83
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
84
|
+
request.respond(parsedOptions.response);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Unmock the page.
|
|
88
|
+
*/ async function unmock() {
|
|
89
|
+
await page.setRequestInterception(false);
|
|
90
|
+
page.off('request', handler);
|
|
91
|
+
}
|
|
92
|
+
page.on('request', handler);
|
|
93
|
+
return {
|
|
94
|
+
unmock
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
const MockJsonRpcOptionsStruct = object({
|
|
98
|
+
method: string(),
|
|
99
|
+
result: UnsafeJsonStruct
|
|
100
|
+
});
|
|
101
|
+
/**
|
|
102
|
+
* Mock an Ethereum JSON-RPC request. This intercepts all requests to the
|
|
103
|
+
* Ethereum provider, and returns the `result` instead.
|
|
104
|
+
*
|
|
105
|
+
* @param page - The page to enable network JSON-RPC mocking on.
|
|
106
|
+
* @param options - The options for the JSON-RPC mock.
|
|
107
|
+
* @param options.method - The JSON-RPC method to mock. Any other methods will be
|
|
108
|
+
* forwarded to the provider.
|
|
109
|
+
* @param options.result - The JSON response to return.
|
|
110
|
+
* @returns A {@link Mock} object, with an `unmock` function.
|
|
111
|
+
*/ export async function mockJsonRpc(page, { method, result }) {
|
|
112
|
+
return await mock(page, {
|
|
113
|
+
condition: (request)=>{
|
|
114
|
+
if (request.url() !== JSON_RPC_ENDPOINT) {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
const body = request.postData();
|
|
118
|
+
if (!body) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const json = JSON.parse(body);
|
|
123
|
+
return json.method === method;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
log(`Unable to mock "${method}" request to Ethereum provider: %s`, error.message);
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
response: {
|
|
130
|
+
status: 200,
|
|
131
|
+
contentType: 'application/json',
|
|
132
|
+
body: JSON.stringify({
|
|
133
|
+
jsonrpc: '2.0',
|
|
134
|
+
id: 1,
|
|
135
|
+
result
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
//# sourceMappingURL=network.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/network.ts"],"sourcesContent":["import { JSON_RPC_ENDPOINT } from '@metamask/snaps-simulator';\nimport { createModuleLogger, UnsafeJsonStruct } from '@metamask/utils';\nimport { Page, HTTPRequest } from 'puppeteer';\nimport {\n assign,\n boolean,\n create,\n defaulted,\n Infer,\n number,\n object,\n optional,\n record,\n regexp,\n string,\n Struct,\n union,\n unknown,\n func,\n} from 'superstruct';\n\nimport { DeepPartial } from '../types';\nimport { rootLogger } from './logger';\n\n/**\n * The default headers to use for mocked responses. These headers are used to\n * enable CORS.\n */\nconst DEFAULT_HEADERS = {\n /* eslint-disable @typescript-eslint/naming-convention */\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n 'Access-Control-Allow-Headers':\n 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers',\n /* eslint-enable @typescript-eslint/naming-convention */\n};\n\nconst log = createModuleLogger(rootLogger, 'network');\n\nexport type Unmock = () => Promise<void>;\n\nexport type Mock = {\n /**\n * A function that can be used to unmock the URL.\n */\n unmock: Unmock;\n};\n\n/**\n * A function that can return `true` if the given request should be mocked, or\n * false if not.\n *\n * @param request - The request to check.\n * @returns Whether to mock the request.\n */\nexport type ConditionFunction = (request: HTTPRequest) => boolean;\n\nconst MockOptionsBaseStruct = object({\n response: defaulted(\n object({\n status: defaulted(number(), 200),\n headers: defaulted(record(string(), unknown()), DEFAULT_HEADERS),\n contentType: defaulted(string(), 'text/plain'),\n body: defaulted(string(), ''),\n }),\n {},\n ),\n});\n\nconst MockOptionsUrlStruct = object({\n url: union([string(), regexp()]),\n partial: optional(boolean()),\n});\n\nconst MockOptionsConditionStruct = object({\n condition: func() as unknown as Struct<ConditionFunction, null>,\n});\n\nexport const MockOptionsStruct = union([\n assign(MockOptionsBaseStruct, MockOptionsUrlStruct),\n assign(MockOptionsBaseStruct, MockOptionsConditionStruct),\n]);\n\n/**\n * The options for the network mocking.\n *\n * @property url - The URL to mock. If a string is provided, the URL will be\n * matched exactly. If a RegExp is provided, the URL will be matched against it.\n * This option is incompatible with the `condition` option.\n * @property partial - If enabled, the request will be mocked if the URL starts\n * with the given URL. This option is ignored if a RegExp is provided to the\n * `url` option. This option is incompatible with the `condition` option.\n * @property condition - A function which gets the {@link HTTPRequest} as\n * parameter and returns a boolean to indicate whether the response should be\n * mocked or not. This option is incompatible with the `url` and `partial`\n * options.\n * @property response - The response to send for the request.\n * @property response.status - The status code to send for the response.\n * Defaults to `200`.\n * @property response.headers - The headers to send for the response. Defaults\n * to headers that enable CORS.\n * @property response.contentType - The content type to send for the response.\n * Defaults to `text/plain`.\n */\nexport type MockOptions = Infer<typeof MockOptionsStruct>;\n\n/**\n * Check if the given URL matches the given request, or if the condition\n * function returns `true`.\n *\n * @param request - The request to check.\n * @param options - The options for the network mocking.\n * @returns Whether the URL matches the request.\n */\nfunction matches(request: HTTPRequest, options: MockOptions) {\n if ('url' in options) {\n const { url, partial } = options;\n if (typeof url === 'string') {\n if (partial) {\n return request.url().startsWith(url);\n }\n\n return url === request.url();\n }\n\n return url.test(request.url());\n }\n\n const { condition } = options;\n return condition(request);\n}\n\n/**\n * Enable network mocking for the given page, and all its sub-frames.\n *\n * @param page - The page to enable network mocking on.\n * @param options - The options for the network mocking.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mock(\n page: Page,\n options: DeepPartial<MockOptions>,\n): Promise<Mock> {\n await page.setRequestInterception(true);\n\n const parsedOptions = create(options, MockOptionsStruct);\n\n /**\n * The mock handler.\n *\n * @param request - The request to handle.\n */\n function handler(request: HTTPRequest) {\n // If the request is already handled, Puppeteer will throw an error if we\n // try to continue the request.\n if (request.isInterceptResolutionHandled()) {\n return;\n }\n\n if (!matches(request, parsedOptions)) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.continue();\n return;\n }\n\n log('Mocking request to %s', request.url());\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n request.respond(parsedOptions.response);\n }\n\n /**\n * Unmock the page.\n */\n async function unmock() {\n await page.setRequestInterception(false);\n page.off('request', handler);\n }\n\n page.on('request', handler);\n\n return {\n unmock,\n };\n}\n\nconst MockJsonRpcOptionsStruct = object({\n method: string(),\n result: UnsafeJsonStruct,\n});\n\nexport type MockJsonRpcOptions = Infer<typeof MockJsonRpcOptionsStruct>;\n\n/**\n * Mock an Ethereum JSON-RPC request. This intercepts all requests to the\n * Ethereum provider, and returns the `result` instead.\n *\n * @param page - The page to enable network JSON-RPC mocking on.\n * @param options - The options for the JSON-RPC mock.\n * @param options.method - The JSON-RPC method to mock. Any other methods will be\n * forwarded to the provider.\n * @param options.result - The JSON response to return.\n * @returns A {@link Mock} object, with an `unmock` function.\n */\nexport async function mockJsonRpc(\n page: Page,\n { method, result }: MockJsonRpcOptions,\n) {\n return await mock(page, {\n condition: (request: HTTPRequest) => {\n if (request.url() !== JSON_RPC_ENDPOINT) {\n return false;\n }\n\n const body = request.postData();\n if (!body) {\n return false;\n }\n\n try {\n const json = JSON.parse(body);\n return json.method === method;\n } catch (error) {\n log(\n `Unable to mock \"${method}\" request to Ethereum provider: %s`,\n error.message,\n );\n return false;\n }\n },\n response: {\n status: 200,\n contentType: 'application/json',\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n result,\n }),\n },\n });\n}\n"],"names":["JSON_RPC_ENDPOINT","createModuleLogger","UnsafeJsonStruct","assign","boolean","create","defaulted","number","object","optional","record","regexp","string","union","unknown","func","rootLogger","DEFAULT_HEADERS","log","MockOptionsBaseStruct","response","status","headers","contentType","body","MockOptionsUrlStruct","url","partial","MockOptionsConditionStruct","condition","MockOptionsStruct","matches","request","options","startsWith","test","mock","page","setRequestInterception","parsedOptions","handler","isInterceptResolutionHandled","continue","respond","unmock","off","on","MockJsonRpcOptionsStruct","method","result","mockJsonRpc","postData","json","JSON","parse","error","message","stringify","jsonrpc","id"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,4BAA4B;AAC9D,SAASC,kBAAkB,EAAEC,gBAAgB,QAAQ,kBAAkB;AAEvE,SACEC,MAAM,EACNC,OAAO,EACPC,MAAM,EACNC,SAAS,EAETC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,EACNC,MAAM,EAENC,KAAK,EACLC,OAAO,EACPC,IAAI,QACC,cAAc;AAGrB,SAASC,UAAU,QAAQ,WAAW;AAEtC;;;CAGC,GACD,MAAMC,kBAAkB;IACtB,uDAAuD,GACvD,+BAA+B;IAC/B,oCAAoC;IACpC,gCAAgC;IAChC,gCACE;AAEJ;AAEA,MAAMC,MAAMjB,mBAAmBe,YAAY;AAoB3C,MAAMG,wBAAwBX,OAAO;IACnCY,UAAUd,UACRE,OAAO;QACLa,QAAQf,UAAUC,UAAU;QAC5Be,SAAShB,UAAUI,OAAOE,UAAUE,YAAYG;QAChDM,aAAajB,UAAUM,UAAU;QACjCY,MAAMlB,UAAUM,UAAU;IAC5B,IACA,CAAC;AAEL;AAEA,MAAMa,uBAAuBjB,OAAO;IAClCkB,KAAKb,MAAM;QAACD;QAAUD;KAAS;IAC/BgB,SAASlB,SAASL;AACpB;AAEA,MAAMwB,6BAA6BpB,OAAO;IACxCqB,WAAWd;AACb;AAEA,OAAO,MAAMe,oBAAoBjB,MAAM;IACrCV,OAAOgB,uBAAuBM;IAC9BtB,OAAOgB,uBAAuBS;CAC/B,EAAE;AAyBH;;;;;;;CAOC,GACD,SAASG,QAAQC,OAAoB,EAAEC,OAAoB;IACzD,IAAI,SAASA,SAAS;QACpB,MAAM,EAAEP,GAAG,EAAEC,OAAO,EAAE,GAAGM;QACzB,IAAI,OAAOP,QAAQ,UAAU;YAC3B,IAAIC,SAAS;gBACX,OAAOK,QAAQN,GAAG,GAAGQ,UAAU,CAACR;YAClC;YAEA,OAAOA,QAAQM,QAAQN,GAAG;QAC5B;QAEA,OAAOA,IAAIS,IAAI,CAACH,QAAQN,GAAG;IAC7B;IAEA,MAAM,EAAEG,SAAS,EAAE,GAAGI;IACtB,OAAOJ,UAAUG;AACnB;AAEA;;;;;;CAMC,GACD,OAAO,eAAeI,KACpBC,IAAU,EACVJ,OAAiC;IAEjC,MAAMI,KAAKC,sBAAsB,CAAC;IAElC,MAAMC,gBAAgBlC,OAAO4B,SAASH;IAEtC;;;;GAIC,GACD,SAASU,QAAQR,OAAoB;QACnC,yEAAyE;QACzE,+BAA+B;QAC/B,IAAIA,QAAQS,4BAA4B,IAAI;YAC1C;QACF;QAEA,IAAI,CAACV,QAAQC,SAASO,gBAAgB;YACpC,mEAAmE;YACnEP,QAAQU,QAAQ;YAChB;QACF;QAEAxB,IAAI,yBAAyBc,QAAQN,GAAG;QAExC,mEAAmE;QACnEM,QAAQW,OAAO,CAACJ,cAAcnB,QAAQ;IACxC;IAEA;;GAEC,GACD,eAAewB;QACb,MAAMP,KAAKC,sBAAsB,CAAC;QAClCD,KAAKQ,GAAG,CAAC,WAAWL;IACtB;IAEAH,KAAKS,EAAE,CAAC,WAAWN;IAEnB,OAAO;QACLI;IACF;AACF;AAEA,MAAMG,2BAA2BvC,OAAO;IACtCwC,QAAQpC;IACRqC,QAAQ/C;AACV;AAIA;;;;;;;;;;CAUC,GACD,OAAO,eAAegD,YACpBb,IAAU,EACV,EAAEW,MAAM,EAAEC,MAAM,EAAsB;IAEtC,OAAO,MAAMb,KAAKC,MAAM;QACtBR,WAAW,CAACG;YACV,IAAIA,QAAQN,GAAG,OAAO1B,mBAAmB;gBACvC,OAAO;YACT;YAEA,MAAMwB,OAAOQ,QAAQmB,QAAQ;YAC7B,IAAI,CAAC3B,MAAM;gBACT,OAAO;YACT;YAEA,IAAI;gBACF,MAAM4B,OAAOC,KAAKC,KAAK,CAAC9B;gBACxB,OAAO4B,KAAKJ,MAAM,KAAKA;YACzB,EAAE,OAAOO,OAAO;gBACdrC,IACE,CAAC,gBAAgB,EAAE8B,OAAO,kCAAkC,CAAC,EAC7DO,MAAMC,OAAO;gBAEf,OAAO;YACT;QACF;QACApC,UAAU;YACRC,QAAQ;YACRE,aAAa;YACbC,MAAM6B,KAAKI,SAAS,CAAC;gBACnBC,SAAS;gBACTC,IAAI;gBACJV;YACF;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { HandlerType } from '@metamask/snaps-utils';
|
|
2
|
+
import { assert, createModuleLogger, hasProperty, isPlainObject } from '@metamask/utils';
|
|
3
|
+
import { getDocument, queries } from 'pptr-testing-library';
|
|
4
|
+
import { create } from 'superstruct';
|
|
5
|
+
import { getInterface, getNotifications } from './interface';
|
|
6
|
+
import { rootLogger } from './logger';
|
|
7
|
+
import { TransactionOptionsStruct } from './structs';
|
|
8
|
+
import { waitForResponse } from './wait-for';
|
|
9
|
+
const log = createModuleLogger(rootLogger, 'request');
|
|
10
|
+
/**
|
|
11
|
+
* Send a request to the snap.
|
|
12
|
+
*
|
|
13
|
+
* @param page - The page to send the request from.
|
|
14
|
+
* @param args - The request arguments.
|
|
15
|
+
* @returns The request ID.
|
|
16
|
+
*/ async function sendRequest(page, args) {
|
|
17
|
+
const document = await getDocument(page);
|
|
18
|
+
const button = await queries.getByTestId(document, `navigation-${args.handler}`);
|
|
19
|
+
// Navigate to the request handler page.
|
|
20
|
+
await button.click();
|
|
21
|
+
return await page.evaluate((payload)=>{
|
|
22
|
+
window.__SIMULATOR_API__.dispatch({
|
|
23
|
+
type: 'simulation/sendRequest',
|
|
24
|
+
payload
|
|
25
|
+
});
|
|
26
|
+
return window.__SIMULATOR_API__.getRequestId();
|
|
27
|
+
}, args);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Send a request to the snap.
|
|
31
|
+
*
|
|
32
|
+
* @param page - The page to send the request from.
|
|
33
|
+
* @param options - The request options.
|
|
34
|
+
* @param options.origin - The origin of the request. Defaults to `metamask.io`.
|
|
35
|
+
* @param handler - The handler to use. Defaults to `onRpcRequest`.
|
|
36
|
+
* @returns The response.
|
|
37
|
+
*/ export function request(page, { origin = 'metamask.io', ...options }, handler = HandlerType.OnRpcRequest) {
|
|
38
|
+
const doRequest = async ()=>{
|
|
39
|
+
const args = {
|
|
40
|
+
origin,
|
|
41
|
+
handler,
|
|
42
|
+
request: {
|
|
43
|
+
jsonrpc: '2.0',
|
|
44
|
+
id: 1,
|
|
45
|
+
...options
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
log('Sending request %o', args);
|
|
49
|
+
const promise = waitForResponse(page, handler);
|
|
50
|
+
const id = await sendRequest(page, args);
|
|
51
|
+
const response = await promise;
|
|
52
|
+
log('Received response %o', response);
|
|
53
|
+
const notifications = await getNotifications(page, id);
|
|
54
|
+
return {
|
|
55
|
+
id,
|
|
56
|
+
response,
|
|
57
|
+
notifications
|
|
58
|
+
};
|
|
59
|
+
};
|
|
60
|
+
// This is a bit hacky, but it allows us to add the `getInterface` method
|
|
61
|
+
// to the response promise.
|
|
62
|
+
const response = doRequest();
|
|
63
|
+
response.getInterface = async (getInterfaceOptions)=>{
|
|
64
|
+
return await getInterface(page, getInterfaceOptions);
|
|
65
|
+
};
|
|
66
|
+
return response;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Send a transaction to the snap.
|
|
70
|
+
*
|
|
71
|
+
* @param page - The page to send the transaction from.
|
|
72
|
+
* @param options - The transaction options.
|
|
73
|
+
* @returns The response.
|
|
74
|
+
*/ export async function sendTransaction(page, options) {
|
|
75
|
+
const { origin: transactionOrigin, chainId, ...transaction } = create(options, TransactionOptionsStruct);
|
|
76
|
+
const args = {
|
|
77
|
+
origin: '',
|
|
78
|
+
handler: HandlerType.OnTransaction,
|
|
79
|
+
request: {
|
|
80
|
+
jsonrpc: '2.0',
|
|
81
|
+
method: '',
|
|
82
|
+
params: {
|
|
83
|
+
chainId,
|
|
84
|
+
transaction,
|
|
85
|
+
transactionOrigin
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
log('Sending transaction %o', args);
|
|
90
|
+
const promise = waitForResponse(page, HandlerType.OnTransaction);
|
|
91
|
+
const id = await sendRequest(page, args);
|
|
92
|
+
const response = await promise;
|
|
93
|
+
log('Received response %o', response);
|
|
94
|
+
if (hasProperty(response, 'error')) {
|
|
95
|
+
return {
|
|
96
|
+
id,
|
|
97
|
+
response,
|
|
98
|
+
notifications: []
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
assert(isPlainObject(response.result));
|
|
102
|
+
assert(hasProperty(response.result, 'content'));
|
|
103
|
+
return {
|
|
104
|
+
id,
|
|
105
|
+
response,
|
|
106
|
+
notifications: [],
|
|
107
|
+
content: response.result.content
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Run a cronjob.
|
|
112
|
+
*
|
|
113
|
+
* @param page - The page to run the cronjob from.
|
|
114
|
+
* @param options - The request options.
|
|
115
|
+
* @returns The response.
|
|
116
|
+
*/ export function runCronjob(page, options) {
|
|
117
|
+
return request(page, options, HandlerType.OnCronjob);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=request.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/request.ts"],"sourcesContent":["import { Component } from '@metamask/snaps-ui';\nimport { HandlerType, SnapRpcHookArgs } from '@metamask/snaps-utils';\nimport {\n assert,\n createModuleLogger,\n hasProperty,\n isPlainObject,\n} from '@metamask/utils';\nimport { getDocument, queries } from 'pptr-testing-library';\nimport { Page } from 'puppeteer';\nimport { create } from 'superstruct';\n\nimport {\n CronjobOptions,\n RequestOptions,\n SnapRequest,\n SnapResponse,\n TransactionOptions,\n} from '../types';\nimport { getInterface, getNotifications } from './interface';\nimport { rootLogger } from './logger';\nimport { TransactionOptionsStruct } from './structs';\nimport { waitForResponse } from './wait-for';\n\nconst log = createModuleLogger(rootLogger, 'request');\n\n/**\n * Send a request to the snap.\n *\n * @param page - The page to send the request from.\n * @param args - The request arguments.\n * @returns The request ID.\n */\nasync function sendRequest(page: Page, args: SnapRpcHookArgs) {\n const document = await getDocument(page);\n const button = await queries.getByTestId(\n document,\n `navigation-${args.handler}`,\n );\n\n // Navigate to the request handler page.\n await button.click();\n\n return await page.evaluate((payload) => {\n window.__SIMULATOR_API__.dispatch({\n type: 'simulation/sendRequest',\n payload,\n });\n\n return window.__SIMULATOR_API__.getRequestId();\n }, args);\n}\n\n/**\n * Send a request to the snap.\n *\n * @param page - The page to send the request from.\n * @param options - The request options.\n * @param options.origin - The origin of the request. Defaults to `metamask.io`.\n * @param handler - The handler to use. Defaults to `onRpcRequest`.\n * @returns The response.\n */\nexport function request(\n page: Page,\n { origin = 'metamask.io', ...options }: RequestOptions,\n handler:\n | HandlerType.OnRpcRequest\n | HandlerType.OnCronjob = HandlerType.OnRpcRequest,\n) {\n const doRequest = async (): Promise<SnapResponse> => {\n const args: SnapRpcHookArgs = {\n origin,\n handler,\n request: {\n jsonrpc: '2.0',\n id: 1,\n ...options,\n },\n };\n\n log('Sending request %o', args);\n\n const promise = waitForResponse(page, handler);\n const id = await sendRequest(page, args);\n const response = await promise;\n\n log('Received response %o', response);\n\n const notifications = await getNotifications(page, id);\n\n return { id, response, notifications };\n };\n\n // This is a bit hacky, but it allows us to add the `getInterface` method\n // to the response promise.\n const response = doRequest() as SnapRequest;\n\n response.getInterface = async (getInterfaceOptions) => {\n return await getInterface(page, getInterfaceOptions);\n };\n\n return response;\n}\n\n/**\n * Send a transaction to the snap.\n *\n * @param page - The page to send the transaction from.\n * @param options - The transaction options.\n * @returns The response.\n */\nexport async function sendTransaction(\n page: Page,\n options: Partial<TransactionOptions>,\n) {\n const {\n origin: transactionOrigin,\n chainId,\n ...transaction\n } = create(options, TransactionOptionsStruct);\n\n const args: SnapRpcHookArgs = {\n origin: '',\n handler: HandlerType.OnTransaction,\n request: {\n jsonrpc: '2.0',\n method: '',\n params: {\n chainId,\n transaction,\n transactionOrigin,\n },\n },\n };\n\n log('Sending transaction %o', args);\n\n const promise = waitForResponse(page, HandlerType.OnTransaction);\n const id = await sendRequest(page, args);\n const response = await promise;\n\n log('Received response %o', response);\n\n if (hasProperty(response, 'error')) {\n return { id, response, notifications: [] };\n }\n\n assert(isPlainObject(response.result));\n assert(hasProperty(response.result, 'content'));\n\n return {\n id,\n response,\n notifications: [],\n content: response.result.content as Component,\n };\n}\n\n/**\n * Run a cronjob.\n *\n * @param page - The page to run the cronjob from.\n * @param options - The request options.\n * @returns The response.\n */\nexport function runCronjob(page: Page, options: CronjobOptions) {\n return request(page, options, HandlerType.OnCronjob);\n}\n"],"names":["HandlerType","assert","createModuleLogger","hasProperty","isPlainObject","getDocument","queries","create","getInterface","getNotifications","rootLogger","TransactionOptionsStruct","waitForResponse","log","sendRequest","page","args","document","button","getByTestId","handler","click","evaluate","payload","window","__SIMULATOR_API__","dispatch","type","getRequestId","request","origin","options","OnRpcRequest","doRequest","jsonrpc","id","promise","response","notifications","getInterfaceOptions","sendTransaction","transactionOrigin","chainId","transaction","OnTransaction","method","params","result","content","runCronjob","OnCronjob"],"mappings":"AACA,SAASA,WAAW,QAAyB,wBAAwB;AACrE,SACEC,MAAM,EACNC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,QACR,kBAAkB;AACzB,SAASC,WAAW,EAAEC,OAAO,QAAQ,uBAAuB;AAE5D,SAASC,MAAM,QAAQ,cAAc;AASrC,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,cAAc;AAC7D,SAASC,UAAU,QAAQ,WAAW;AACtC,SAASC,wBAAwB,QAAQ,YAAY;AACrD,SAASC,eAAe,QAAQ,aAAa;AAE7C,MAAMC,MAAMX,mBAAmBQ,YAAY;AAE3C;;;;;;CAMC,GACD,eAAeI,YAAYC,IAAU,EAAEC,IAAqB;IAC1D,MAAMC,WAAW,MAAMZ,YAAYU;IACnC,MAAMG,SAAS,MAAMZ,QAAQa,WAAW,CACtCF,UACA,CAAC,WAAW,EAAED,KAAKI,OAAO,CAAC,CAAC;IAG9B,wCAAwC;IACxC,MAAMF,OAAOG,KAAK;IAElB,OAAO,MAAMN,KAAKO,QAAQ,CAAC,CAACC;QAC1BC,OAAOC,iBAAiB,CAACC,QAAQ,CAAC;YAChCC,MAAM;YACNJ;QACF;QAEA,OAAOC,OAAOC,iBAAiB,CAACG,YAAY;IAC9C,GAAGZ;AACL;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASa,QACdd,IAAU,EACV,EAAEe,SAAS,aAAa,EAAE,GAAGC,SAAyB,EACtDX,UAE4BpB,YAAYgC,YAAY;IAEpD,MAAMC,YAAY;QAChB,MAAMjB,OAAwB;YAC5Bc;YACAV;YACAS,SAAS;gBACPK,SAAS;gBACTC,IAAI;gBACJ,GAAGJ,OAAO;YACZ;QACF;QAEAlB,IAAI,sBAAsBG;QAE1B,MAAMoB,UAAUxB,gBAAgBG,MAAMK;QACtC,MAAMe,KAAK,MAAMrB,YAAYC,MAAMC;QACnC,MAAMqB,WAAW,MAAMD;QAEvBvB,IAAI,wBAAwBwB;QAE5B,MAAMC,gBAAgB,MAAM7B,iBAAiBM,MAAMoB;QAEnD,OAAO;YAAEA;YAAIE;YAAUC;QAAc;IACvC;IAEA,yEAAyE;IACzE,2BAA2B;IAC3B,MAAMD,WAAWJ;IAEjBI,SAAS7B,YAAY,GAAG,OAAO+B;QAC7B,OAAO,MAAM/B,aAAaO,MAAMwB;IAClC;IAEA,OAAOF;AACT;AAEA;;;;;;CAMC,GACD,OAAO,eAAeG,gBACpBzB,IAAU,EACVgB,OAAoC;IAEpC,MAAM,EACJD,QAAQW,iBAAiB,EACzBC,OAAO,EACP,GAAGC,aACJ,GAAGpC,OAAOwB,SAASpB;IAEpB,MAAMK,OAAwB;QAC5Bc,QAAQ;QACRV,SAASpB,YAAY4C,aAAa;QAClCf,SAAS;YACPK,SAAS;YACTW,QAAQ;YACRC,QAAQ;gBACNJ;gBACAC;gBACAF;YACF;QACF;IACF;IAEA5B,IAAI,0BAA0BG;IAE9B,MAAMoB,UAAUxB,gBAAgBG,MAAMf,YAAY4C,aAAa;IAC/D,MAAMT,KAAK,MAAMrB,YAAYC,MAAMC;IACnC,MAAMqB,WAAW,MAAMD;IAEvBvB,IAAI,wBAAwBwB;IAE5B,IAAIlC,YAAYkC,UAAU,UAAU;QAClC,OAAO;YAAEF;YAAIE;YAAUC,eAAe,EAAE;QAAC;IAC3C;IAEArC,OAAOG,cAAciC,SAASU,MAAM;IACpC9C,OAAOE,YAAYkC,SAASU,MAAM,EAAE;IAEpC,OAAO;QACLZ;QACAE;QACAC,eAAe,EAAE;QACjBU,SAASX,SAASU,MAAM,CAACC,OAAO;IAClC;AACF;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,WAAWlC,IAAU,EAAEgB,OAAuB;IAC5D,OAAOF,QAAQd,MAAMgB,SAAS/B,YAAYkD,SAAS;AACrD"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { assertIsSnapManifest, isDirectory, isFile } from '@metamask/snaps-utils';
|
|
2
|
+
import { createModuleLogger } from '@metamask/utils';
|
|
3
|
+
import express from 'express';
|
|
4
|
+
import { promises as fs } from 'fs';
|
|
5
|
+
import { createServer } from 'http';
|
|
6
|
+
import { resolve as pathResolve, dirname } from 'path';
|
|
7
|
+
import { rootLogger } from './logger';
|
|
8
|
+
const SNAPS_EXECUTION_ENVIRONMENTS_PATH = pathResolve(dirname(require.resolve('@metamask/snaps-execution-environments/package.json')), 'dist', 'browserify', 'iframe');
|
|
9
|
+
const SNAPS_SIMULATOR_PATH = pathResolve(dirname(require.resolve('@metamask/snaps-simulator/package.json')), 'dist', 'webpack', 'test');
|
|
10
|
+
/**
|
|
11
|
+
* Check that:
|
|
12
|
+
*
|
|
13
|
+
* - The root directory exists.
|
|
14
|
+
* - The root directory contains a `snap.manifest.json` file.
|
|
15
|
+
* - The file path in the manifest exists.
|
|
16
|
+
*
|
|
17
|
+
* @param root - The root directory.
|
|
18
|
+
* @throws If any of the checks fail.
|
|
19
|
+
*/ async function assertRoot(root) {
|
|
20
|
+
if (!root) {
|
|
21
|
+
throw new Error('You must specify a root directory.');
|
|
22
|
+
}
|
|
23
|
+
if (!await isDirectory(root, false)) {
|
|
24
|
+
throw new Error(`Root directory "${root}" is not a directory.`);
|
|
25
|
+
}
|
|
26
|
+
const manifestPath = pathResolve(root, 'snap.manifest.json');
|
|
27
|
+
const manifest = await fs.readFile(manifestPath, 'utf8').then(JSON.parse);
|
|
28
|
+
assertIsSnapManifest(manifest);
|
|
29
|
+
const filePath = pathResolve(root, manifest.source.location.npm.filePath);
|
|
30
|
+
if (!await isFile(filePath)) {
|
|
31
|
+
throw new Error(`File "${filePath}" does not exist, or is not a file. Did you forget to build your snap?`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Start an HTTP server on `localhost` with a random port. This is used to serve
|
|
36
|
+
* the static files for the environment.
|
|
37
|
+
*
|
|
38
|
+
* @param options - The options to use.
|
|
39
|
+
* @param options.port - The port to use for the server.
|
|
40
|
+
* @param options.root - The root directory to serve from the server.
|
|
41
|
+
* @returns The HTTP server.
|
|
42
|
+
*/ export async function startServer(options) {
|
|
43
|
+
await assertRoot(options.root);
|
|
44
|
+
const log = createModuleLogger(rootLogger, 'server');
|
|
45
|
+
const app = express();
|
|
46
|
+
app.use((_request, response, next)=>{
|
|
47
|
+
response.header('Access-Control-Allow-Origin', '*');
|
|
48
|
+
response.header('Access-Control-Allow-Credentials', 'true');
|
|
49
|
+
response.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
|
|
50
|
+
response.header('Access-Control-Allow-Headers', 'Content-Type');
|
|
51
|
+
next();
|
|
52
|
+
});
|
|
53
|
+
app.use('/environment', express.static(SNAPS_EXECUTION_ENVIRONMENTS_PATH));
|
|
54
|
+
app.use('/simulator', express.static(SNAPS_SIMULATOR_PATH));
|
|
55
|
+
app.use(express.static(pathResolve(process.cwd(), options.root)));
|
|
56
|
+
const server = createServer(app);
|
|
57
|
+
return await new Promise((resolve, reject)=>{
|
|
58
|
+
server.listen(options.port, ()=>{
|
|
59
|
+
resolve(server);
|
|
60
|
+
});
|
|
61
|
+
server.on('error', (error)=>{
|
|
62
|
+
log(error);
|
|
63
|
+
reject(error);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/server.ts"],"sourcesContent":["import {\n assertIsSnapManifest,\n isDirectory,\n isFile,\n SnapManifest,\n} from '@metamask/snaps-utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport express from 'express';\nimport { promises as fs } from 'fs';\nimport { createServer, Server } from 'http';\nimport { resolve as pathResolve, dirname } from 'path';\n\nimport { SnapsEnvironmentOptions } from '../options';\nimport { rootLogger } from './logger';\n\nconst SNAPS_EXECUTION_ENVIRONMENTS_PATH = pathResolve(\n dirname(\n require.resolve('@metamask/snaps-execution-environments/package.json'),\n ),\n 'dist',\n 'browserify',\n 'iframe',\n);\n\nconst SNAPS_SIMULATOR_PATH = pathResolve(\n dirname(require.resolve('@metamask/snaps-simulator/package.json')),\n 'dist',\n 'webpack',\n 'test',\n);\n\nexport type ServerOptions = Required<\n // We need a double `Required` for the type to be inferred correctly.\n Required<SnapsEnvironmentOptions>['server']\n>;\n\n/**\n * Check that:\n *\n * - The root directory exists.\n * - The root directory contains a `snap.manifest.json` file.\n * - The file path in the manifest exists.\n *\n * @param root - The root directory.\n * @throws If any of the checks fail.\n */\nasync function assertRoot(root: string) {\n if (!root) {\n throw new Error('You must specify a root directory.');\n }\n\n if (!(await isDirectory(root, false))) {\n throw new Error(`Root directory \"${root}\" is not a directory.`);\n }\n\n const manifestPath = pathResolve(root, 'snap.manifest.json');\n const manifest: SnapManifest = await fs\n .readFile(manifestPath, 'utf8')\n .then(JSON.parse);\n\n assertIsSnapManifest(manifest);\n const filePath = pathResolve(root, manifest.source.location.npm.filePath);\n\n if (!(await isFile(filePath))) {\n throw new Error(\n `File \"${filePath}\" does not exist, or is not a file. Did you forget to build your snap?`,\n );\n }\n}\n\n/**\n * Start an HTTP server on `localhost` with a random port. This is used to serve\n * the static files for the environment.\n *\n * @param options - The options to use.\n * @param options.port - The port to use for the server.\n * @param options.root - The root directory to serve from the server.\n * @returns The HTTP server.\n */\nexport async function startServer(options: ServerOptions) {\n await assertRoot(options.root);\n\n const log = createModuleLogger(rootLogger, 'server');\n const app = express();\n\n app.use((_request, response, next) => {\n response.header('Access-Control-Allow-Origin', '*');\n response.header('Access-Control-Allow-Credentials', 'true');\n response.header('Access-Control-Allow-Methods', 'GET, OPTIONS');\n response.header('Access-Control-Allow-Headers', 'Content-Type');\n\n next();\n });\n\n app.use('/environment', express.static(SNAPS_EXECUTION_ENVIRONMENTS_PATH));\n app.use('/simulator', express.static(SNAPS_SIMULATOR_PATH));\n app.use(express.static(pathResolve(process.cwd(), options.root)));\n\n const server = createServer(app);\n return await new Promise<Server>((resolve, reject) => {\n server.listen(options.port, () => {\n resolve(server);\n });\n\n server.on('error', (error) => {\n log(error);\n reject(error);\n });\n });\n}\n"],"names":["assertIsSnapManifest","isDirectory","isFile","createModuleLogger","express","promises","fs","createServer","resolve","pathResolve","dirname","rootLogger","SNAPS_EXECUTION_ENVIRONMENTS_PATH","require","SNAPS_SIMULATOR_PATH","assertRoot","root","Error","manifestPath","manifest","readFile","then","JSON","parse","filePath","source","location","npm","startServer","options","log","app","use","_request","response","next","header","static","process","cwd","server","Promise","reject","listen","port","on","error"],"mappings":"AAAA,SACEA,oBAAoB,EACpBC,WAAW,EACXC,MAAM,QAED,wBAAwB;AAC/B,SAASC,kBAAkB,QAAQ,kBAAkB;AACrD,OAAOC,aAAa,UAAU;AAC9B,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,YAAY,QAAgB,OAAO;AAC5C,SAASC,WAAWC,WAAW,EAAEC,OAAO,QAAQ,OAAO;AAGvD,SAASC,UAAU,QAAQ,WAAW;AAEtC,MAAMC,oCAAoCH,YACxCC,QACEG,QAAQL,OAAO,CAAC,yDAElB,QACA,cACA;AAGF,MAAMM,uBAAuBL,YAC3BC,QAAQG,QAAQL,OAAO,CAAC,4CACxB,QACA,WACA;AAQF;;;;;;;;;CASC,GACD,eAAeO,WAAWC,IAAY;IACpC,IAAI,CAACA,MAAM;QACT,MAAM,IAAIC,MAAM;IAClB;IAEA,IAAI,CAAE,MAAMhB,YAAYe,MAAM,QAAS;QACrC,MAAM,IAAIC,MAAM,CAAC,gBAAgB,EAAED,KAAK,qBAAqB,CAAC;IAChE;IAEA,MAAME,eAAeT,YAAYO,MAAM;IACvC,MAAMG,WAAyB,MAAMb,GAClCc,QAAQ,CAACF,cAAc,QACvBG,IAAI,CAACC,KAAKC,KAAK;IAElBvB,qBAAqBmB;IACrB,MAAMK,WAAWf,YAAYO,MAAMG,SAASM,MAAM,CAACC,QAAQ,CAACC,GAAG,CAACH,QAAQ;IAExE,IAAI,CAAE,MAAMtB,OAAOsB,WAAY;QAC7B,MAAM,IAAIP,MACR,CAAC,MAAM,EAAEO,SAAS,sEAAsE,CAAC;IAE7F;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,eAAeI,YAAYC,OAAsB;IACtD,MAAMd,WAAWc,QAAQb,IAAI;IAE7B,MAAMc,MAAM3B,mBAAmBQ,YAAY;IAC3C,MAAMoB,MAAM3B;IAEZ2B,IAAIC,GAAG,CAAC,CAACC,UAAUC,UAAUC;QAC3BD,SAASE,MAAM,CAAC,+BAA+B;QAC/CF,SAASE,MAAM,CAAC,oCAAoC;QACpDF,SAASE,MAAM,CAAC,gCAAgC;QAChDF,SAASE,MAAM,CAAC,gCAAgC;QAEhDD;IACF;IAEAJ,IAAIC,GAAG,CAAC,gBAAgB5B,QAAQiC,MAAM,CAACzB;IACvCmB,IAAIC,GAAG,CAAC,cAAc5B,QAAQiC,MAAM,CAACvB;IACrCiB,IAAIC,GAAG,CAAC5B,QAAQiC,MAAM,CAAC5B,YAAY6B,QAAQC,GAAG,IAAIV,QAAQb,IAAI;IAE9D,MAAMwB,SAASjC,aAAawB;IAC5B,OAAO,MAAM,IAAIU,QAAgB,CAACjC,SAASkC;QACzCF,OAAOG,MAAM,CAACd,QAAQe,IAAI,EAAE;YAC1BpC,QAAQgC;QACV;QAEAA,OAAOK,EAAE,CAAC,SAAS,CAACC;YAClBhB,IAAIgB;YACJJ,OAAOI;QACT;IACF;AACF"}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { NotificationType } from '@metamask/rpc-methods';
|
|
2
|
+
import { ComponentStruct } from '@metamask/snaps-ui';
|
|
3
|
+
import { enumValue } from '@metamask/snaps-utils';
|
|
4
|
+
import { bytesToHex, JsonStruct, StrictHexStruct, valueToBytes } from '@metamask/utils';
|
|
5
|
+
import { randomBytes } from 'crypto';
|
|
6
|
+
import { array, assign, bigint, coerce, defaulted, instance, literal, number, object, optional, string, type, union } from 'superstruct';
|
|
7
|
+
// TODO: Export this from `@metamask/utils` instead.
|
|
8
|
+
const BytesLikeStruct = union([
|
|
9
|
+
bigint(),
|
|
10
|
+
number(),
|
|
11
|
+
string(),
|
|
12
|
+
instance(Uint8Array)
|
|
13
|
+
]);
|
|
14
|
+
export const TransactionOptionsStruct = object({
|
|
15
|
+
/**
|
|
16
|
+
* The CAIP-2 chain ID to send the transaction on. Defaults to `eip155:1`.
|
|
17
|
+
*/ chainId: defaulted(string(), 'eip155:1'),
|
|
18
|
+
/**
|
|
19
|
+
* The origin to send the transaction from. Defaults to `metamask.io`.
|
|
20
|
+
*/ origin: defaulted(string(), 'metamask.io'),
|
|
21
|
+
/**
|
|
22
|
+
* The address to send the transaction from. Defaults to a randomly generated
|
|
23
|
+
* address.
|
|
24
|
+
*/ // TODO: Move this coercer to `@metamask/utils`.
|
|
25
|
+
from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value)=>{
|
|
26
|
+
if (value) {
|
|
27
|
+
return valueToBytes(value);
|
|
28
|
+
}
|
|
29
|
+
return bytesToHex(randomBytes(20));
|
|
30
|
+
}),
|
|
31
|
+
/**
|
|
32
|
+
* The address to send the transaction to. Defaults to a randomly generated
|
|
33
|
+
* address.
|
|
34
|
+
*/ // TODO: Move this coercer to `@metamask/utils`.
|
|
35
|
+
to: coerce(StrictHexStruct, optional(BytesLikeStruct), (value)=>{
|
|
36
|
+
if (value) {
|
|
37
|
+
return valueToBytes(value);
|
|
38
|
+
}
|
|
39
|
+
return bytesToHex(randomBytes(20));
|
|
40
|
+
}),
|
|
41
|
+
/**
|
|
42
|
+
* The value to send with the transaction. The value may be specified as a
|
|
43
|
+
* `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.
|
|
44
|
+
*/ value: defaulted(coerce(StrictHexStruct, BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), '0x0'),
|
|
45
|
+
/**
|
|
46
|
+
* The gas limit to use for the transaction. The gas limit may be specified
|
|
47
|
+
* as a `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `21_000`.
|
|
48
|
+
*/ gasLimit: defaulted(coerce(StrictHexStruct, BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), valueToBytes(21000)),
|
|
49
|
+
/**
|
|
50
|
+
* The max fee per gas (in Wei) to use for the transaction. The max fee per
|
|
51
|
+
* gas may be specified as a `number`, `bigint`, `string`, or `Uint8Array`.
|
|
52
|
+
* Defaults to `1`.
|
|
53
|
+
*/ maxFeePerGas: defaulted(coerce(StrictHexStruct, BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), valueToBytes(1)),
|
|
54
|
+
/**
|
|
55
|
+
* The max priority fee per gas (in Wei) to use for the transaction. The max
|
|
56
|
+
* priority fee per gas may be specified as a `number`, `bigint`, `string`,
|
|
57
|
+
* or `Uint8Array`. Defaults to `1`.
|
|
58
|
+
*/ maxPriorityFeePerGas: defaulted(coerce(StrictHexStruct, BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), valueToBytes(1)),
|
|
59
|
+
/**
|
|
60
|
+
* The nonce to use for the transaction. The nonce may be specified as a
|
|
61
|
+
* `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.
|
|
62
|
+
*/ nonce: defaulted(coerce(StrictHexStruct, BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), valueToBytes(0)),
|
|
63
|
+
/**
|
|
64
|
+
* The data to send with the transaction. The data may be specified as a
|
|
65
|
+
* `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0x`.
|
|
66
|
+
*/ data: defaulted(coerce(union([
|
|
67
|
+
StrictHexStruct,
|
|
68
|
+
literal('0x')
|
|
69
|
+
]), BytesLikeStruct, (value)=>bytesToHex(valueToBytes(value))), '0x')
|
|
70
|
+
});
|
|
71
|
+
export const SnapOptionsStruct = object({
|
|
72
|
+
/**
|
|
73
|
+
* The timeout in milliseconds to use for requests to the snap. Defaults to
|
|
74
|
+
* `1000`.
|
|
75
|
+
*/ timeout: defaulted(optional(number()), 1000)
|
|
76
|
+
});
|
|
77
|
+
export const InterfaceStruct = type({
|
|
78
|
+
content: optional(ComponentStruct)
|
|
79
|
+
});
|
|
80
|
+
export const SnapResponseStruct = assign(InterfaceStruct, object({
|
|
81
|
+
id: string(),
|
|
82
|
+
response: union([
|
|
83
|
+
object({
|
|
84
|
+
result: JsonStruct
|
|
85
|
+
}),
|
|
86
|
+
object({
|
|
87
|
+
error: JsonStruct
|
|
88
|
+
})
|
|
89
|
+
]),
|
|
90
|
+
notifications: array(object({
|
|
91
|
+
id: string(),
|
|
92
|
+
message: string(),
|
|
93
|
+
type: union([
|
|
94
|
+
enumValue(NotificationType.InApp),
|
|
95
|
+
enumValue(NotificationType.Native)
|
|
96
|
+
])
|
|
97
|
+
}))
|
|
98
|
+
}));
|
|
99
|
+
|
|
100
|
+
//# sourceMappingURL=structs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/structs.ts"],"sourcesContent":["import { NotificationType } from '@metamask/rpc-methods';\nimport { ComponentStruct } from '@metamask/snaps-ui';\nimport { enumValue } from '@metamask/snaps-utils';\nimport {\n bytesToHex,\n JsonStruct,\n StrictHexStruct,\n valueToBytes,\n} from '@metamask/utils';\nimport { randomBytes } from 'crypto';\nimport {\n array,\n assign,\n bigint,\n coerce,\n defaulted,\n instance,\n literal,\n number,\n object,\n optional,\n string,\n type,\n union,\n} from 'superstruct';\n\n// TODO: Export this from `@metamask/utils` instead.\nconst BytesLikeStruct = union([\n bigint(),\n number(),\n string(),\n instance(Uint8Array),\n]);\n\nexport const TransactionOptionsStruct = object({\n /**\n * The CAIP-2 chain ID to send the transaction on. Defaults to `eip155:1`.\n */\n chainId: defaulted(string(), 'eip155:1'),\n\n /**\n * The origin to send the transaction from. Defaults to `metamask.io`.\n */\n origin: defaulted(string(), 'metamask.io'),\n\n /**\n * The address to send the transaction from. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n from: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return valueToBytes(value);\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The address to send the transaction to. Defaults to a randomly generated\n * address.\n */\n // TODO: Move this coercer to `@metamask/utils`.\n to: coerce(StrictHexStruct, optional(BytesLikeStruct), (value) => {\n if (value) {\n return valueToBytes(value);\n }\n\n return bytesToHex(randomBytes(20));\n }),\n\n /**\n * The value to send with the transaction. The value may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n value: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x0',\n ),\n\n /**\n * The gas limit to use for the transaction. The gas limit may be specified\n * as a `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `21_000`.\n */\n gasLimit: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(21_000),\n ),\n\n /**\n * The max fee per gas (in Wei) to use for the transaction. The max fee per\n * gas may be specified as a `number`, `bigint`, `string`, or `Uint8Array`.\n * Defaults to `1`.\n */\n maxFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The max priority fee per gas (in Wei) to use for the transaction. The max\n * priority fee per gas may be specified as a `number`, `bigint`, `string`,\n * or `Uint8Array`. Defaults to `1`.\n */\n maxPriorityFeePerGas: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(1),\n ),\n\n /**\n * The nonce to use for the transaction. The nonce may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0`.\n */\n nonce: defaulted(\n coerce(StrictHexStruct, BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n valueToBytes(0),\n ),\n\n /**\n * The data to send with the transaction. The data may be specified as a\n * `number`, `bigint`, `string`, or `Uint8Array`. Defaults to `0x`.\n */\n data: defaulted(\n coerce(union([StrictHexStruct, literal('0x')]), BytesLikeStruct, (value) =>\n bytesToHex(valueToBytes(value)),\n ),\n '0x',\n ),\n});\n\nexport const SnapOptionsStruct = object({\n /**\n * The timeout in milliseconds to use for requests to the snap. Defaults to\n * `1000`.\n */\n timeout: defaulted(optional(number()), 1000),\n});\n\nexport const InterfaceStruct = type({\n content: optional(ComponentStruct),\n});\n\nexport const SnapResponseStruct = assign(\n InterfaceStruct,\n object({\n id: string(),\n\n response: union([\n object({\n result: JsonStruct,\n }),\n object({\n error: JsonStruct,\n }),\n ]),\n\n notifications: array(\n object({\n id: string(),\n message: string(),\n type: union([\n enumValue(NotificationType.InApp),\n enumValue(NotificationType.Native),\n ]),\n }),\n ),\n }),\n);\n"],"names":["NotificationType","ComponentStruct","enumValue","bytesToHex","JsonStruct","StrictHexStruct","valueToBytes","randomBytes","array","assign","bigint","coerce","defaulted","instance","literal","number","object","optional","string","type","union","BytesLikeStruct","Uint8Array","TransactionOptionsStruct","chainId","origin","from","value","to","gasLimit","maxFeePerGas","maxPriorityFeePerGas","nonce","data","SnapOptionsStruct","timeout","InterfaceStruct","content","SnapResponseStruct","id","response","result","error","notifications","message","InApp","Native"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,wBAAwB;AACzD,SAASC,eAAe,QAAQ,qBAAqB;AACrD,SAASC,SAAS,QAAQ,wBAAwB;AAClD,SACEC,UAAU,EACVC,UAAU,EACVC,eAAe,EACfC,YAAY,QACP,kBAAkB;AACzB,SAASC,WAAW,QAAQ,SAAS;AACrC,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,SAAS,EACTC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,IAAI,EACJC,KAAK,QACA,cAAc;AAErB,oDAAoD;AACpD,MAAMC,kBAAkBD,MAAM;IAC5BV;IACAK;IACAG;IACAL,SAASS;CACV;AAED,OAAO,MAAMC,2BAA2BP,OAAO;IAC7C;;GAEC,GACDQ,SAASZ,UAAUM,UAAU;IAE7B;;GAEC,GACDO,QAAQb,UAAUM,UAAU;IAE5B;;;GAGC,GACD,gDAAgD;IAChDQ,MAAMf,OAAON,iBAAiBY,SAASI,kBAAkB,CAACM;QACxD,IAAIA,OAAO;YACT,OAAOrB,aAAaqB;QACtB;QAEA,OAAOxB,WAAWI,YAAY;IAChC;IAEA;;;GAGC,GACD,gDAAgD;IAChDqB,IAAIjB,OAAON,iBAAiBY,SAASI,kBAAkB,CAACM;QACtD,IAAIA,OAAO;YACT,OAAOrB,aAAaqB;QACtB;QAEA,OAAOxB,WAAWI,YAAY;IAChC;IAEA;;;GAGC,GACDoB,OAAOf,UACLD,OAAON,iBAAiBgB,iBAAiB,CAACM,QACxCxB,WAAWG,aAAaqB,UAE1B;IAGF;;;GAGC,GACDE,UAAUjB,UACRD,OAAON,iBAAiBgB,iBAAiB,CAACM,QACxCxB,WAAWG,aAAaqB,UAE1BrB,aAAa;IAGf;;;;GAIC,GACDwB,cAAclB,UACZD,OAAON,iBAAiBgB,iBAAiB,CAACM,QACxCxB,WAAWG,aAAaqB,UAE1BrB,aAAa;IAGf;;;;GAIC,GACDyB,sBAAsBnB,UACpBD,OAAON,iBAAiBgB,iBAAiB,CAACM,QACxCxB,WAAWG,aAAaqB,UAE1BrB,aAAa;IAGf;;;GAGC,GACD0B,OAAOpB,UACLD,OAAON,iBAAiBgB,iBAAiB,CAACM,QACxCxB,WAAWG,aAAaqB,UAE1BrB,aAAa;IAGf;;;GAGC,GACD2B,MAAMrB,UACJD,OAAOS,MAAM;QAACf;QAAiBS,QAAQ;KAAM,GAAGO,iBAAiB,CAACM,QAChExB,WAAWG,aAAaqB,UAE1B;AAEJ,GAAG;AAEH,OAAO,MAAMO,oBAAoBlB,OAAO;IACtC;;;GAGC,GACDmB,SAASvB,UAAUK,SAASF,WAAW;AACzC,GAAG;AAEH,OAAO,MAAMqB,kBAAkBjB,KAAK;IAClCkB,SAASpB,SAAShB;AACpB,GAAG;AAEH,OAAO,MAAMqC,qBAAqB7B,OAChC2B,iBACApB,OAAO;IACLuB,IAAIrB;IAEJsB,UAAUpB,MAAM;QACdJ,OAAO;YACLyB,QAAQrC;QACV;QACAY,OAAO;YACL0B,OAAOtC;QACT;KACD;IAEDuC,eAAenC,MACbQ,OAAO;QACLuB,IAAIrB;QACJ0B,SAAS1B;QACTC,MAAMC,MAAM;YACVlB,UAAUF,iBAAiB6C,KAAK;YAChC3C,UAAUF,iBAAiB8C,MAAM;SAClC;IACH;AAEJ,IACA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/internals/types.ts"],"sourcesContent":["import { NotificationType } from '@metamask/rpc-methods';\nimport { ApplicationState, Dispatch } from '@metamask/snaps-simulator';\nimport { EnumToUnion } from '@metamask/snaps-utils';\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n // This API is injected into the page by the simulator. It allows us to\n // dispatch actions to the simulator, and read the state directly from the\n // Redux store.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n __SIMULATOR_API__: {\n dispatch: Dispatch;\n subscribe: (listener: () => void) => () => void;\n getState: () => ApplicationState;\n getRequestId: () => string;\n getNotifications: (requestId: string) => {\n id: string;\n message: string;\n type: EnumToUnion<NotificationType>;\n }[];\n };\n }\n}\n\nexport {};\n"],"names":[],"mappings":"AAAA,WAyBU"}
|