-
Notifications
You must be signed in to change notification settings - Fork 573
/
Copy pathSnapController.ts
2007 lines (1764 loc) · 55.5 KB
/
SnapController.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
AddApprovalRequest,
BaseControllerV2 as BaseController,
Caveat,
GetEndowments,
GetPermissions,
GrantPermissions,
HasPermission,
HasPermissions,
RequestPermissions,
RestrictedControllerMessenger,
RevokeAllPermissions,
RevokePermissionForAllSubjects,
RevokePermissions,
SubjectPermissions,
ValidPermission,
} from '@metamask/controllers';
import { ErrorJSON, SnapData, SnapId } from '@metamask/snap-types';
import {
Duration,
hasProperty,
inMilliseconds,
isNonEmptyArray,
Json,
timeSince,
} from '@metamask/utils';
import passworder from '@metamask/browser-passworder';
import { ethErrors, serializeError } from 'eth-rpc-errors';
import { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';
import type { Patch } from 'immer';
import { nanoid } from 'nanoid';
import {
assertExhaustive,
ErrorMessageEvent,
ExecuteSnapAction,
GetRpcRequestHandlerAction,
TerminateAllSnapsAction,
TerminateSnapAction,
} from '..';
import { hasTimedOut, setDiff, withTimeout } from '../utils';
import { DEFAULT_ENDOWMENTS } from './default-endowments';
import { LONG_RUNNING_PERMISSION } from './endowments';
import { SnapManifest, validateSnapJsonFile } from './json-schemas';
import { RequestQueue } from './RequestQueue';
import {
DEFAULT_REQUESTED_SNAP_VERSION,
fetchNpmSnap,
getSnapPermissionName,
getSnapPrefix,
gtVersion,
isValidSnapVersionRange,
LOCALHOST_HOSTNAMES,
NpmSnapFileNames,
resolveVersion,
satifiesVersionRange,
SnapIdPrefixes,
SNAP_PREFIX,
ValidatedSnapId,
validateSnapShasum,
} from './utils';
export const controllerName = 'SnapController';
export const SNAP_PREFIX_REGEX = new RegExp(`^${SNAP_PREFIX}`, 'u');
export const SNAP_APPROVAL_UPDATE = 'wallet_updateSnap';
type TruncatedSnapFields =
| 'id'
| 'initialPermissions'
| 'permissionName'
| 'version';
const TRUNCATED_SNAP_PROPERTIES = new Set<TruncatedSnapFields>([
'initialPermissions',
'id',
'permissionName',
'version',
]);
type RequestedSnapPermissions = {
[permission: string]: Record<string, Json>;
};
/**
* A Snap as it exists in {@link SnapController} state.
*/
export type Snap = {
/**
* Whether the Snap is enabled, which determines if it can be started.
*/
enabled: boolean;
/**
* The ID of the Snap.
*/
id: SnapId;
/**
* The initial permissions of the Snap, which will be requested when it is
* installed.
*/
initialPermissions: RequestedSnapPermissions;
/**
* The Snap's manifest file.
*/
manifest: SnapManifest;
/**
* The name of the permission used to invoke the Snap.
*/
permissionName: string;
/**
* The source code of the Snap.
*/
sourceCode: string;
/**
* The current status of the Snap, e.g. whether it's running or stopped.
*/
status: SnapStatus;
/**
* The version of the Snap.
*/
version: string;
/**
* The version history of the Snap.
* Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.
*/
versionHistory: VersionHistory[];
};
export type VersionHistory = {
origin: string;
version: string;
// Unix timestamp
date: number;
};
/**
* A wrapper type for any data stored during runtime of Snaps.
* It is not persisted in state as it contains non-serializable data and is only relevant for the current session.
*/
export interface SnapRuntimeData {
/**
* A promise that resolves when the Snap has finished installing
*/
installPromise: null | Promise<Snap>;
/**
* A Unix timestamp for the last time the Snap received an RPC request
*/
lastRequest: null | number;
/**
* The current number of pending requests
*/
pendingRequests: number;
/**
* RPC handler designated for the Snap
*/
rpcHandler:
| null
| ((origin: string, request: Record<string, unknown>) => Promise<unknown>);
}
/**
* A {@link Snap} object with the fields that are relevant to an external
* caller.
*/
export type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;
export type SnapError = {
message: string;
code: number;
data?: Json;
};
/**
* The return type of {@link SnapController._fetchSnap} and its sibling methods.
*/
type FetchSnapResult = {
/**
* The manifest of the fetched Snap.
*/
manifest: SnapManifest;
/**
* The source code of the fetched Snap.
*/
sourceCode: string;
/**
* The raw XML content of the Snap's SVG icon, if any.
*/
svgIcon?: string;
};
export type ProcessSnapResult =
| TruncatedSnap
| { error: SerializedEthereumRpcError };
export type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;
// Types that probably should be defined elsewhere in prod
type CloseAllConnectionsFunction = (origin: string) => void;
type StoredSnaps = Record<SnapId, Snap>;
export type SnapControllerState = {
snaps: StoredSnaps;
snapStates: Record<SnapId, string>;
snapErrors: {
[internalID: string]: SnapError & { internalID: string };
};
};
// Controller Messenger Actions
/**
* Adds the specified Snap to state. Used during installation.
*/
export type AddSnap = {
type: `${typeof controllerName}:add`;
handler: SnapController['add'];
};
/**
* Gets the specified Snap from state.
*/
export type GetSnap = {
type: `${typeof controllerName}:get`;
handler: SnapController['get'];
};
/**
* Handles sending an inbound rpc message to a snap and returns its result.
*/
export type HandleSnapRpcRequest = {
type: `${typeof controllerName}:handleRpcRequest`;
handler: SnapController['handleRpcRequest'];
};
/**
* Gets the specified Snap's persisted state.
*/
export type GetSnapState = {
type: `${typeof controllerName}:getSnapState`;
handler: SnapController['getSnapState'];
};
/**
* Checks if the specified snap exists in state.
*/
export type HasSnap = {
type: `${typeof controllerName}:has`;
handler: SnapController['has'];
};
/**
* Updates the specified Snap's persisted state.
*/
export type UpdateSnapState = {
type: `${typeof controllerName}:updateSnapState`;
handler: SnapController['updateSnapState'];
};
/**
* Clears the specified Snap's persisted state.
*/
export type ClearSnapState = {
type: `${typeof controllerName}:clearSnapState`;
handler: SnapController['clearSnapState'];
};
export type SnapControllerActions =
| AddSnap
| ClearSnapState
| GetSnap
| GetSnapState
| HandleSnapRpcRequest
| HasSnap
| UpdateSnapState;
// Controller Messenger Events
export type SnapStateChange = {
type: `${typeof controllerName}:stateChange`;
payload: [SnapControllerState, Patch[]];
};
/**
* Emitted when a Snap has been added to state during installation.
*/
export type SnapAdded = {
type: `${typeof controllerName}:snapAdded`;
payload: [snap: Snap, svgIcon: string | undefined];
};
/**
* Emitted when a snap has been started after being added and authorized during
* installation.
*/
export type SnapInstalled = {
type: `${typeof controllerName}:snapInstalled`;
payload: [snap: TruncatedSnap];
};
/**
* Emitted when a snap is removed.
*/
export type SnapRemoved = {
type: `${typeof controllerName}:snapRemoved`;
payload: [snap: TruncatedSnap];
};
/**
* Emitted when a snap is updated.
*/
export type SnapUpdated = {
type: `${typeof controllerName}:snapUpdated`;
payload: [snap: TruncatedSnap, oldVersion: string];
};
/**
* Emitted when a Snap is terminated. This is different from the snap being
* stopped as it can also be triggered when a snap fails initialization.
*/
export type SnapTerminated = {
type: `${typeof controllerName}:snapTerminated`;
payload: [snap: TruncatedSnap];
};
export type SnapControllerEvents =
| SnapAdded
| SnapInstalled
| SnapRemoved
| SnapStateChange
| SnapUpdated
| SnapTerminated;
export type AllowedActions =
| GetEndowments
| GetPermissions
| HasPermission
| HasPermissions
| RevokePermissions
| RequestPermissions
| RevokeAllPermissions
| RevokePermissionForAllSubjects
| GrantPermissions
| RequestPermissions
| AddApprovalRequest
| GetRpcRequestHandlerAction
| ExecuteSnapAction
| TerminateAllSnapsAction
| TerminateSnapAction;
export type AllowedEvents = ErrorMessageEvent;
type SnapControllerMessenger = RestrictedControllerMessenger<
typeof controllerName,
SnapControllerActions | AllowedActions,
SnapControllerEvents | AllowedEvents,
AllowedActions['type'],
AllowedEvents['type']
>;
export enum AppKeyType {
stateEncryption = 'stateEncryption',
}
type GetAppKey = (subject: string, appKeyType: AppKeyType) => Promise<string>;
type FeatureFlags = {
/**
* We still need to implement new UI approval page in metamask-extension before we can allow DApps to update Snaps.
* After it's added, this flag can be removed.
*
* @see {SNAP_APPROVAL_UPDATE}
* @see {SnapController.processRequestedSnap}
*/
dappsCanUpdateSnaps?: true;
};
type SnapControllerArgs = {
/**
* A teardown function that allows the host to clean up its instrumentation
* for a running snap.
*/
closeAllConnections: CloseAllConnectionsFunction;
/**
* The names of endowment permissions whose values are the names of JavaScript
* APIs that will be added to the snap execution environment at runtime.
*/
environmentEndowmentPermissions: string[];
/**
* The function that will be used by the controller fo make network requests.
* Should be compatible with {@link fetch}.
*/
fetchFunction?: typeof fetch;
/**
* Flags that enable or disable features in the controller.
* See {@link FeatureFlags}.
*/
featureFlags: FeatureFlags;
/**
* A function to get an "app key" for a specific subject.
*/
getAppKey: GetAppKey;
/**
* How frequently to check whether a snap is idle.
*/
idleTimeCheckInterval?: number;
/**
* The maximum amount of time that a snap may be idle.
*/
maxIdleTime?: number;
/**
* The controller messenger.
*/
messenger: SnapControllerMessenger;
/**
* The maximum amount of time a snap may take to process an RPC request,
* unless it is permitted to take longer.
*/
maxRequestTime?: number;
/**
* The npm registry URL that will be used to fetch published snaps.
*/
npmRegistryUrl?: string;
/**
* Persisted state that will be used for rehydration.
*/
state?: SnapControllerState;
};
type AddSnapArgsBase = {
id: SnapId;
origin: string;
versionRange?: string;
};
// A snap can either be added directly, with manifest and source code, or it
// can be fetched and then added.
type AddSnapArgs =
| AddSnapArgsBase
| (AddSnapArgsBase & {
manifest: SnapManifest;
sourceCode: string;
});
// When we set a snap, we need all required properties to be present and
// validated.
type SetSnapArgs = Omit<AddSnapArgs, 'id'> & {
id: ValidatedSnapId;
manifest: SnapManifest;
sourceCode: string;
svgIcon?: string;
};
const defaultState: SnapControllerState = {
snapErrors: {},
snaps: {},
snapStates: {},
};
export enum SnapStatus {
installing = 'installing',
running = 'running',
stopped = 'stopped',
crashed = 'crashed',
}
export enum SnapStatusEvent {
start = 'start',
stop = 'stop',
crash = 'crash',
update = 'update',
}
/**
* Guard transitioning when the snap is disabled.
*
* @param serializedSnap - The snap metadata.
* @returns A boolean signalling whether the passed snap is enabled or not.
*/
const disabledGuard = (serializedSnap: Snap) => {
return serializedSnap.enabled;
};
/**
* The state machine configuration for a snaps `status` state.
* Using a state machine for a snaps `status` ensures that the snap transitions to a valid next lifecycle state.
* Supports a very minimal subset of XState conventions outlined in `_transitionSnapState`.
*/
const snapStatusStateMachineConfig = {
initial: SnapStatus.installing,
states: {
[SnapStatus.installing]: {
on: {
[SnapStatusEvent.start]: {
target: SnapStatus.running,
cond: disabledGuard,
},
},
},
[SnapStatus.running]: {
on: {
[SnapStatusEvent.stop]: SnapStatus.stopped,
[SnapStatusEvent.crash]: SnapStatus.crashed,
},
},
[SnapStatus.stopped]: {
on: {
[SnapStatusEvent.start]: {
target: SnapStatus.running,
cond: disabledGuard,
},
[SnapStatusEvent.update]: SnapStatus.installing,
},
},
[SnapStatus.crashed]: {
on: {
[SnapStatusEvent.start]: {
target: SnapStatus.running,
cond: disabledGuard,
},
},
},
},
} as const;
const name = 'SnapController';
/*
* A snap is initialized in three phases:
* - Add: Loads the snap from a remote source and parses it.
* - Authorize: Requests the snap's required permissions from the user.
* - Start: Initializes the snap in its SES realm with the authorized permissions.
*/
export class SnapController extends BaseController<
string,
SnapControllerState,
SnapControllerMessenger
> {
private _closeAllConnections: CloseAllConnectionsFunction;
private _environmentEndowmentPermissions: string[];
private _featureFlags: FeatureFlags;
private _fetchFunction: typeof fetch;
private _idleTimeCheckInterval: number;
private _maxIdleTime: number;
private _maxRequestTime: number;
private _npmRegistryUrl?: string;
private _snapsRuntimeData: Map<SnapId, SnapRuntimeData>;
private _getAppKey: GetAppKey;
private _timeoutForLastRequestStatus?: number;
constructor({
closeAllConnections,
messenger,
state,
getAppKey,
environmentEndowmentPermissions = [],
npmRegistryUrl,
idleTimeCheckInterval = inMilliseconds(5, Duration.Second),
maxIdleTime = inMilliseconds(30, Duration.Second),
maxRequestTime = inMilliseconds(60, Duration.Second),
fetchFunction = globalThis.fetch.bind(globalThis),
featureFlags = {},
}: SnapControllerArgs) {
super({
messenger,
metadata: {
snapErrors: {
persist: false,
anonymous: false,
},
snapStates: {
persist: true,
anonymous: false,
},
snaps: {
persist: (snaps) => {
return Object.values(snaps)
.map((snap) => {
return {
...snap,
// At the time state is rehydrated, no snap will be running.
status: SnapStatus.stopped,
};
})
.reduce((memo: Record<string, Snap>, snap) => {
memo[snap.id] = snap;
return memo;
}, {});
},
anonymous: false,
},
},
name,
state: { ...defaultState, ...state },
});
this._closeAllConnections = closeAllConnections;
this._environmentEndowmentPermissions = environmentEndowmentPermissions;
this._featureFlags = featureFlags;
this._fetchFunction = fetchFunction;
this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);
this._getAppKey = getAppKey;
this._idleTimeCheckInterval = idleTimeCheckInterval;
this._maxIdleTime = maxIdleTime;
this._maxRequestTime = maxRequestTime;
this._npmRegistryUrl = npmRegistryUrl;
this._onUnhandledSnapError = this._onUnhandledSnapError.bind(this);
this._snapsRuntimeData = new Map();
this._pollForLastRequestStatus();
this.messagingSystem.subscribe(
'ExecutionService:unhandledError',
this._onUnhandledSnapError,
);
this.registerMessageHandlers();
}
/**
* Constructor helper for registering the controller's messaging system
* actions.
*/
private registerMessageHandlers(): void {
this.messagingSystem.registerActionHandler(
`${controllerName}:add`,
(...args) => this.add(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:clearSnapState`,
(...args) => this.clearSnapState(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:get`,
(...args) => this.get(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:getSnapState`,
(...args) => this.getSnapState(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:handleRpcRequest`,
(...args) => this.handleRpcRequest(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:has`,
(...args) => this.has(...args),
);
this.messagingSystem.registerActionHandler(
`${controllerName}:updateSnapState`,
(...args) => this.updateSnapState(...args),
);
}
_pollForLastRequestStatus() {
this._timeoutForLastRequestStatus = setTimeout(async () => {
await this._stopSnapsLastRequestPastMax();
this._pollForLastRequestStatus();
}, this._idleTimeCheckInterval) as unknown as number;
}
async _stopSnapsLastRequestPastMax() {
const entries = [...this._snapsRuntimeData.entries()];
return Promise.all(
entries
.filter(
([_snapId, runtime]) =>
runtime.pendingRequests === 0 &&
// lastRequest should always be set here but TypeScript wants this check
runtime.lastRequest &&
this._maxIdleTime &&
timeSince(runtime.lastRequest) > this._maxIdleTime,
)
.map(([snapId]) => this.stopSnap(snapId, SnapStatusEvent.stop)),
);
}
async _onUnhandledSnapError(snapId: SnapId, error: ErrorJSON) {
await this.stopSnap(snapId, SnapStatusEvent.crash);
this.addSnapError(error);
}
/**
* Transitions between states using `snapStatusStateMachineConfig` as the template to figure out the next state.
* This transition function uses a very minimal subset of XState conventions:
* - supports initial state
* - .on supports raw event target string
* - .on supports {target, cond} object
* - the arguments for `cond` is the `SerializedSnap` instead of Xstate convention of `(event, context) => boolean`
*
* @param snapId - The id of the snap to transition.
* @param event - The event enum to use to transition.
*/
_transitionSnapState(snapId: SnapId, event: SnapStatusEvent) {
const snapStatus = this.state.snaps[snapId].status;
let nextStatus =
(snapStatusStateMachineConfig.states[snapStatus].on as any)[event] ??
snapStatus;
if (nextStatus.cond) {
const cond = nextStatus.cond(this.state.snaps[snapId]);
if (cond === false) {
throw new Error(
`Condition failed for state transition "${snapId}" with event "${event}".`,
);
}
}
if (nextStatus.target) {
nextStatus = nextStatus.target;
}
if (nextStatus === snapStatus) {
return;
}
this.update((state: any) => {
state.snaps[snapId].status = nextStatus;
});
}
/**
* Starts the given snap. Throws an error if no such snap exists
* or if it is already running.
*
* @param snapId - The id of the Snap to start.
*/
async startSnap(snapId: SnapId): Promise<void> {
const snap = this.get(snapId);
if (!snap) {
throw new Error(`Snap "${snapId}" not found.`);
}
if (this.state.snaps[snapId].enabled === false) {
throw new Error(`Snap "${snapId}" is disabled.`);
}
await this._startSnap({
snapId,
sourceCode: snap.sourceCode,
});
}
/**
* Enables the given snap. A snap can only be started if it is enabled.
*
* @param snapId - The id of the Snap to enable.
*/
enableSnap(snapId: SnapId): void {
if (!this.has(snapId)) {
throw new Error(`Snap "${snapId}" not found.`);
}
this.update((state: any) => {
state.snaps[snapId].enabled = true;
});
}
/**
* Disables the given snap. A snap can only be started if it is enabled.
*
* @param snapId - The id of the Snap to disable.
* @returns A promise that resolves once the snap has been disabled.
*/
disableSnap(snapId: SnapId): Promise<void> {
if (!this.has(snapId)) {
throw new Error(`Snap "${snapId}" not found.`);
}
this.update((state: any) => {
state.snaps[snapId].enabled = false;
});
if (this.isRunning(snapId)) {
return this.stopSnap(snapId, SnapStatusEvent.stop);
}
return Promise.resolve();
}
/**
* Stops the given snap, removes all hooks, closes all connections, and
* terminates its worker.
*
* @param snapId - The id of the Snap to stop.
* @param statusEvent - The Snap status event that caused the snap to be
* stopped.
*/
public async stopSnap(
snapId: SnapId,
statusEvent:
| SnapStatusEvent.stop
| SnapStatusEvent.crash = SnapStatusEvent.stop,
): Promise<void> {
const runtime = this._getSnapRuntimeData(snapId);
if (!runtime) {
return;
}
// Reset request tracking
runtime.lastRequest = null;
runtime.pendingRequests = 0;
try {
if (this.isRunning(snapId)) {
this._closeAllConnections(snapId);
await this.terminateSnap(snapId);
}
} finally {
if (this.isRunning(snapId)) {
this._transitionSnapState(snapId, statusEvent);
}
}
}
/**
* Terminates the specified snap and emits the `snapTerminated` event.
*
* @param snapId - The snap to terminate.
*/
private async terminateSnap(snapId: SnapId) {
await this.messagingSystem.call('ExecutionService:terminateSnap', snapId);
this.messagingSystem.publish(
'SnapController:snapTerminated',
this.getTruncated(snapId) as TruncatedSnap,
);
}
/**
* Returns whether the given snap is running.
* Throws an error if the snap doesn't exist.
*
* @param snapId - The id of the Snap to check.
* @returns `true` if the snap is running, otherwise `false`.
*/
isRunning(snapId: SnapId): boolean {
const snap = this.get(snapId);
if (!snap) {
throw new Error(`Snap "${snapId}" not found.`);
}
return snap.status === SnapStatus.running;
}
/**
* Returns whether the given snap has been added to state.
*
* @param snapId - The id of the Snap to check for.
* @returns `true` if the snap exists in the controller state, otherwise `false`.
*/
has(snapId: SnapId): boolean {
return Boolean(this.get(snapId));
}
/**
* Gets the snap with the given id if it exists, including all data.
* This should not be used if the snap is to be serializable, as e.g.
* the snap sourceCode may be quite large.
*
* @param snapId - The id of the Snap to get.
* @returns The entire snap object from the controller state.
*/
get(snapId: SnapId): Snap | undefined {
return this.state.snaps[snapId];
}
/**
* Gets the snap with the given id if it exists, excluding any
* non-serializable or expensive-to-serialize data.
*
* @param snapId - The id of the Snap to get.
* @returns A truncated version of the snap state, that is less expensive to serialize.
*/
getTruncated(snapId: SnapId): TruncatedSnap | null {
const snap = this.get(snapId);
return snap
? (Object.keys(snap).reduce((serialized, key) => {
if (TRUNCATED_SNAP_PROPERTIES.has(key as any)) {
serialized[key as keyof TruncatedSnap] = snap[
key as keyof TruncatedSnap
] as any;
}
return serialized;
}, {} as Partial<TruncatedSnap>) as TruncatedSnap)
: null;
}
/**
* Updates the own state of the snap with the given id.
* This is distinct from the state MetaMask uses to manage snaps.
*
* @param snapId - The id of the Snap whose state should be updated.
* @param newSnapState - The new state of the snap.
*/
async updateSnapState(snapId: SnapId, newSnapState: Json): Promise<void> {
const encrypted = await this.encryptSnapState(snapId, newSnapState);
this.update((state: any) => {
state.snapStates[snapId] = encrypted;
});
}
/**
* Clears the state of the snap with the given id.
* This is distinct from the state MetaMask uses to manage snaps.
*
* @param snapId - The id of the Snap whose state should be cleared.
*/
async clearSnapState(snapId: SnapId): Promise<void> {
this.update((state: any) => {
delete state.snapStates[snapId];
});
}
/**
* Adds error from a snap to the SnapController state.
*
* @param snapError - The error to store on the SnapController.
*/
addSnapError(snapError: SnapError): void {
this.update((state: any) => {
const id = nanoid();
state.snapErrors[id] = {
...snapError,
internalID: id,
};
});
}
/**
* Removes an error by internalID from a the SnapControllers state.
*
* @param internalID - The internal error ID to remove on the SnapController.
*/
async removeSnapError(internalID: string) {
this.update((state: any) => {
delete state.snapErrors[internalID];
});
}
/**
* Clears all errors from the SnapControllers state.
*
*/
async clearSnapErrors() {
this.update((state: any) => {
state.snapErrors = {};
});
}
/**
* Gets the own state of the snap with the given id.
* This is distinct from the state MetaMask uses to manage snaps.
*
* @param snapId - The id of the Snap whose state to get.
* @returns A promise that resolves with the decrypted snap state or null if no state exists.
* @throws If the snap state decryption fails.
*/
async getSnapState(snapId: SnapId): Promise<Json> {
const state = this.state.snapStates[snapId];
return state ? this.decryptSnapState(snapId, state) : null;
}