-
Notifications
You must be signed in to change notification settings - Fork 542
/
dialog.ts
224 lines (197 loc) · 6.13 KB
/
dialog.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import {
PermissionSpecificationBuilder,
PermissionType,
RestrictedMethodOptions,
ValidPermissionSpecification,
} from '@metamask/permission-controller';
import { Component, ComponentStruct } from '@metamask/snaps-ui';
import { NonEmptyArray } from '@metamask/utils';
import { ethErrors } from 'eth-rpc-errors';
import {
create,
enums,
Infer,
literal,
object,
optional,
size,
string,
Struct,
StructError,
type,
union,
} from 'superstruct';
const methodName = 'snap_dialog';
export enum DialogType {
Alert = 'Alert',
Confirmation = 'Confirmation',
Prompt = 'Prompt',
}
const PlaceholderStruct = optional(size(string(), 1, 40));
export type Placeholder = Infer<typeof PlaceholderStruct>;
type ShowDialog = (
snapId: string,
type: DialogType,
ui: Component,
placeholder?: Placeholder,
) => Promise<null | boolean | string>;
export type DialogMethodHooks = {
/**
* @param snapId - The ID of the Snap that created the alert.
* @param type - The dialog type.
* @param ui - The dialog custom UI.
* @param placeholder - The placeholder for the Prompt dialog input.
*/
showDialog: ShowDialog;
};
type DialogSpecificationBuilderOptions = {
allowedCaveats?: Readonly<NonEmptyArray<string>> | null;
methodHooks: DialogMethodHooks;
};
type DialogSpecification = ValidPermissionSpecification<{
permissionType: PermissionType.RestrictedMethod;
targetKey: typeof methodName;
methodImplementation: ReturnType<typeof getDialogImplementation>;
allowedCaveats: Readonly<NonEmptyArray<string>> | null;
}>;
/**
* The specification builder for the `snap_dialog` permission. `snap_dialog`
* lets the Snap display one of the following dialogs to the user:
* - An alert, for displaying information.
* - A confirmation, for accepting or rejecting some action.
* - A prompt, for inputting some information.
*
* @param options - The specification builder options.
* @param options.allowedCaveats - The optional allowed caveats for the
* permission.
* @param options.methodHooks - The RPC method hooks needed by the method
* implementation.
* @returns The specification for the `snap_dialog` permission.
*/
const specificationBuilder: PermissionSpecificationBuilder<
PermissionType.RestrictedMethod,
DialogSpecificationBuilderOptions,
DialogSpecification
> = ({
allowedCaveats = null,
methodHooks,
}: DialogSpecificationBuilderOptions) => {
return {
permissionType: PermissionType.RestrictedMethod,
targetKey: methodName,
allowedCaveats,
methodImplementation: getDialogImplementation(methodHooks),
};
};
export const dialogBuilder = Object.freeze({
targetKey: methodName,
specificationBuilder,
methodHooks: {
showDialog: true,
},
} as const);
// Note: We use `type` here instead of `object` because `type` does not validate
// the keys of the object, which is what we want.
const BaseParamsStruct = type({
type: enums([DialogType.Alert, DialogType.Confirmation, DialogType.Prompt]),
});
const AlertParametersStruct = object({
type: literal(DialogType.Alert),
ui: ComponentStruct,
});
const ConfirmationParametersStruct = object({
type: literal(DialogType.Confirmation),
ui: ComponentStruct,
});
const PromptParametersStruct = object({
type: literal(DialogType.Prompt),
ui: ComponentStruct,
placeholder: PlaceholderStruct,
});
const DialogParametersStruct = union([
AlertParametersStruct,
ConfirmationParametersStruct,
PromptParametersStruct,
]);
export type DialogParameters = Infer<typeof DialogParametersStruct>;
const structs = {
[DialogType.Alert]: AlertParametersStruct,
[DialogType.Confirmation]: ConfirmationParametersStruct,
[DialogType.Prompt]: PromptParametersStruct,
};
/**
* Builds the method implementation for `snap_dialog`.
*
* @param hooks - The RPC method hooks.
* @param hooks.showDialog - A function that shows the specified dialog in the
* MetaMask UI and returns the appropriate value for the dialog type.
* @returns The method implementation which return value depends on the dialog
* type, valid return types are: string, boolean, null.
*/
export function getDialogImplementation({ showDialog }: DialogMethodHooks) {
return async function dialogImplementation(
args: RestrictedMethodOptions<DialogParameters>,
): Promise<boolean | null | string> {
const {
params,
context: { origin },
} = args;
const validatedType = getValidatedType(params);
const validatedParams = getValidatedParams(params, structs[validatedType]);
const { ui } = validatedParams;
const placeholder =
validatedParams.type === DialogType.Prompt
? validatedParams.placeholder
: undefined;
return showDialog(origin, validatedType, ui, placeholder);
};
}
/**
* Get the validated type of the dialog parameters. Throws an error if the type
* is invalid.
*
* @param params - The parameters to validate.
* @returns The validated type of the dialog parameters.
*/
function getValidatedType(params: unknown): DialogType {
try {
return create(params, BaseParamsStruct).type;
} catch (error) {
throw ethErrors.rpc.invalidParams({
message: `The "type" property must be one of: ${Object.values(
DialogType,
).join(', ')}.`,
});
}
}
/**
* Validates the confirm method `params` and returns them cast to the correct
* type. Throws if validation fails.
*
* @param params - The unvalidated params object from the method request.
* @param struct - The struct to validate the params against.
* @returns The validated confirm method parameter object.
*/
function getValidatedParams(
params: unknown,
struct: Struct<any>,
): DialogParameters {
try {
return create(params, struct);
} catch (error) {
if (error instanceof StructError) {
const { key, type: errorType } = error;
if (key === 'placeholder' && errorType === 'never') {
throw ethErrors.rpc.invalidParams({
message:
'Invalid params: Alerts or confirmations may not specify a "placeholder" field.',
});
}
throw ethErrors.rpc.invalidParams({
message: `Invalid params: ${error.message}.`,
});
}
/* istanbul ignore next */
throw ethErrors.rpc.internal();
}
}