@metamask-previews/sample-controllers 1.0.0-preview-f3f2e8c8 → 1.0.0-preview-8029191

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/index.cjs +5 -4
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +7 -3
  5. package/dist/index.d.cts.map +1 -1
  6. package/dist/index.d.mts +7 -3
  7. package/dist/index.d.mts.map +1 -1
  8. package/dist/index.mjs +3 -3
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/sample-gas-prices-controller-method-action-types.cjs +7 -0
  11. package/dist/sample-gas-prices-controller-method-action-types.cjs.map +1 -0
  12. package/dist/sample-gas-prices-controller-method-action-types.d.cts +21 -0
  13. package/dist/sample-gas-prices-controller-method-action-types.d.cts.map +1 -0
  14. package/dist/sample-gas-prices-controller-method-action-types.d.mts +21 -0
  15. package/dist/sample-gas-prices-controller-method-action-types.d.mts.map +1 -0
  16. package/dist/sample-gas-prices-controller-method-action-types.mjs +6 -0
  17. package/dist/sample-gas-prices-controller-method-action-types.mjs.map +1 -0
  18. package/dist/sample-gas-prices-controller.cjs +83 -41
  19. package/dist/sample-gas-prices-controller.cjs.map +1 -1
  20. package/dist/sample-gas-prices-controller.d.cts +78 -61
  21. package/dist/sample-gas-prices-controller.d.cts.map +1 -1
  22. package/dist/sample-gas-prices-controller.d.mts +78 -61
  23. package/dist/sample-gas-prices-controller.d.mts.map +1 -1
  24. package/dist/sample-gas-prices-controller.mjs +83 -41
  25. package/dist/sample-gas-prices-controller.mjs.map +1 -1
  26. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.cjs +7 -0
  27. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.cjs.map +1 -0
  28. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.d.cts +21 -0
  29. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.d.cts.map +1 -0
  30. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.d.mts +21 -0
  31. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.d.mts.map +1 -0
  32. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.mjs +6 -0
  33. package/dist/sample-gas-prices-service/sample-gas-prices-service-method-action-types.mjs.map +1 -0
  34. package/dist/sample-gas-prices-service/sample-gas-prices-service.cjs +136 -29
  35. package/dist/sample-gas-prices-service/sample-gas-prices-service.cjs.map +1 -1
  36. package/dist/sample-gas-prices-service/sample-gas-prices-service.d.cts +123 -28
  37. package/dist/sample-gas-prices-service/sample-gas-prices-service.d.cts.map +1 -1
  38. package/dist/sample-gas-prices-service/sample-gas-prices-service.d.mts +123 -28
  39. package/dist/sample-gas-prices-service/sample-gas-prices-service.d.mts.map +1 -1
  40. package/dist/sample-gas-prices-service/sample-gas-prices-service.mjs +135 -28
  41. package/dist/sample-gas-prices-service/sample-gas-prices-service.mjs.map +1 -1
  42. package/dist/sample-petnames-controller-method-action-types.cjs +7 -0
  43. package/dist/sample-petnames-controller-method-action-types.cjs.map +1 -0
  44. package/dist/sample-petnames-controller-method-action-types.d.cts +22 -0
  45. package/dist/sample-petnames-controller-method-action-types.d.cts.map +1 -0
  46. package/dist/sample-petnames-controller-method-action-types.d.mts +22 -0
  47. package/dist/sample-petnames-controller-method-action-types.d.mts.map +1 -0
  48. package/dist/sample-petnames-controller-method-action-types.mjs +6 -0
  49. package/dist/sample-petnames-controller-method-action-types.mjs.map +1 -0
  50. package/dist/sample-petnames-controller.cjs +27 -14
  51. package/dist/sample-petnames-controller.cjs.map +1 -1
  52. package/dist/sample-petnames-controller.d.cts +39 -24
  53. package/dist/sample-petnames-controller.d.cts.map +1 -1
  54. package/dist/sample-petnames-controller.d.mts +39 -24
  55. package/dist/sample-petnames-controller.d.mts.map +1 -1
  56. package/dist/sample-petnames-controller.mjs +26 -14
  57. package/dist/sample-petnames-controller.mjs.map +1 -1
  58. package/package.json +4 -3
  59. package/dist/network-controller-types.cjs +0 -20
  60. package/dist/network-controller-types.cjs.map +0 -1
  61. package/dist/network-controller-types.d.cts +0 -34
  62. package/dist/network-controller-types.d.cts.map +0 -1
  63. package/dist/network-controller-types.d.mts +0 -34
  64. package/dist/network-controller-types.d.mts.map +0 -1
  65. package/dist/network-controller-types.mjs +0 -16
  66. package/dist/network-controller-types.mjs.map +0 -1
  67. package/dist/sample-gas-prices-service/index.cjs +0 -6
  68. package/dist/sample-gas-prices-service/index.cjs.map +0 -1
  69. package/dist/sample-gas-prices-service/index.d.cts +0 -3
  70. package/dist/sample-gas-prices-service/index.d.cts.map +0 -1
  71. package/dist/sample-gas-prices-service/index.d.mts +0 -3
  72. package/dist/sample-gas-prices-service/index.d.mts.map +0 -1
  73. package/dist/sample-gas-prices-service/index.mjs +0 -2
  74. package/dist/sample-gas-prices-service/index.mjs.map +0 -1
  75. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.cjs +0 -3
  76. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.cjs.map +0 -1
  77. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.d.cts +0 -7
  78. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.d.cts.map +0 -1
  79. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.d.mts +0 -7
  80. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.d.mts.map +0 -1
  81. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.mjs +0 -2
  82. package/dist/sample-gas-prices-service/sample-abstract-gas-prices-service.mjs.map +0 -1
@@ -1,44 +1,142 @@
1
- import type { Hex } from "@metamask/utils";
1
+ import type { RestrictedMessenger } from "@metamask/base-controller";
2
+ import type { CreateServicePolicyOptions, ServicePolicy } from "@metamask/controller-utils";
3
+ import { type Hex } from "@metamask/utils";
4
+ import type { SampleGasPricesServiceMethodActions } from "./sample-gas-prices-service-method-action-types.mjs";
5
+ /**
6
+ * The name of the {@link SampleGasPricesService}, used to namespace the
7
+ * service's actions and events.
8
+ */
9
+ export declare const serviceName = "SampleGasPricesService";
10
+ /**
11
+ * Actions that {@link SampleGasPricesService} exposes to other consumers.
12
+ */
13
+ export type SampleGasPricesServiceActions = SampleGasPricesServiceMethodActions;
14
+ /**
15
+ * Actions from other messengers that {@link SampleGasPricesMessenger} calls.
16
+ */
17
+ type AllowedActions = never;
18
+ /**
19
+ * Events that {@link SampleGasPricesService} exposes to other consumers.
20
+ */
21
+ export type SampleGasPricesServiceEvents = never;
22
+ /**
23
+ * Events from other messengers that {@link SampleGasPricesService} subscribes
24
+ * to.
25
+ */
26
+ type AllowedEvents = never;
27
+ /**
28
+ * The messenger which is restricted to actions and events accessed by
29
+ * {@link SampleGasPricesService}.
30
+ */
31
+ export type SampleGasPricesServiceMessenger = RestrictedMessenger<typeof serviceName, SampleGasPricesServiceActions | AllowedActions, SampleGasPricesServiceEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
32
+ /**
33
+ * What the API endpoint returns.
34
+ */
35
+ type GasPricesResponse = {
36
+ data: {
37
+ low: number;
38
+ average: number;
39
+ high: number;
40
+ };
41
+ };
2
42
  /**
3
43
  * This service object is responsible for fetching gas prices via an API.
4
44
  *
5
45
  * @example
6
46
  *
7
- * On its own:
8
- *
9
47
  * ``` ts
10
- * const gasPricesService = new SampleGasPricesService({ fetch });
11
- * // Fetch gas prices for Mainnet
12
- * const gasPricesResponse = await gasPricesService.fetchGasPrices('0x1');
13
- * // ... Do something with the response ...
14
- * ```
48
+ * import { Messenger } from '@metamask/base-controller';
49
+ * import type {
50
+ * SampleGasPricesServiceActions,
51
+ * SampleGasPricesServiceEvents,
52
+ * } from '@metamask/sample-controllers';
15
53
  *
16
- * In conjunction with `SampleGasPricesController`:
17
- *
18
- * ``` ts
19
- * const gasPricesService = new SampleGasPricesService({ fetch });
20
- * const gasPricesController = new SampleGasPricesController({
21
- * // ... state, messenger, etc. ...
22
- * gasPricesService,
54
+ * const globalMessenger = new Messenger<
55
+ * SampleGasPricesServiceActions,
56
+ * SampleGasPricesServiceEvents
57
+ * >();
58
+ * const gasPricesServiceMessenger = globalMessenger.getRestricted({
59
+ * name: 'SampleGasPricesService',
60
+ * allowedActions: [],
61
+ * allowedEvents: [],
62
+ * });
63
+ * // Instantiate the service to register its actions on the messenger
64
+ * new SampleGasPricesService({
65
+ * messenger: gasPricesServiceMessenger,
66
+ * fetch,
23
67
  * });
24
- * // This will use the service object internally
25
- * gasPricesController.updateGasPrices();
68
+ *
69
+ * // Later...
70
+ * // Fetch gas prices for Mainnet
71
+ * const gasPrices = await globalMessenger.call(
72
+ * 'SampleGasPricesService:fetchGasPrices',
73
+ * '0x1',
74
+ * );
75
+ * // ... Do something with the gas prices ...
26
76
  * ```
27
77
  */
28
78
  export declare class SampleGasPricesService {
29
79
  #private;
80
+ /**
81
+ * The name of the service.
82
+ */
83
+ readonly name: typeof serviceName;
30
84
  /**
31
85
  * Constructs a new SampleGasPricesService object.
32
86
  *
33
- * @param args - The arguments.
34
- * @param args.fetch - A function that can be used to make an HTTP request.
35
- * If your JavaScript environment supports `fetch` natively, you'll probably
36
- * want to pass that; otherwise you can pass an equivalent (such as `fetch`
37
- * via `node-fetch`).
87
+ * @param args - The constructor arguments.
88
+ * @param args.messenger - The messenger suited for this service.
89
+ * @param args.fetch - A function that can be used to make an HTTP request. If
90
+ * your JavaScript environment supports `fetch` natively, you'll probably want
91
+ * to pass that; otherwise you can pass an equivalent (such as `fetch` via
92
+ * `node-fetch`).
93
+ * @param args.policyOptions - Options to pass to `createServicePolicy`, which
94
+ * is used to wrap each request. See {@link CreateServicePolicyOptions}.
38
95
  */
39
- constructor({ fetch: fetchFunction }: {
96
+ constructor({ messenger, fetch: fetchFunction, policyOptions, }: {
97
+ messenger: SampleGasPricesServiceMessenger;
40
98
  fetch: typeof fetch;
99
+ policyOptions?: CreateServicePolicyOptions;
41
100
  });
101
+ /**
102
+ * Registers a handler that will be called after a request returns a non-500
103
+ * response, causing a retry. Primarily useful in tests where timers are being
104
+ * mocked.
105
+ *
106
+ * @param listener - The handler to be called.
107
+ * @returns An object that can be used to unregister the handler. See
108
+ * {@link CockatielEvent}.
109
+ * @see {@link createServicePolicy}
110
+ */
111
+ onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): import("cockatiel").IDisposable;
112
+ /**
113
+ * Registers a handler that will be called after a set number of retry rounds
114
+ * prove that requests to the API endpoint consistently return a 5xx response.
115
+ *
116
+ * @param listener - The handler to be called.
117
+ * @returns An object that can be used to unregister the handler. See
118
+ * {@link CockatielEvent}.
119
+ * @see {@link createServicePolicy}
120
+ */
121
+ onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): import("cockatiel").IDisposable;
122
+ /**
123
+ * Registers a handler that will be called under one of two circumstances:
124
+ *
125
+ * 1. After a set number of retries prove that requests to the API
126
+ * consistently result in one of the following failures:
127
+ * 1. A connection initiation error
128
+ * 2. A connection reset error
129
+ * 3. A timeout error
130
+ * 4. A non-JSON response
131
+ * 5. A 502, 503, or 504 response
132
+ * 2. After a successful request is made to the API, but the response takes
133
+ * longer than a set duration to return.
134
+ *
135
+ * @param listener - The handler to be called.
136
+ * @returns An object that can be used to unregister the handler. See
137
+ * {@link CockatielEvent}.
138
+ */
139
+ onDegraded(listener: Parameters<ServicePolicy['onDegraded']>[0]): import("cockatiel").IDisposable;
42
140
  /**
43
141
  * Makes a request to the API in order to retrieve gas prices for a particular
44
142
  * chain.
@@ -46,10 +144,7 @@ export declare class SampleGasPricesService {
46
144
  * @param chainId - The chain ID for which you want to fetch gas prices.
47
145
  * @returns The gas prices for the given chain.
48
146
  */
49
- fetchGasPrices(chainId: Hex): Promise<{
50
- low: number;
51
- average: number;
52
- high: number;
53
- }>;
147
+ fetchGasPrices(chainId: Hex): Promise<GasPricesResponse['data']>;
54
148
  }
149
+ export {};
55
150
  //# sourceMappingURL=sample-gas-prices-service.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sample-gas-prices-service.d.mts","sourceRoot":"","sources":["../../src/sample-gas-prices-service/sample-gas-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAa3C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,sBAAsB;;IAGjC;;;;;;;;OAQG;gBACS,EAAE,KAAK,EAAE,aAAa,EAAE,EAAE;QAAE,KAAK,EAAE,OAAO,KAAK,CAAA;KAAE;IAI7D;;;;;;OAMG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG;;;;;CASlC"}
1
+ {"version":3,"file":"sample-gas-prices-service.d.mts","sourceRoot":"","sources":["../../src/sample-gas-prices-service/sample-gas-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,kCAAkC;AACrE,OAAO,KAAK,EACV,0BAA0B,EAC1B,aAAa,EACd,mCAAmC;AAMpC,OAAO,EAA8B,KAAK,GAAG,EAAE,wBAAwB;AAEvE,OAAO,KAAK,EAAE,mCAAmC,EAAE,4DAAwD;AAI3G;;;GAGG;AACH,eAAO,MAAM,WAAW,2BAA2B,CAAC;AAMpD;;GAEG;AACH,MAAM,MAAM,6BAA6B,GAAG,mCAAmC,CAAC;AAEhF;;GAEG;AACH,KAAK,cAAc,GAAG,KAAK,CAAC;AAE5B;;GAEG;AACH,MAAM,MAAM,4BAA4B,GAAG,KAAK,CAAC;AAEjD;;;GAGG;AACH,KAAK,aAAa,GAAG,KAAK,CAAC;AAE3B;;;GAGG;AACH,MAAM,MAAM,+BAA+B,GAAG,mBAAmB,CAC/D,OAAO,WAAW,EAClB,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,GAAG,aAAa,EAC5C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAIF;;GAEG;AACH,KAAK,iBAAiB,GAAG;IACvB,IAAI,EAAE;QACJ,GAAG,EAAE,MAAM,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,EAAE,MAAM,CAAC;KACd,CAAC;CACH,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,qBAAa,sBAAsB;;IACjC;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,OAAO,WAAW,CAAC;IAuBlC;;;;;;;;;;;OAWG;gBACS,EACV,SAAS,EACT,KAAK,EAAE,aAAa,EACpB,aAAkB,GACnB,EAAE;QACD,SAAS,EAAE,+BAA+B,CAAC;QAC3C,KAAK,EAAE,OAAO,KAAK,CAAC;QACpB,aAAa,CAAC,EAAE,0BAA0B,CAAC;KAC5C;IAYD;;;;;;;;;OASG;IACH,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAIzD;;;;;;;;OAQG;IACH,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IAKzD;;;;;;;;;;;;;;;;OAgBG;IAEH,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;IAI/D;;;;;;OAMG;IACG,cAAc,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;CAqCvE"}
@@ -9,46 +9,133 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _SampleGasPricesService_fetch;
12
+ var _a, _SampleGasPricesService_messenger, _SampleGasPricesService_fetch, _SampleGasPricesService_policy;
13
+ import { createServicePolicy, fromHex, HttpError } from "@metamask/controller-utils";
14
+ import { hasProperty, isPlainObject } from "@metamask/utils";
15
+ // === GENERAL ===
16
+ /**
17
+ * The name of the {@link SampleGasPricesService}, used to namespace the
18
+ * service's actions and events.
19
+ */
20
+ export const serviceName = 'SampleGasPricesService';
21
+ // === MESSENGER ===
22
+ const MESSENGER_EXPOSED_METHODS = ['fetchGasPrices'];
13
23
  /**
14
24
  * This service object is responsible for fetching gas prices via an API.
15
25
  *
16
26
  * @example
17
27
  *
18
- * On its own:
19
- *
20
28
  * ``` ts
21
- * const gasPricesService = new SampleGasPricesService({ fetch });
22
- * // Fetch gas prices for Mainnet
23
- * const gasPricesResponse = await gasPricesService.fetchGasPrices('0x1');
24
- * // ... Do something with the response ...
25
- * ```
26
- *
27
- * In conjunction with `SampleGasPricesController`:
29
+ * import { Messenger } from '@metamask/base-controller';
30
+ * import type {
31
+ * SampleGasPricesServiceActions,
32
+ * SampleGasPricesServiceEvents,
33
+ * } from '@metamask/sample-controllers';
28
34
  *
29
- * ``` ts
30
- * const gasPricesService = new SampleGasPricesService({ fetch });
31
- * const gasPricesController = new SampleGasPricesController({
32
- * // ... state, messenger, etc. ...
33
- * gasPricesService,
35
+ * const globalMessenger = new Messenger<
36
+ * SampleGasPricesServiceActions,
37
+ * SampleGasPricesServiceEvents
38
+ * >();
39
+ * const gasPricesServiceMessenger = globalMessenger.getRestricted({
40
+ * name: 'SampleGasPricesService',
41
+ * allowedActions: [],
42
+ * allowedEvents: [],
43
+ * });
44
+ * // Instantiate the service to register its actions on the messenger
45
+ * new SampleGasPricesService({
46
+ * messenger: gasPricesServiceMessenger,
47
+ * fetch,
34
48
  * });
35
- * // This will use the service object internally
36
- * gasPricesController.updateGasPrices();
49
+ *
50
+ * // Later...
51
+ * // Fetch gas prices for Mainnet
52
+ * const gasPrices = await globalMessenger.call(
53
+ * 'SampleGasPricesService:fetchGasPrices',
54
+ * '0x1',
55
+ * );
56
+ * // ... Do something with the gas prices ...
37
57
  * ```
38
58
  */
39
59
  export class SampleGasPricesService {
40
60
  /**
41
61
  * Constructs a new SampleGasPricesService object.
42
62
  *
43
- * @param args - The arguments.
44
- * @param args.fetch - A function that can be used to make an HTTP request.
45
- * If your JavaScript environment supports `fetch` natively, you'll probably
46
- * want to pass that; otherwise you can pass an equivalent (such as `fetch`
47
- * via `node-fetch`).
63
+ * @param args - The constructor arguments.
64
+ * @param args.messenger - The messenger suited for this service.
65
+ * @param args.fetch - A function that can be used to make an HTTP request. If
66
+ * your JavaScript environment supports `fetch` natively, you'll probably want
67
+ * to pass that; otherwise you can pass an equivalent (such as `fetch` via
68
+ * `node-fetch`).
69
+ * @param args.policyOptions - Options to pass to `createServicePolicy`, which
70
+ * is used to wrap each request. See {@link CreateServicePolicyOptions}.
48
71
  */
49
- constructor({ fetch: fetchFunction }) {
72
+ constructor({ messenger, fetch: fetchFunction, policyOptions = {}, }) {
73
+ /**
74
+ * The messenger suited for this service.
75
+ */
76
+ _SampleGasPricesService_messenger.set(this, void 0);
77
+ /**
78
+ * A function that can be used to make an HTTP request.
79
+ */
50
80
  _SampleGasPricesService_fetch.set(this, void 0);
81
+ /**
82
+ * The policy that wraps the request.
83
+ *
84
+ * @see {@link createServicePolicy}
85
+ */
86
+ _SampleGasPricesService_policy.set(this, void 0);
87
+ this.name = serviceName;
88
+ __classPrivateFieldSet(this, _SampleGasPricesService_messenger, messenger, "f");
51
89
  __classPrivateFieldSet(this, _SampleGasPricesService_fetch, fetchFunction, "f");
90
+ __classPrivateFieldSet(this, _SampleGasPricesService_policy, createServicePolicy(policyOptions), "f");
91
+ __classPrivateFieldGet(this, _SampleGasPricesService_messenger, "f").registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
92
+ }
93
+ /**
94
+ * Registers a handler that will be called after a request returns a non-500
95
+ * response, causing a retry. Primarily useful in tests where timers are being
96
+ * mocked.
97
+ *
98
+ * @param listener - The handler to be called.
99
+ * @returns An object that can be used to unregister the handler. See
100
+ * {@link CockatielEvent}.
101
+ * @see {@link createServicePolicy}
102
+ */
103
+ onRetry(listener) {
104
+ return __classPrivateFieldGet(this, _SampleGasPricesService_policy, "f").onRetry(listener);
105
+ }
106
+ /**
107
+ * Registers a handler that will be called after a set number of retry rounds
108
+ * prove that requests to the API endpoint consistently return a 5xx response.
109
+ *
110
+ * @param listener - The handler to be called.
111
+ * @returns An object that can be used to unregister the handler. See
112
+ * {@link CockatielEvent}.
113
+ * @see {@link createServicePolicy}
114
+ */
115
+ onBreak(listener) {
116
+ return __classPrivateFieldGet(this, _SampleGasPricesService_policy, "f").onBreak(listener);
117
+ }
118
+ /* eslint-disable jsdoc/check-indentation */
119
+ /**
120
+ * Registers a handler that will be called under one of two circumstances:
121
+ *
122
+ * 1. After a set number of retries prove that requests to the API
123
+ * consistently result in one of the following failures:
124
+ * 1. A connection initiation error
125
+ * 2. A connection reset error
126
+ * 3. A timeout error
127
+ * 4. A non-JSON response
128
+ * 5. A 502, 503, or 504 response
129
+ * 2. After a successful request is made to the API, but the response takes
130
+ * longer than a set duration to return.
131
+ *
132
+ * @param listener - The handler to be called.
133
+ * @returns An object that can be used to unregister the handler. See
134
+ * {@link CockatielEvent}.
135
+ */
136
+ /* eslint-enable jsdoc/check-indentation */
137
+ onDegraded(listener) {
138
+ return __classPrivateFieldGet(this, _SampleGasPricesService_policy, "f").onDegraded(listener);
52
139
  }
53
140
  /**
54
141
  * Makes a request to the API in order to retrieve gas prices for a particular
@@ -58,11 +145,31 @@ export class SampleGasPricesService {
58
145
  * @returns The gas prices for the given chain.
59
146
  */
60
147
  async fetchGasPrices(chainId) {
61
- const response = await __classPrivateFieldGet(this, _SampleGasPricesService_fetch, "f").call(this, `https://example.com/gas-prices/${chainId}.json`);
62
- // Type assertion: We have to assume the shape of the response data.
63
- const gasPricesResponse = (await response.json());
64
- return gasPricesResponse.data;
148
+ const response = await __classPrivateFieldGet(this, _SampleGasPricesService_policy, "f").execute(async () => {
149
+ const url = new URL('https://api.example.com/gas-prices');
150
+ url.searchParams.append('chainId', `eip155:${fromHex(chainId)}`);
151
+ const localResponse = await __classPrivateFieldGet(this, _SampleGasPricesService_fetch, "f").call(this, url);
152
+ if (!localResponse.ok) {
153
+ throw new HttpError(localResponse.status, `Fetching '${url.toString()}' failed with status '${localResponse.status}'`);
154
+ }
155
+ return localResponse;
156
+ });
157
+ const jsonResponse = await response.json();
158
+ if (isPlainObject(jsonResponse) &&
159
+ hasProperty(jsonResponse, 'data') &&
160
+ isPlainObject(jsonResponse.data) &&
161
+ hasProperty(jsonResponse.data, 'low') &&
162
+ hasProperty(jsonResponse.data, 'average') &&
163
+ hasProperty(jsonResponse.data, 'high')) {
164
+ const { data: { low, average, high }, } = jsonResponse;
165
+ if (typeof low === 'number' &&
166
+ typeof average === 'number' &&
167
+ typeof high === 'number') {
168
+ return { low, average, high };
169
+ }
170
+ }
171
+ throw new Error('Malformed response received from gas prices API');
65
172
  }
66
173
  }
67
- _SampleGasPricesService_fetch = new WeakMap();
174
+ _a = SampleGasPricesService, _SampleGasPricesService_messenger = new WeakMap(), _SampleGasPricesService_fetch = new WeakMap(), _SampleGasPricesService_policy = new WeakMap();
68
175
  //# sourceMappingURL=sample-gas-prices-service.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"sample-gas-prices-service.mjs","sourceRoot":"","sources":["../../src/sample-gas-prices-service/sample-gas-prices-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAaA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,sBAAsB;IAGjC;;;;;;;;OAQG;IACH,YAAY,EAAE,KAAK,EAAE,aAAa,EAA2B;QAXpD,gDAAqB;QAY5B,uBAAA,IAAI,iCAAU,aAAa,MAAA,CAAC;IAC9B,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,cAAc,CAAC,OAAY;QAC/B,MAAM,QAAQ,GAAG,MAAM,uBAAA,IAAI,qCAAO,MAAX,IAAI,EACzB,kCAAkC,OAAO,OAAO,CACjD,CAAC;QACF,oEAAoE;QACpE,MAAM,iBAAiB,GACrB,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAiC,CAAC;QAC1D,OAAO,iBAAiB,CAAC,IAAI,CAAC;IAChC,CAAC;CACF","sourcesContent":["import type { Hex } from '@metamask/utils';\n\n/**\n * What the API endpoint returns.\n */\ntype GasPricesResponse = {\n data: {\n low: number;\n average: number;\n high: number;\n };\n};\n\n/**\n * This service object is responsible for fetching gas prices via an API.\n *\n * @example\n *\n * On its own:\n *\n * ``` ts\n * const gasPricesService = new SampleGasPricesService({ fetch });\n * // Fetch gas prices for Mainnet\n * const gasPricesResponse = await gasPricesService.fetchGasPrices('0x1');\n * // ... Do something with the response ...\n * ```\n *\n * In conjunction with `SampleGasPricesController`:\n *\n * ``` ts\n * const gasPricesService = new SampleGasPricesService({ fetch });\n * const gasPricesController = new SampleGasPricesController({\n * // ... state, messenger, etc. ...\n * gasPricesService,\n * });\n * // This will use the service object internally\n * gasPricesController.updateGasPrices();\n * ```\n */\nexport class SampleGasPricesService {\n readonly #fetch: typeof fetch;\n\n /**\n * Constructs a new SampleGasPricesService object.\n *\n * @param args - The arguments.\n * @param args.fetch - A function that can be used to make an HTTP request.\n * If your JavaScript environment supports `fetch` natively, you'll probably\n * want to pass that; otherwise you can pass an equivalent (such as `fetch`\n * via `node-fetch`).\n */\n constructor({ fetch: fetchFunction }: { fetch: typeof fetch }) {\n this.#fetch = fetchFunction;\n }\n\n /**\n * Makes a request to the API in order to retrieve gas prices for a particular\n * chain.\n *\n * @param chainId - The chain ID for which you want to fetch gas prices.\n * @returns The gas prices for the given chain.\n */\n async fetchGasPrices(chainId: Hex) {\n const response = await this.#fetch(\n `https://example.com/gas-prices/${chainId}.json`,\n );\n // Type assertion: We have to assume the shape of the response data.\n const gasPricesResponse =\n (await response.json()) as unknown as GasPricesResponse;\n return gasPricesResponse.data;\n }\n}\n"]}
1
+ {"version":3,"file":"sample-gas-prices-service.mjs","sourceRoot":"","sources":["../../src/sample-gas-prices-service/sample-gas-prices-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EACL,mBAAmB,EACnB,OAAO,EACP,SAAS,EACV,mCAAmC;AACpC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAY,wBAAwB;AAIvE,kBAAkB;AAElB;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,wBAAwB,CAAC;AAEpD,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG,CAAC,gBAAgB,CAAU,CAAC;AAgD9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,OAAO,sBAAsB;IA2BjC;;;;;;;;;;;OAWG;IACH,YAAY,EACV,SAAS,EACT,KAAK,EAAE,aAAa,EACpB,aAAa,GAAG,EAAE,GAKnB;QAzCD;;WAEG;QACM,oDAES;QAElB;;WAEG;QACM,gDAEK;QAEd;;;;WAIG;QACM,iDAAuB;QAuB9B,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,uBAAA,IAAI,qCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,iCAAU,aAAa,MAAA,CAAC;QAC5B,uBAAA,IAAI,kCAAW,mBAAmB,CAAC,aAAa,CAAC,MAAA,CAAC;QAElD,uBAAA,IAAI,yCAAW,CAAC,4BAA4B,CAC1C,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IAED;;;;;;;;;OASG;IACH,OAAO,CAAC,QAAiD;QACvD,OAAO,uBAAA,IAAI,sCAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IAED;;;;;;;;OAQG;IACH,OAAO,CAAC,QAAiD;QACvD,OAAO,uBAAA,IAAI,sCAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;IACxC,CAAC;IAED,4CAA4C;IAC5C;;;;;;;;;;;;;;;;OAgBG;IACH,2CAA2C;IAC3C,UAAU,CAAC,QAAoD;QAC7D,OAAO,uBAAA,IAAI,sCAAQ,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IAC3C,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,cAAc,CAAC,OAAY;QAC/B,MAAM,QAAQ,GAAG,MAAM,uBAAA,IAAI,sCAAQ,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;YACrD,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,oCAAoC,CAAC,CAAC;YAC1D,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,SAAS,EAAE,UAAU,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YACjE,MAAM,aAAa,GAAG,MAAM,uBAAA,IAAI,qCAAO,MAAX,IAAI,EAAQ,GAAG,CAAC,CAAC;YAC7C,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE;gBACrB,MAAM,IAAI,SAAS,CACjB,aAAa,CAAC,MAAM,EACpB,aAAa,GAAG,CAAC,QAAQ,EAAE,yBAAyB,aAAa,CAAC,MAAM,GAAG,CAC5E,CAAC;aACH;YACD,OAAO,aAAa,CAAC;QACvB,CAAC,CAAC,CAAC;QACH,MAAM,YAAY,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAE3C,IACE,aAAa,CAAC,YAAY,CAAC;YAC3B,WAAW,CAAC,YAAY,EAAE,MAAM,CAAC;YACjC,aAAa,CAAC,YAAY,CAAC,IAAI,CAAC;YAChC,WAAW,CAAC,YAAY,CAAC,IAAI,EAAE,KAAK,CAAC;YACrC,WAAW,CAAC,YAAY,CAAC,IAAI,EAAE,SAAS,CAAC;YACzC,WAAW,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,EACtC;YACA,MAAM,EACJ,IAAI,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,GAC7B,GAAG,YAAY,CAAC;YACjB,IACE,OAAO,GAAG,KAAK,QAAQ;gBACvB,OAAO,OAAO,KAAK,QAAQ;gBAC3B,OAAO,IAAI,KAAK,QAAQ,EACxB;gBACA,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;aAC/B;SACF;QAED,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;CACF","sourcesContent":["import type { RestrictedMessenger } from '@metamask/base-controller';\nimport type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport {\n createServicePolicy,\n fromHex,\n HttpError,\n} from '@metamask/controller-utils';\nimport { hasProperty, isPlainObject, type Hex } from '@metamask/utils';\n\nimport type { SampleGasPricesServiceMethodActions } from './sample-gas-prices-service-method-action-types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link SampleGasPricesService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'SampleGasPricesService';\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchGasPrices'] as const;\n\n/**\n * Actions that {@link SampleGasPricesService} exposes to other consumers.\n */\nexport type SampleGasPricesServiceActions = SampleGasPricesServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link SampleGasPricesMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link SampleGasPricesService} exposes to other consumers.\n */\nexport type SampleGasPricesServiceEvents = never;\n\n/**\n * Events from other messengers that {@link SampleGasPricesService} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link SampleGasPricesService}.\n */\nexport type SampleGasPricesServiceMessenger = RestrictedMessenger<\n typeof serviceName,\n SampleGasPricesServiceActions | AllowedActions,\n SampleGasPricesServiceEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * What the API endpoint returns.\n */\ntype GasPricesResponse = {\n data: {\n low: number;\n average: number;\n high: number;\n };\n};\n\n/**\n * This service object is responsible for fetching gas prices via an API.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/base-controller';\n * import type {\n * SampleGasPricesServiceActions,\n * SampleGasPricesServiceEvents,\n * } from '@metamask/sample-controllers';\n *\n * const globalMessenger = new Messenger<\n * SampleGasPricesServiceActions,\n * SampleGasPricesServiceEvents\n * >();\n * const gasPricesServiceMessenger = globalMessenger.getRestricted({\n * name: 'SampleGasPricesService',\n * allowedActions: [],\n * allowedEvents: [],\n * });\n * // Instantiate the service to register its actions on the messenger\n * new SampleGasPricesService({\n * messenger: gasPricesServiceMessenger,\n * fetch,\n * });\n *\n * // Later...\n * // Fetch gas prices for Mainnet\n * const gasPrices = await globalMessenger.call(\n * 'SampleGasPricesService:fetchGasPrices',\n * '0x1',\n * );\n * // ... Do something with the gas prices ...\n * ```\n */\nexport class SampleGasPricesService {\n /**\n * The name of the service.\n */\n readonly name: typeof serviceName;\n\n /**\n * The messenger suited for this service.\n */\n readonly #messenger: ConstructorParameters<\n typeof SampleGasPricesService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<\n typeof SampleGasPricesService\n >[0]['fetch'];\n\n /**\n * The policy that wraps the request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n /**\n * Constructs a new SampleGasPricesService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.fetch - A function that can be used to make an HTTP request. If\n * your JavaScript environment supports `fetch` natively, you'll probably want\n * to pass that; otherwise you can pass an equivalent (such as `fetch` via\n * `node-fetch`).\n * @param args.policyOptions - Options to pass to `createServicePolicy`, which\n * is used to wrap each request. See {@link CreateServicePolicyOptions}.\n */\n constructor({\n messenger,\n fetch: fetchFunction,\n policyOptions = {},\n }: {\n messenger: SampleGasPricesServiceMessenger;\n fetch: typeof fetch;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n this.name = serviceName;\n this.#messenger = messenger;\n this.#fetch = fetchFunction;\n this.#policy = createServicePolicy(policyOptions);\n\n this.#messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers a handler that will be called after a request returns a non-500\n * response, causing a retry. Primarily useful in tests where timers are being\n * mocked.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]) {\n return this.#policy.onRetry(listener);\n }\n\n /**\n * Registers a handler that will be called after a set number of retry rounds\n * prove that requests to the API endpoint consistently return a 5xx response.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n * @see {@link createServicePolicy}\n */\n onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]) {\n return this.#policy.onBreak(listener);\n }\n\n /* eslint-disable jsdoc/check-indentation */\n /**\n * Registers a handler that will be called under one of two circumstances:\n *\n * 1. After a set number of retries prove that requests to the API\n * consistently result in one of the following failures:\n * 1. A connection initiation error\n * 2. A connection reset error\n * 3. A timeout error\n * 4. A non-JSON response\n * 5. A 502, 503, or 504 response\n * 2. After a successful request is made to the API, but the response takes\n * longer than a set duration to return.\n *\n * @param listener - The handler to be called.\n * @returns An object that can be used to unregister the handler. See\n * {@link CockatielEvent}.\n */\n /* eslint-enable jsdoc/check-indentation */\n onDegraded(listener: Parameters<ServicePolicy['onDegraded']>[0]) {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Makes a request to the API in order to retrieve gas prices for a particular\n * chain.\n *\n * @param chainId - The chain ID for which you want to fetch gas prices.\n * @returns The gas prices for the given chain.\n */\n async fetchGasPrices(chainId: Hex): Promise<GasPricesResponse['data']> {\n const response = await this.#policy.execute(async () => {\n const url = new URL('https://api.example.com/gas-prices');\n url.searchParams.append('chainId', `eip155:${fromHex(chainId)}`);\n const localResponse = await this.#fetch(url);\n if (!localResponse.ok) {\n throw new HttpError(\n localResponse.status,\n `Fetching '${url.toString()}' failed with status '${localResponse.status}'`,\n );\n }\n return localResponse;\n });\n const jsonResponse = await response.json();\n\n if (\n isPlainObject(jsonResponse) &&\n hasProperty(jsonResponse, 'data') &&\n isPlainObject(jsonResponse.data) &&\n hasProperty(jsonResponse.data, 'low') &&\n hasProperty(jsonResponse.data, 'average') &&\n hasProperty(jsonResponse.data, 'high')\n ) {\n const {\n data: { low, average, high },\n } = jsonResponse;\n if (\n typeof low === 'number' &&\n typeof average === 'number' &&\n typeof high === 'number'\n ) {\n return { low, average, high };\n }\n }\n\n throw new Error('Malformed response received from gas prices API');\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /**
3
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
4
+ * Do not edit manually.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ //# sourceMappingURL=sample-petnames-controller-method-action-types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-petnames-controller-method-action-types.cjs","sourceRoot":"","sources":["../src/sample-petnames-controller-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { SamplePetnamesController } from './sample-petnames-controller';\n\n/**\n * Registers the given name with the given address (relative to the given\n * chain).\n *\n * @param chainId - The chain ID that the address belongs to.\n * @param address - The account address to name.\n * @param name - The name to assign to the address.\n */\nexport type SamplePetnamesControllerAssignPetnameAction = {\n type: `SamplePetnamesController:assignPetname`;\n handler: SamplePetnamesController['assignPetname'];\n};\n\n/**\n * Union of all SamplePetnamesController action types.\n */\nexport type SamplePetnamesControllerMethodActions =\n SamplePetnamesControllerAssignPetnameAction;\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
3
+ * Do not edit manually.
4
+ */
5
+ import type { SamplePetnamesController } from "./sample-petnames-controller.cjs";
6
+ /**
7
+ * Registers the given name with the given address (relative to the given
8
+ * chain).
9
+ *
10
+ * @param chainId - The chain ID that the address belongs to.
11
+ * @param address - The account address to name.
12
+ * @param name - The name to assign to the address.
13
+ */
14
+ export type SamplePetnamesControllerAssignPetnameAction = {
15
+ type: `SamplePetnamesController:assignPetname`;
16
+ handler: SamplePetnamesController['assignPetname'];
17
+ };
18
+ /**
19
+ * Union of all SamplePetnamesController action types.
20
+ */
21
+ export type SamplePetnamesControllerMethodActions = SamplePetnamesControllerAssignPetnameAction;
22
+ //# sourceMappingURL=sample-petnames-controller-method-action-types.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-petnames-controller-method-action-types.d.cts","sourceRoot":"","sources":["../src/sample-petnames-controller-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,yCAAqC;AAE7E;;;;;;;GAOG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,wBAAwB,CAAC,eAAe,CAAC,CAAC;CACpD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qCAAqC,GAC/C,2CAA2C,CAAC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
3
+ * Do not edit manually.
4
+ */
5
+ import type { SamplePetnamesController } from "./sample-petnames-controller.mjs";
6
+ /**
7
+ * Registers the given name with the given address (relative to the given
8
+ * chain).
9
+ *
10
+ * @param chainId - The chain ID that the address belongs to.
11
+ * @param address - The account address to name.
12
+ * @param name - The name to assign to the address.
13
+ */
14
+ export type SamplePetnamesControllerAssignPetnameAction = {
15
+ type: `SamplePetnamesController:assignPetname`;
16
+ handler: SamplePetnamesController['assignPetname'];
17
+ };
18
+ /**
19
+ * Union of all SamplePetnamesController action types.
20
+ */
21
+ export type SamplePetnamesControllerMethodActions = SamplePetnamesControllerAssignPetnameAction;
22
+ //# sourceMappingURL=sample-petnames-controller-method-action-types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-petnames-controller-method-action-types.d.mts","sourceRoot":"","sources":["../src/sample-petnames-controller-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,yCAAqC;AAE7E;;;;;;;GAOG;AACH,MAAM,MAAM,2CAA2C,GAAG;IACxD,IAAI,EAAE,wCAAwC,CAAC;IAC/C,OAAO,EAAE,wBAAwB,CAAC,eAAe,CAAC,CAAC;CACpD,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,qCAAqC,GAC/C,2CAA2C,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
3
+ * Do not edit manually.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=sample-petnames-controller-method-action-types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sample-petnames-controller-method-action-types.mjs","sourceRoot":"","sources":["../src/sample-petnames-controller-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated by `scripts/generate-method-action-types.ts`.\n * Do not edit manually.\n */\n\nimport type { SamplePetnamesController } from './sample-petnames-controller';\n\n/**\n * Registers the given name with the given address (relative to the given\n * chain).\n *\n * @param chainId - The chain ID that the address belongs to.\n * @param address - The account address to name.\n * @param name - The name to assign to the address.\n */\nexport type SamplePetnamesControllerAssignPetnameAction = {\n type: `SamplePetnamesController:assignPetname`;\n handler: SamplePetnamesController['assignPetname'];\n};\n\n/**\n * Union of all SamplePetnamesController action types.\n */\nexport type SamplePetnamesControllerMethodActions =\n SamplePetnamesControllerAssignPetnameAction;\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SamplePetnamesController = exports.controllerName = void 0;
3
+ exports.SamplePetnamesController = exports.getDefaultPetnamesControllerState = exports.controllerName = void 0;
4
4
  const base_controller_1 = require("@metamask/base-controller");
5
5
  const controller_utils_1 = require("@metamask/controller-utils");
6
6
  // === GENERAL ===
@@ -15,8 +15,10 @@ exports.controllerName = 'SamplePetnamesController';
15
15
  */
16
16
  const samplePetnamesControllerMetadata = {
17
17
  namesByChainIdAndAddress: {
18
+ includeInStateLogs: true,
18
19
  persist: true,
19
20
  anonymous: false,
21
+ usedInUi: true,
20
22
  },
21
23
  };
22
24
  /**
@@ -32,10 +34,13 @@ function getDefaultPetnamesControllerState() {
32
34
  namesByChainIdAndAddress: {},
33
35
  };
34
36
  }
37
+ exports.getDefaultPetnamesControllerState = getDefaultPetnamesControllerState;
38
+ // === MESSENGER ===
39
+ const MESSENGER_EXPOSED_METHODS = ['assignPetname'];
35
40
  // === CONTROLLER DEFINITION ===
36
41
  /**
37
- * `SamplePetnamesController` records user-provided nicknames for various addresses on
38
- * various chains.
42
+ * `SamplePetnamesController` records user-provided nicknames for various
43
+ * addresses on various chains.
39
44
  *
40
45
  * @example
41
46
  *
@@ -43,28 +48,35 @@ function getDefaultPetnamesControllerState() {
43
48
  * import { Messenger } from '@metamask/base-controller';
44
49
  * import type {
45
50
  * SamplePetnamesControllerActions,
46
- * SamplePetnamesControllerEvents
47
- * } from '@metamask/example-controllers';
51
+ * SamplePetnamesControllerEvents,
52
+ * } from '@metamask/sample-controllers';
48
53
  *
49
- * const rootMessenger = new Messenger<
54
+ * const globalMessenger = new Messenger<
50
55
  * SamplePetnamesControllerActions,
51
56
  * SamplePetnamesControllerEvents
52
57
  * >();
53
- * const samplePetnamesMessenger = rootMessenger.getRestricted({
58
+ * const samplePetnamesMessenger = globalMessenger.getRestricted({
54
59
  * name: 'SamplePetnamesController',
55
60
  * allowedActions: [],
56
61
  * allowedEvents: [],
57
62
  * });
58
- * const samplePetnamesController = new SamplePetnamesController({
63
+ * // Instantiate the controller to register its actions on the messenger
64
+ * new SamplePetnamesController({
59
65
  * messenger: samplePetnamesMessenger,
60
66
  * });
61
67
  *
62
- * samplePetnamesController.assignPetname(
63
- * '0x1',
64
- * '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99',
65
- * 'Primary Account'
68
+ * globalMessenger.call(
69
+ * 'SamplePetnamesController:assignPetname',
70
+ * [
71
+ * '0x1',
72
+ * '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99',
73
+ * 'Primary Account',
74
+ * ],
66
75
  * );
67
- * samplePetnamesController.state.namesByChainIdAndAddress
76
+ * const samplePetnamesControllerState = await globalMessenger.call(
77
+ * 'SamplePetnamesController:getState',
78
+ * );
79
+ * samplePetnamesControllerState.namesByChainIdAndAddress
68
80
  * // => { '0x1': { '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99': 'Primary Account' } }
69
81
  * ```
70
82
  */
@@ -72,7 +84,7 @@ class SamplePetnamesController extends base_controller_1.BaseController {
72
84
  /**
73
85
  * Constructs a new {@link SamplePetnamesController}.
74
86
  *
75
- * @param args - The arguments to the controller.
87
+ * @param args - The arguments to this controller.
76
88
  * @param args.messenger - The messenger suited for this controller.
77
89
  * @param args.state - The desired state with which to initialize this
78
90
  * controller. Missing properties will be filled in with defaults.
@@ -87,6 +99,7 @@ class SamplePetnamesController extends base_controller_1.BaseController {
87
99
  ...state,
88
100
  },
89
101
  });
102
+ this.messagingSystem.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
90
103
  }
91
104
  /**
92
105
  * Registers the given name with the given address (relative to the given
@@ -1 +1 @@
1
- {"version":3,"file":"sample-petnames-controller.cjs","sourceRoot":"","sources":["../src/sample-petnames-controller.ts"],"names":[],"mappings":";;;AAMA,+DAA2D;AAC3D,iEAA8D;AAG9D,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,0BAA0B,CAAC;AAmBzD;;GAEG;AACH,MAAM,gCAAgC,GAAG;IACvC,wBAAwB,EAAE;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;KACjB;CACqD,CAAC;AA0DzD;;;;;;;GAOG;AACH,SAAS,iCAAiC;IACxC,OAAO;QACL,wBAAwB,EAAE,EAAE;KAC7B,CAAC;AACJ,CAAC;AAED,gCAAgC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAa,wBAAyB,SAAQ,gCAI7C;IACC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,GAIN;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE,gCAAgC;YAC1C,IAAI,EAAE,sBAAc;YACpB,KAAK,EAAE;gBACL,GAAG,iCAAiC,EAAE;gBACtC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;OAOG;IACH,aAAa,CAAC,OAAY,EAAE,OAAY,EAAE,IAAY;QACpD,IAAI,CAAC,IAAA,mCAAgB,EAAC,OAAO,CAAC,EAAE;YAC9B,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QAED,MAAM,iBAAiB,GAAG,OAAO,CAAC,WAAW,EAAS,CAAC;QAEvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;;YACpB,MAAA,KAAK,CAAC,wBAAwB,EAAC,OAAO,SAAP,OAAO,IAAM,EAAE,EAAC;YAC/C,KAAK,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAnDD,4DAmDC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { isSafeDynamicKey } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link SamplePetnamesController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'SamplePetnamesController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerState = {\n /**\n * The registry of pet names, categorized by chain ID first and address\n * second.\n */\n namesByChainIdAndAddress: {\n [chainId: Hex]: {\n [address: Hex]: string;\n };\n };\n};\n\n/**\n * The metadata for each property in {@link SamplePetnamesControllerState}.\n */\nconst samplePetnamesControllerMetadata = {\n namesByChainIdAndAddress: {\n persist: true,\n anonymous: false,\n },\n} satisfies StateMetadata<SamplePetnamesControllerState>;\n\n// === MESSENGER ===\n\n/**\n * The action which can be used to retrieve the state of the\n * {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SamplePetnamesControllerState\n>;\n\n/**\n * All actions that {@link SamplePetnamesController} registers, to be called\n * externally.\n */\nexport type SamplePetnamesControllerActions =\n SamplePetnamesControllerGetStateAction;\n\n/**\n * All actions that {@link SamplePetnamesController} calls internally.\n */\ntype AllowedActions = never;\n\n/**\n * The event that {@link SamplePetnamesController} publishes when updating state.\n */\nexport type SamplePetnamesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SamplePetnamesControllerState\n >;\n\n/**\n * All events that {@link SamplePetnamesController} publishes, to be subscribed to\n * externally.\n */\nexport type SamplePetnamesControllerEvents =\n SamplePetnamesControllerStateChangeEvent;\n\n/**\n * All events that {@link SamplePetnamesController} subscribes to internally.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SamplePetnamesControllerActions | AllowedActions,\n SamplePetnamesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Constructs the default {@link SamplePetnamesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link SamplePetnamesController} state.\n */\nfunction getDefaultPetnamesControllerState(): SamplePetnamesControllerState {\n return {\n namesByChainIdAndAddress: {},\n };\n}\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * `SamplePetnamesController` records user-provided nicknames for various addresses on\n * various chains.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/base-controller';\n * import type {\n * SamplePetnamesControllerActions,\n * SamplePetnamesControllerEvents\n * } from '@metamask/example-controllers';\n *\n * const rootMessenger = new Messenger<\n * SamplePetnamesControllerActions,\n * SamplePetnamesControllerEvents\n * >();\n * const samplePetnamesMessenger = rootMessenger.getRestricted({\n * name: 'SamplePetnamesController',\n * allowedActions: [],\n * allowedEvents: [],\n * });\n * const samplePetnamesController = new SamplePetnamesController({\n * messenger: samplePetnamesMessenger,\n * });\n *\n * samplePetnamesController.assignPetname(\n * '0x1',\n * '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99',\n * 'Primary Account'\n * );\n * samplePetnamesController.state.namesByChainIdAndAddress\n * // => { '0x1': { '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99': 'Primary Account' } }\n * ```\n */\nexport class SamplePetnamesController extends BaseController<\n typeof controllerName,\n SamplePetnamesControllerState,\n SamplePetnamesControllerMessenger\n> {\n /**\n * Constructs a new {@link SamplePetnamesController}.\n *\n * @param args - The arguments to the controller.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n */\n constructor({\n messenger,\n state,\n }: {\n messenger: SamplePetnamesControllerMessenger;\n state?: Partial<SamplePetnamesControllerState>;\n }) {\n super({\n messenger,\n metadata: samplePetnamesControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultPetnamesControllerState(),\n ...state,\n },\n });\n }\n\n /**\n * Registers the given name with the given address (relative to the given\n * chain).\n *\n * @param chainId - The chain ID that the address belongs to.\n * @param address - The account address to name.\n * @param name - The name to assign to the address.\n */\n assignPetname(chainId: Hex, address: Hex, name: string) {\n if (!isSafeDynamicKey(chainId)) {\n throw new Error('Invalid chain ID');\n }\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n this.update((state) => {\n state.namesByChainIdAndAddress[chainId] ??= {};\n state.namesByChainIdAndAddress[chainId][normalizedAddress] = name;\n });\n }\n}\n"]}
1
+ {"version":3,"file":"sample-petnames-controller.cjs","sourceRoot":"","sources":["../src/sample-petnames-controller.ts"],"names":[],"mappings":";;;AAMA,+DAA2D;AAC3D,iEAA8D;AAK9D,kBAAkB;AAElB;;;;GAIG;AACU,QAAA,cAAc,GAAG,0BAA0B,CAAC;AAmBzD;;GAEG;AACH,MAAM,gCAAgC,GAAG;IACvC,wBAAwB,EAAE;QACxB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;CACqD,CAAC;AAEzD;;;;;;;GAOG;AACH,SAAgB,iCAAiC;IAC/C,OAAO;QACL,wBAAwB,EAAE,EAAE;KAC7B,CAAC;AACJ,CAAC;AAJD,8EAIC;AAED,oBAAoB;AAEpB,MAAM,yBAAyB,GAAG,CAAC,eAAe,CAAU,CAAC;AAuD7D,gCAAgC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,MAAa,wBAAyB,SAAQ,gCAI7C;IACC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,KAAK,GAIN;QACC,KAAK,CAAC;YACJ,SAAS;YACT,QAAQ,EAAE,gCAAgC;YAC1C,IAAI,EAAE,sBAAc;YACpB,KAAK,EAAE;gBACL,GAAG,iCAAiC,EAAE;gBACtC,GAAG,KAAK;aACT;SACF,CAAC,CAAC;QAEH,IAAI,CAAC,eAAe,CAAC,4BAA4B,CAC/C,IAAI,EACJ,yBAAyB,CAC1B,CAAC;IACJ,CAAC;IAED;;;;;;;OAOG;IACH,aAAa,CAAC,OAAY,EAAE,OAAY,EAAE,IAAY;QACpD,IAAI,CAAC,IAAA,mCAAgB,EAAC,OAAO,CAAC,EAAE;YAC9B,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QAED,MAAM,iBAAiB,GAAG,OAAO,CAAC,WAAW,EAAS,CAAC;QAEvD,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;;YACpB,MAAA,KAAK,CAAC,wBAAwB,EAAC,OAAO,SAAP,OAAO,IAAM,EAAE,EAAC;YAC/C,KAAK,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC,iBAAiB,CAAC,GAAG,IAAI,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxDD,4DAwDC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport { isSafeDynamicKey } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport type { SamplePetnamesControllerMethodActions } from './sample-petnames-controller-method-action-types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link SamplePetnamesController}, used to namespace the\n * controller's actions and events and to namespace the controller's state data\n * when composed with other controllers.\n */\nexport const controllerName = 'SamplePetnamesController';\n\n// === STATE ===\n\n/**\n * Describes the shape of the state object for {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerState = {\n /**\n * The registry of pet names, categorized by chain ID first and address\n * second.\n */\n namesByChainIdAndAddress: {\n [chainId: Hex]: {\n [address: Hex]: string;\n };\n };\n};\n\n/**\n * The metadata for each property in {@link SamplePetnamesControllerState}.\n */\nconst samplePetnamesControllerMetadata = {\n namesByChainIdAndAddress: {\n includeInStateLogs: true,\n persist: true,\n anonymous: false,\n usedInUi: true,\n },\n} satisfies StateMetadata<SamplePetnamesControllerState>;\n\n/**\n * Constructs the default {@link SamplePetnamesController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link SamplePetnamesController} state.\n */\nexport function getDefaultPetnamesControllerState(): SamplePetnamesControllerState {\n return {\n namesByChainIdAndAddress: {},\n };\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['assignPetname'] as const;\n\n/**\n * Retrieves the state of the {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n SamplePetnamesControllerState\n>;\n\n/**\n * Actions that {@link SampleGasPricesMessenger} exposes to other consumers.\n */\nexport type SamplePetnamesControllerActions =\n | SamplePetnamesControllerGetStateAction\n | SamplePetnamesControllerMethodActions;\n\n/**\n * Actions from other messengers that {@link SampleGasPricesMessenger} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Published when the state of {@link SamplePetnamesController} changes.\n */\nexport type SamplePetnamesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SamplePetnamesControllerState\n >;\n\n/**\n * Events that {@link SampleGasPricesMessenger} exposes to other consumers.\n */\nexport type SamplePetnamesControllerEvents =\n SamplePetnamesControllerStateChangeEvent;\n\n/**\n * Events from other messengers that {@link SampleGasPricesMessenger} subscribes\n * to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger restricted to actions and events accessed by\n * {@link SamplePetnamesController}.\n */\nexport type SamplePetnamesControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n SamplePetnamesControllerActions | AllowedActions,\n SamplePetnamesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n// === CONTROLLER DEFINITION ===\n\n/**\n * `SamplePetnamesController` records user-provided nicknames for various\n * addresses on various chains.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/base-controller';\n * import type {\n * SamplePetnamesControllerActions,\n * SamplePetnamesControllerEvents,\n * } from '@metamask/sample-controllers';\n *\n * const globalMessenger = new Messenger<\n * SamplePetnamesControllerActions,\n * SamplePetnamesControllerEvents\n * >();\n * const samplePetnamesMessenger = globalMessenger.getRestricted({\n * name: 'SamplePetnamesController',\n * allowedActions: [],\n * allowedEvents: [],\n * });\n * // Instantiate the controller to register its actions on the messenger\n * new SamplePetnamesController({\n * messenger: samplePetnamesMessenger,\n * });\n *\n * globalMessenger.call(\n * 'SamplePetnamesController:assignPetname',\n * [\n * '0x1',\n * '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99',\n * 'Primary Account',\n * ],\n * );\n * const samplePetnamesControllerState = await globalMessenger.call(\n * 'SamplePetnamesController:getState',\n * );\n * samplePetnamesControllerState.namesByChainIdAndAddress\n * // => { '0x1': { '0xF57F855e17483B1f09bFec62783C9d3b6c8b3A99': 'Primary Account' } }\n * ```\n */\nexport class SamplePetnamesController extends BaseController<\n typeof controllerName,\n SamplePetnamesControllerState,\n SamplePetnamesControllerMessenger\n> {\n /**\n * Constructs a new {@link SamplePetnamesController}.\n *\n * @param args - The arguments to this controller.\n * @param args.messenger - The messenger suited for this controller.\n * @param args.state - The desired state with which to initialize this\n * controller. Missing properties will be filled in with defaults.\n */\n constructor({\n messenger,\n state,\n }: {\n messenger: SamplePetnamesControllerMessenger;\n state?: Partial<SamplePetnamesControllerState>;\n }) {\n super({\n messenger,\n metadata: samplePetnamesControllerMetadata,\n name: controllerName,\n state: {\n ...getDefaultPetnamesControllerState(),\n ...state,\n },\n });\n\n this.messagingSystem.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Registers the given name with the given address (relative to the given\n * chain).\n *\n * @param chainId - The chain ID that the address belongs to.\n * @param address - The account address to name.\n * @param name - The name to assign to the address.\n */\n assignPetname(chainId: Hex, address: Hex, name: string) {\n if (!isSafeDynamicKey(chainId)) {\n throw new Error('Invalid chain ID');\n }\n\n const normalizedAddress = address.toLowerCase() as Hex;\n\n this.update((state) => {\n state.namesByChainIdAndAddress[chainId] ??= {};\n state.namesByChainIdAndAddress[chainId][normalizedAddress] = name;\n });\n }\n}\n"]}