@metamask/ramps-controller 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/OnRampService-method-action-types.cjs +7 -0
  5. package/dist/OnRampService-method-action-types.cjs.map +1 -0
  6. package/dist/OnRampService-method-action-types.d.cts +20 -0
  7. package/dist/OnRampService-method-action-types.d.cts.map +1 -0
  8. package/dist/OnRampService-method-action-types.d.mts +20 -0
  9. package/dist/OnRampService-method-action-types.d.mts.map +1 -0
  10. package/dist/OnRampService-method-action-types.mjs +6 -0
  11. package/dist/OnRampService-method-action-types.mjs.map +1 -0
  12. package/dist/OnRampService.cjs +204 -0
  13. package/dist/OnRampService.cjs.map +1 -0
  14. package/dist/OnRampService.d.cts +152 -0
  15. package/dist/OnRampService.d.cts.map +1 -0
  16. package/dist/OnRampService.d.mts +152 -0
  17. package/dist/OnRampService.d.mts.map +1 -0
  18. package/dist/OnRampService.mjs +200 -0
  19. package/dist/OnRampService.mjs.map +1 -0
  20. package/dist/RampsController.cjs +74 -0
  21. package/dist/RampsController.cjs.map +1 -0
  22. package/dist/RampsController.d.cts +82 -0
  23. package/dist/RampsController.d.cts.map +1 -0
  24. package/dist/RampsController.d.mts +82 -0
  25. package/dist/RampsController.d.mts.map +1 -0
  26. package/dist/RampsController.mjs +69 -0
  27. package/dist/RampsController.mjs.map +1 -0
  28. package/dist/index.cjs +10 -0
  29. package/dist/index.cjs.map +1 -0
  30. package/dist/index.d.cts +6 -0
  31. package/dist/index.d.cts.map +1 -0
  32. package/dist/index.d.mts +6 -0
  33. package/dist/index.d.mts.map +1 -0
  34. package/dist/index.mjs +3 -0
  35. package/dist/index.mjs.map +1 -0
  36. package/package.json +77 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.0.0]
11
+
12
+ ### Added
13
+
14
+ - Initial release ([#7316](https://github.com/MetaMask/core/pull/7316))
15
+ - Add `RampsController` for managing on/off ramps state
16
+ - Add `OnRampService` for interacting with the OnRamp API
17
+ - Add geolocation detection via IP address lookup
18
+
19
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/ramps-controller@1.0.0...HEAD
20
+ [1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/ramps-controller@1.0.0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MetaMask
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # `@metamask/ramps-controller`
2
+
3
+ A controller for managing cryptocurrency on/off ramps functionality.
4
+
5
+ ## Installation
6
+
7
+ `yarn add @metamask/ramps-controller`
8
+
9
+ or
10
+
11
+ `npm install @metamask/ramps-controller`
12
+
13
+ ## Contributing
14
+
15
+ This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme).
@@ -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=OnRampService-method-action-types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService-method-action-types.cjs","sourceRoot":"","sources":["../src/OnRampService-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 { OnRampService } from './OnRampService';\n\n/**\n * Makes a request to the API in order to retrieve the user's geolocation\n * based on their IP address.\n *\n * @returns The user's country/region code (e.g., \"US-UT\" for Utah, USA).\n */\nexport type OnRampServiceGetGeolocationAction = {\n type: `OnRampService:getGeolocation`;\n handler: OnRampService['getGeolocation'];\n};\n\n/**\n * Union of all OnRampService action types.\n */\nexport type OnRampServiceMethodActions = OnRampServiceGetGeolocationAction;\n"]}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
3
+ * Do not edit manually.
4
+ */
5
+ import type { OnRampService } from "./OnRampService.cjs";
6
+ /**
7
+ * Makes a request to the API in order to retrieve the user's geolocation
8
+ * based on their IP address.
9
+ *
10
+ * @returns The user's country/region code (e.g., "US-UT" for Utah, USA).
11
+ */
12
+ export type OnRampServiceGetGeolocationAction = {
13
+ type: `OnRampService:getGeolocation`;
14
+ handler: OnRampService['getGeolocation'];
15
+ };
16
+ /**
17
+ * Union of all OnRampService action types.
18
+ */
19
+ export type OnRampServiceMethodActions = OnRampServiceGetGeolocationAction;
20
+ //# sourceMappingURL=OnRampService-method-action-types.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService-method-action-types.d.cts","sourceRoot":"","sources":["../src/OnRampService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,4BAAwB;AAErD;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;CAC1C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,iCAAiC,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * This file is auto generated by `scripts/generate-method-action-types.ts`.
3
+ * Do not edit manually.
4
+ */
5
+ import type { OnRampService } from "./OnRampService.mjs";
6
+ /**
7
+ * Makes a request to the API in order to retrieve the user's geolocation
8
+ * based on their IP address.
9
+ *
10
+ * @returns The user's country/region code (e.g., "US-UT" for Utah, USA).
11
+ */
12
+ export type OnRampServiceGetGeolocationAction = {
13
+ type: `OnRampService:getGeolocation`;
14
+ handler: OnRampService['getGeolocation'];
15
+ };
16
+ /**
17
+ * Union of all OnRampService action types.
18
+ */
19
+ export type OnRampServiceMethodActions = OnRampServiceGetGeolocationAction;
20
+ //# sourceMappingURL=OnRampService-method-action-types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService-method-action-types.d.mts","sourceRoot":"","sources":["../src/OnRampService-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,4BAAwB;AAErD;;;;;GAKG;AACH,MAAM,MAAM,iCAAiC,GAAG;IAC9C,IAAI,EAAE,8BAA8B,CAAC;IACrC,OAAO,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;CAC1C,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,iCAAiC,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=OnRampService-method-action-types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService-method-action-types.mjs","sourceRoot":"","sources":["../src/OnRampService-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 { OnRampService } from './OnRampService';\n\n/**\n * Makes a request to the API in order to retrieve the user's geolocation\n * based on their IP address.\n *\n * @returns The user's country/region code (e.g., \"US-UT\" for Utah, USA).\n */\nexport type OnRampServiceGetGeolocationAction = {\n type: `OnRampService:getGeolocation`;\n handler: OnRampService['getGeolocation'];\n};\n\n/**\n * Union of all OnRampService action types.\n */\nexport type OnRampServiceMethodActions = OnRampServiceGetGeolocationAction;\n"]}
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ 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");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _a, _OnRampService_messenger, _OnRampService_fetch, _OnRampService_policy, _OnRampService_baseUrl;
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.OnRampService = exports.OnRampEnvironment = exports.serviceName = void 0;
16
+ const controller_utils_1 = require("@metamask/controller-utils");
17
+ // === GENERAL ===
18
+ /**
19
+ * The name of the {@link OnRampService}, used to namespace the
20
+ * service's actions and events.
21
+ */
22
+ exports.serviceName = 'OnRampService';
23
+ /**
24
+ * The environment to use for API requests.
25
+ */
26
+ var OnRampEnvironment;
27
+ (function (OnRampEnvironment) {
28
+ OnRampEnvironment["Production"] = "production";
29
+ OnRampEnvironment["Staging"] = "staging";
30
+ OnRampEnvironment["Development"] = "development";
31
+ })(OnRampEnvironment || (exports.OnRampEnvironment = OnRampEnvironment = {}));
32
+ // === MESSENGER ===
33
+ const MESSENGER_EXPOSED_METHODS = ['getGeolocation'];
34
+ // === SERVICE DEFINITION ===
35
+ /**
36
+ * Gets the base URL for API requests based on the environment.
37
+ *
38
+ * @param environment - The environment to use.
39
+ * @returns The base URL for API requests.
40
+ */
41
+ function getBaseUrl(environment) {
42
+ switch (environment) {
43
+ case OnRampEnvironment.Production:
44
+ return 'https://on-ramp.api.cx.metamask.io';
45
+ case OnRampEnvironment.Staging:
46
+ return 'https://on-ramp.uat-api.cx.metamask.io';
47
+ case OnRampEnvironment.Development:
48
+ return 'http://localhost:3000';
49
+ default:
50
+ throw new Error(`Invalid environment: ${String(environment)}`);
51
+ }
52
+ }
53
+ /**
54
+ * This service object is responsible for interacting with the OnRamp API.
55
+ *
56
+ * @example
57
+ *
58
+ * ``` ts
59
+ * import { Messenger } from '@metamask/messenger';
60
+ * import type {
61
+ * OnRampServiceActions,
62
+ * OnRampServiceEvents,
63
+ * } from '@metamask/ramps-controller';
64
+ *
65
+ * const rootMessenger = new Messenger<
66
+ * 'Root',
67
+ * OnRampServiceActions
68
+ * OnRampServiceEvents
69
+ * >({ namespace: 'Root' });
70
+ * const onRampServiceMessenger = new Messenger<
71
+ * 'OnRampService',
72
+ * OnRampServiceActions,
73
+ * OnRampServiceEvents,
74
+ * typeof rootMessenger,
75
+ * >({
76
+ * namespace: 'OnRampService',
77
+ * parent: rootMessenger,
78
+ * });
79
+ * // Instantiate the service to register its actions on the messenger
80
+ * new OnRampService({
81
+ * messenger: onRampServiceMessenger,
82
+ * environment: OnRampEnvironment.Production,
83
+ * fetch,
84
+ * });
85
+ *
86
+ * // Later...
87
+ * // Get the user's geolocation
88
+ * const geolocation = await rootMessenger.call(
89
+ * 'OnRampService:getGeolocation',
90
+ * );
91
+ * // ... Do something with the geolocation ...
92
+ * ```
93
+ */
94
+ class OnRampService {
95
+ /**
96
+ * Constructs a new OnRampService object.
97
+ *
98
+ * @param args - The constructor arguments.
99
+ * @param args.messenger - The messenger suited for this service.
100
+ * @param args.environment - The environment to use for API requests.
101
+ * @param args.fetch - A function that can be used to make an HTTP request. If
102
+ * your JavaScript environment supports `fetch` natively, you'll probably want
103
+ * to pass that; otherwise you can pass an equivalent (such as `fetch` via
104
+ * `node-fetch`).
105
+ * @param args.policyOptions - Options to pass to `createServicePolicy`, which
106
+ * is used to wrap each request. See {@link CreateServicePolicyOptions}.
107
+ */
108
+ constructor({ messenger, environment = OnRampEnvironment.Staging, fetch: fetchFunction, policyOptions = {}, }) {
109
+ /**
110
+ * The messenger suited for this service.
111
+ */
112
+ _OnRampService_messenger.set(this, void 0);
113
+ /**
114
+ * A function that can be used to make an HTTP request.
115
+ */
116
+ _OnRampService_fetch.set(this, void 0);
117
+ /**
118
+ * The policy that wraps the request.
119
+ *
120
+ * @see {@link createServicePolicy}
121
+ */
122
+ _OnRampService_policy.set(this, void 0);
123
+ /**
124
+ * The base URL for API requests.
125
+ */
126
+ _OnRampService_baseUrl.set(this, void 0);
127
+ this.name = exports.serviceName;
128
+ __classPrivateFieldSet(this, _OnRampService_messenger, messenger, "f");
129
+ __classPrivateFieldSet(this, _OnRampService_fetch, fetchFunction, "f");
130
+ __classPrivateFieldSet(this, _OnRampService_policy, (0, controller_utils_1.createServicePolicy)(policyOptions), "f");
131
+ __classPrivateFieldSet(this, _OnRampService_baseUrl, getBaseUrl(environment), "f");
132
+ __classPrivateFieldGet(this, _OnRampService_messenger, "f").registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
133
+ }
134
+ /**
135
+ * Registers a handler that will be called after a request returns a non-500
136
+ * response, causing a retry. Primarily useful in tests where timers are being
137
+ * mocked.
138
+ *
139
+ * @param listener - The handler to be called.
140
+ * @returns An object that can be used to unregister the handler. See
141
+ * {@link CockatielEvent}.
142
+ * @see {@link createServicePolicy}
143
+ */
144
+ onRetry(listener) {
145
+ return __classPrivateFieldGet(this, _OnRampService_policy, "f").onRetry(listener);
146
+ }
147
+ /**
148
+ * Registers a handler that will be called after a set number of retry rounds
149
+ * prove that requests to the API endpoint consistently return a 5xx response.
150
+ *
151
+ * @param listener - The handler to be called.
152
+ * @returns An object that can be used to unregister the handler. See
153
+ * {@link CockatielEvent}.
154
+ * @see {@link createServicePolicy}
155
+ */
156
+ onBreak(listener) {
157
+ return __classPrivateFieldGet(this, _OnRampService_policy, "f").onBreak(listener);
158
+ }
159
+ /**
160
+ * Registers a handler that will be called under one of two circumstances:
161
+ *
162
+ * 1. After a set number of retries prove that requests to the API
163
+ * consistently result in one of the following failures:
164
+ * 1. A connection initiation error
165
+ * 2. A connection reset error
166
+ * 3. A timeout error
167
+ * 4. A non-JSON response
168
+ * 5. A 502, 503, or 504 response
169
+ * 2. After a successful request is made to the API, but the response takes
170
+ * longer than a set duration to return.
171
+ *
172
+ * @param listener - The handler to be called.
173
+ * @returns An object that can be used to unregister the handler. See
174
+ * {@link CockatielEvent}.
175
+ */
176
+ onDegraded(listener) {
177
+ return __classPrivateFieldGet(this, _OnRampService_policy, "f").onDegraded(listener);
178
+ }
179
+ /**
180
+ * Makes a request to the API in order to retrieve the user's geolocation
181
+ * based on their IP address.
182
+ *
183
+ * @returns The user's country/region code (e.g., "US-UT" for Utah, USA).
184
+ */
185
+ async getGeolocation() {
186
+ const response = await __classPrivateFieldGet(this, _OnRampService_policy, "f").execute(async () => {
187
+ const url = new URL('geolocation', __classPrivateFieldGet(this, _OnRampService_baseUrl, "f"));
188
+ const localResponse = await __classPrivateFieldGet(this, _OnRampService_fetch, "f").call(this, url);
189
+ if (!localResponse.ok) {
190
+ throw new controller_utils_1.HttpError(localResponse.status, `Fetching '${url.toString()}' failed with status '${localResponse.status}'`);
191
+ }
192
+ return localResponse;
193
+ });
194
+ const textResponse = await response.text();
195
+ const trimmedResponse = textResponse.trim();
196
+ if (trimmedResponse.length > 0) {
197
+ return trimmedResponse;
198
+ }
199
+ throw new Error('Malformed response received from geolocation API');
200
+ }
201
+ }
202
+ exports.OnRampService = OnRampService;
203
+ _a = OnRampService, _OnRampService_messenger = new WeakMap(), _OnRampService_fetch = new WeakMap(), _OnRampService_policy = new WeakMap(), _OnRampService_baseUrl = new WeakMap();
204
+ //# sourceMappingURL=OnRampService.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService.cjs","sourceRoot":"","sources":["../src/OnRampService.ts"],"names":[],"mappings":"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","sourcesContent":["import type {\n CreateServicePolicyOptions,\n ServicePolicy,\n} from '@metamask/controller-utils';\nimport { createServicePolicy, HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\n\nimport type { OnRampServiceMethodActions } from './OnRampService-method-action-types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link OnRampService}, used to namespace the\n * service's actions and events.\n */\nexport const serviceName = 'OnRampService';\n\n/**\n * The environment to use for API requests.\n */\nexport enum OnRampEnvironment {\n Production = 'production',\n Staging = 'staging',\n Development = 'development',\n}\n\n// === MESSENGER ===\n\nconst MESSENGER_EXPOSED_METHODS = ['getGeolocation'] as const;\n\n/**\n * Actions that {@link OnRampService} exposes to other consumers.\n */\nexport type OnRampServiceActions = OnRampServiceMethodActions;\n\n/**\n * Actions from other messengers that {@link OnRampService} calls.\n */\ntype AllowedActions = never;\n\n/**\n * Events that {@link OnRampService} exposes to other consumers.\n */\nexport type OnRampServiceEvents = never;\n\n/**\n * Events from other messengers that {@link OnRampService} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link OnRampService}.\n */\nexport type OnRampServiceMessenger = Messenger<\n typeof serviceName,\n OnRampServiceActions | AllowedActions,\n OnRampServiceEvents | AllowedEvents\n>;\n\n// === SERVICE DEFINITION ===\n\n/**\n * Gets the base URL for API requests based on the environment.\n *\n * @param environment - The environment to use.\n * @returns The base URL for API requests.\n */\nfunction getBaseUrl(environment: OnRampEnvironment): string {\n switch (environment) {\n case OnRampEnvironment.Production:\n return 'https://on-ramp.api.cx.metamask.io';\n case OnRampEnvironment.Staging:\n return 'https://on-ramp.uat-api.cx.metamask.io';\n case OnRampEnvironment.Development:\n return 'http://localhost:3000';\n default:\n throw new Error(`Invalid environment: ${String(environment)}`);\n }\n}\n\n/**\n * This service object is responsible for interacting with the OnRamp API.\n *\n * @example\n *\n * ``` ts\n * import { Messenger } from '@metamask/messenger';\n * import type {\n * OnRampServiceActions,\n * OnRampServiceEvents,\n * } from '@metamask/ramps-controller';\n *\n * const rootMessenger = new Messenger<\n * 'Root',\n * OnRampServiceActions\n * OnRampServiceEvents\n * >({ namespace: 'Root' });\n * const onRampServiceMessenger = new Messenger<\n * 'OnRampService',\n * OnRampServiceActions,\n * OnRampServiceEvents,\n * typeof rootMessenger,\n * >({\n * namespace: 'OnRampService',\n * parent: rootMessenger,\n * });\n * // Instantiate the service to register its actions on the messenger\n * new OnRampService({\n * messenger: onRampServiceMessenger,\n * environment: OnRampEnvironment.Production,\n * fetch,\n * });\n *\n * // Later...\n * // Get the user's geolocation\n * const geolocation = await rootMessenger.call(\n * 'OnRampService:getGeolocation',\n * );\n * // ... Do something with the geolocation ...\n * ```\n */\nexport class OnRampService {\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 OnRampService\n >[0]['messenger'];\n\n /**\n * A function that can be used to make an HTTP request.\n */\n readonly #fetch: ConstructorParameters<typeof OnRampService>[0]['fetch'];\n\n /**\n * The policy that wraps the request.\n *\n * @see {@link createServicePolicy}\n */\n readonly #policy: ServicePolicy;\n\n /**\n * The base URL for API requests.\n */\n readonly #baseUrl: string;\n\n /**\n * Constructs a new OnRampService object.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.environment - The environment to use for API requests.\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 environment = OnRampEnvironment.Staging,\n fetch: fetchFunction,\n policyOptions = {},\n }: {\n messenger: OnRampServiceMessenger;\n environment?: OnRampEnvironment;\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 this.#baseUrl = getBaseUrl(environment);\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(\n listener: Parameters<ServicePolicy['onRetry']>[0],\n ): ReturnType<ServicePolicy['onRetry']> {\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(\n listener: Parameters<ServicePolicy['onBreak']>[0],\n ): ReturnType<ServicePolicy['onBreak']> {\n return this.#policy.onBreak(listener);\n }\n\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 onDegraded(\n listener: Parameters<ServicePolicy['onDegraded']>[0],\n ): ReturnType<ServicePolicy['onDegraded']> {\n return this.#policy.onDegraded(listener);\n }\n\n /**\n * Makes a request to the API in order to retrieve the user's geolocation\n * based on their IP address.\n *\n * @returns The user's country/region code (e.g., \"US-UT\" for Utah, USA).\n */\n async getGeolocation(): Promise<string> {\n const response = await this.#policy.execute(async () => {\n const url = new URL('geolocation', this.#baseUrl);\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\n const textResponse = await response.text();\n const trimmedResponse = textResponse.trim();\n\n if (trimmedResponse.length > 0) {\n return trimmedResponse;\n }\n\n throw new Error('Malformed response received from geolocation API');\n }\n}\n"]}
@@ -0,0 +1,152 @@
1
+ import type { CreateServicePolicyOptions, ServicePolicy } from "@metamask/controller-utils";
2
+ import type { Messenger } from "@metamask/messenger";
3
+ import type { OnRampServiceMethodActions } from "./OnRampService-method-action-types.cjs";
4
+ /**
5
+ * The name of the {@link OnRampService}, used to namespace the
6
+ * service's actions and events.
7
+ */
8
+ export declare const serviceName = "OnRampService";
9
+ /**
10
+ * The environment to use for API requests.
11
+ */
12
+ export declare enum OnRampEnvironment {
13
+ Production = "production",
14
+ Staging = "staging",
15
+ Development = "development"
16
+ }
17
+ /**
18
+ * Actions that {@link OnRampService} exposes to other consumers.
19
+ */
20
+ export type OnRampServiceActions = OnRampServiceMethodActions;
21
+ /**
22
+ * Actions from other messengers that {@link OnRampService} calls.
23
+ */
24
+ type AllowedActions = never;
25
+ /**
26
+ * Events that {@link OnRampService} exposes to other consumers.
27
+ */
28
+ export type OnRampServiceEvents = never;
29
+ /**
30
+ * Events from other messengers that {@link OnRampService} subscribes to.
31
+ */
32
+ type AllowedEvents = never;
33
+ /**
34
+ * The messenger which is restricted to actions and events accessed by
35
+ * {@link OnRampService}.
36
+ */
37
+ export type OnRampServiceMessenger = Messenger<typeof serviceName, OnRampServiceActions | AllowedActions, OnRampServiceEvents | AllowedEvents>;
38
+ /**
39
+ * This service object is responsible for interacting with the OnRamp API.
40
+ *
41
+ * @example
42
+ *
43
+ * ``` ts
44
+ * import { Messenger } from '@metamask/messenger';
45
+ * import type {
46
+ * OnRampServiceActions,
47
+ * OnRampServiceEvents,
48
+ * } from '@metamask/ramps-controller';
49
+ *
50
+ * const rootMessenger = new Messenger<
51
+ * 'Root',
52
+ * OnRampServiceActions
53
+ * OnRampServiceEvents
54
+ * >({ namespace: 'Root' });
55
+ * const onRampServiceMessenger = new Messenger<
56
+ * 'OnRampService',
57
+ * OnRampServiceActions,
58
+ * OnRampServiceEvents,
59
+ * typeof rootMessenger,
60
+ * >({
61
+ * namespace: 'OnRampService',
62
+ * parent: rootMessenger,
63
+ * });
64
+ * // Instantiate the service to register its actions on the messenger
65
+ * new OnRampService({
66
+ * messenger: onRampServiceMessenger,
67
+ * environment: OnRampEnvironment.Production,
68
+ * fetch,
69
+ * });
70
+ *
71
+ * // Later...
72
+ * // Get the user's geolocation
73
+ * const geolocation = await rootMessenger.call(
74
+ * 'OnRampService:getGeolocation',
75
+ * );
76
+ * // ... Do something with the geolocation ...
77
+ * ```
78
+ */
79
+ export declare class OnRampService {
80
+ #private;
81
+ /**
82
+ * The name of the service.
83
+ */
84
+ readonly name: typeof serviceName;
85
+ /**
86
+ * Constructs a new OnRampService object.
87
+ *
88
+ * @param args - The constructor arguments.
89
+ * @param args.messenger - The messenger suited for this service.
90
+ * @param args.environment - The environment to use for API requests.
91
+ * @param args.fetch - A function that can be used to make an HTTP request. If
92
+ * your JavaScript environment supports `fetch` natively, you'll probably want
93
+ * to pass that; otherwise you can pass an equivalent (such as `fetch` via
94
+ * `node-fetch`).
95
+ * @param args.policyOptions - Options to pass to `createServicePolicy`, which
96
+ * is used to wrap each request. See {@link CreateServicePolicyOptions}.
97
+ */
98
+ constructor({ messenger, environment, fetch: fetchFunction, policyOptions, }: {
99
+ messenger: OnRampServiceMessenger;
100
+ environment?: OnRampEnvironment;
101
+ fetch: typeof fetch;
102
+ policyOptions?: CreateServicePolicyOptions;
103
+ });
104
+ /**
105
+ * Registers a handler that will be called after a request returns a non-500
106
+ * response, causing a retry. Primarily useful in tests where timers are being
107
+ * mocked.
108
+ *
109
+ * @param listener - The handler to be called.
110
+ * @returns An object that can be used to unregister the handler. See
111
+ * {@link CockatielEvent}.
112
+ * @see {@link createServicePolicy}
113
+ */
114
+ onRetry(listener: Parameters<ServicePolicy['onRetry']>[0]): ReturnType<ServicePolicy['onRetry']>;
115
+ /**
116
+ * Registers a handler that will be called after a set number of retry rounds
117
+ * prove that requests to the API endpoint consistently return a 5xx response.
118
+ *
119
+ * @param listener - The handler to be called.
120
+ * @returns An object that can be used to unregister the handler. See
121
+ * {@link CockatielEvent}.
122
+ * @see {@link createServicePolicy}
123
+ */
124
+ onBreak(listener: Parameters<ServicePolicy['onBreak']>[0]): ReturnType<ServicePolicy['onBreak']>;
125
+ /**
126
+ * Registers a handler that will be called under one of two circumstances:
127
+ *
128
+ * 1. After a set number of retries prove that requests to the API
129
+ * consistently result in one of the following failures:
130
+ * 1. A connection initiation error
131
+ * 2. A connection reset error
132
+ * 3. A timeout error
133
+ * 4. A non-JSON response
134
+ * 5. A 502, 503, or 504 response
135
+ * 2. After a successful request is made to the API, but the response takes
136
+ * longer than a set duration to return.
137
+ *
138
+ * @param listener - The handler to be called.
139
+ * @returns An object that can be used to unregister the handler. See
140
+ * {@link CockatielEvent}.
141
+ */
142
+ onDegraded(listener: Parameters<ServicePolicy['onDegraded']>[0]): ReturnType<ServicePolicy['onDegraded']>;
143
+ /**
144
+ * Makes a request to the API in order to retrieve the user's geolocation
145
+ * based on their IP address.
146
+ *
147
+ * @returns The user's country/region code (e.g., "US-UT" for Utah, USA).
148
+ */
149
+ getGeolocation(): Promise<string>;
150
+ }
151
+ export {};
152
+ //# sourceMappingURL=OnRampService.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OnRampService.d.cts","sourceRoot":"","sources":["../src/OnRampService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,0BAA0B,EAC1B,aAAa,EACd,mCAAmC;AAEpC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,0BAA0B,EAAE,gDAA4C;AAItF;;;GAGG;AACH,eAAO,MAAM,WAAW,kBAAkB,CAAC;AAE3C;;GAEG;AACH,oBAAY,iBAAiB;IAC3B,UAAU,eAAe;IACzB,OAAO,YAAY;IACnB,WAAW,gBAAgB;CAC5B;AAMD;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG,0BAA0B,CAAC;AAE9D;;GAEG;AACH,KAAK,cAAc,GAAG,KAAK,CAAC;AAE5B;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,KAAK,CAAC;AAExC;;GAEG;AACH,KAAK,aAAa,GAAG,KAAK,CAAC;AAE3B;;;GAGG;AACH,MAAM,MAAM,sBAAsB,GAAG,SAAS,CAC5C,OAAO,WAAW,EAClB,oBAAoB,GAAG,cAAc,EACrC,mBAAmB,GAAG,aAAa,CACpC,CAAC;AAuBF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AACH,qBAAa,aAAa;;IACxB;;OAEG;IACH,QAAQ,CAAC,IAAI,EAAE,OAAO,WAAW,CAAC;IA0BlC;;;;;;;;;;;;OAYG;gBACS,EACV,SAAS,EACT,WAAuC,EACvC,KAAK,EAAE,aAAa,EACpB,aAAkB,GACnB,EAAE;QACD,SAAS,EAAE,sBAAsB,CAAC;QAClC,WAAW,CAAC,EAAE,iBAAiB,CAAC;QAChC,KAAK,EAAE,OAAO,KAAK,CAAC;QACpB,aAAa,CAAC,EAAE,0BAA0B,CAAC;KAC5C;IAaD;;;;;;;;;OASG;IACH,OAAO,CACL,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,GAChD,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IAIvC;;;;;;;;OAQG;IACH,OAAO,CACL,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,GAChD,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IAIvC;;;;;;;;;;;;;;;;OAgBG;IACH,UAAU,CACR,QAAQ,EAAE,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,GACnD,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;IAI1C;;;;;OAKG;IACG,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC;CAsBxC"}