@metamask-previews/chomp-api-service 0.0.0-preview-08b3d87

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 +14 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/chomp-api-service-method-action-types.cjs +7 -0
  5. package/dist/chomp-api-service-method-action-types.cjs.map +1 -0
  6. package/dist/chomp-api-service-method-action-types.d.cts +59 -0
  7. package/dist/chomp-api-service-method-action-types.d.cts.map +1 -0
  8. package/dist/chomp-api-service-method-action-types.d.mts +59 -0
  9. package/dist/chomp-api-service-method-action-types.d.mts.map +1 -0
  10. package/dist/chomp-api-service-method-action-types.mjs +6 -0
  11. package/dist/chomp-api-service-method-action-types.mjs.map +1 -0
  12. package/dist/chomp-api-service.cjs +315 -0
  13. package/dist/chomp-api-service.cjs.map +1 -0
  14. package/dist/chomp-api-service.d.cts +139 -0
  15. package/dist/chomp-api-service.d.cts.map +1 -0
  16. package/dist/chomp-api-service.d.mts +139 -0
  17. package/dist/chomp-api-service.d.mts.map +1 -0
  18. package/dist/chomp-api-service.mjs +311 -0
  19. package/dist/chomp-api-service.mjs.map +1 -0
  20. package/dist/index.cjs +6 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +5 -0
  23. package/dist/index.d.cts.map +1 -0
  24. package/dist/index.d.mts +5 -0
  25. package/dist/index.d.mts.map +1 -0
  26. package/dist/index.mjs +2 -0
  27. package/dist/index.mjs.map +1 -0
  28. package/dist/types.cjs +3 -0
  29. package/dist/types.cjs.map +1 -0
  30. package/dist/types.d.cts +98 -0
  31. package/dist/types.d.cts.map +1 -0
  32. package/dist/types.d.mts +98 -0
  33. package/dist/types.d.mts.map +1 -0
  34. package/dist/types.mjs +2 -0
  35. package/dist/types.mjs.map +1 -0
  36. package/package.json +77 -0
@@ -0,0 +1,139 @@
1
+ import { BaseDataService } from "@metamask/base-data-service";
2
+ import type { DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction } from "@metamask/base-data-service";
3
+ import type { CreateServicePolicyOptions } from "@metamask/controller-utils";
4
+ import type { Messenger } from "@metamask/messenger";
5
+ import type { AuthenticationControllerGetBearerTokenAction } from "@metamask/profile-sync-controller/auth";
6
+ import type { QueryClientConfig } from "@tanstack/query-core";
7
+ import type { ChompApiServiceMethodActions } from "./chomp-api-service-method-action-types.cjs";
8
+ import type { AssociateAddressRequest, AssociateAddressResponse, CreateUpgradeRequest, UpgradeResponse, CreateWithdrawalRequest, CreateWithdrawalResponse, IntentEntry, SendIntentRequest, SendIntentResponse, VerifyDelegationRequest, VerifyDelegationResponse } from "./types.cjs";
9
+ /**
10
+ * The name of the {@link ChompApiService}, used to namespace the service's
11
+ * actions and events.
12
+ */
13
+ export declare const serviceName = "ChompApiService";
14
+ /**
15
+ * Invalidates cached queries for {@link ChompApiService}.
16
+ */
17
+ export type ChompApiServiceInvalidateQueriesAction = DataServiceInvalidateQueriesAction<typeof serviceName>;
18
+ /**
19
+ * Actions that {@link ChompApiService} exposes to other consumers.
20
+ */
21
+ export type ChompApiServiceActions = ChompApiServiceMethodActions | ChompApiServiceInvalidateQueriesAction;
22
+ /**
23
+ * Actions from other messengers that {@link ChompApiService} calls.
24
+ */
25
+ type AllowedActions = AuthenticationControllerGetBearerTokenAction;
26
+ /**
27
+ * Published when {@link ChompApiService}'s cache is updated.
28
+ */
29
+ export type ChompApiServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<typeof serviceName>;
30
+ /**
31
+ * Published when a key within {@link ChompApiService}'s cache is updated.
32
+ */
33
+ export type ChompApiServiceGranularCacheUpdatedEvent = DataServiceGranularCacheUpdatedEvent<typeof serviceName>;
34
+ /**
35
+ * Events that {@link ChompApiService} exposes to other consumers.
36
+ */
37
+ export type ChompApiServiceEvents = ChompApiServiceCacheUpdatedEvent | ChompApiServiceGranularCacheUpdatedEvent;
38
+ /**
39
+ * Events from other messengers that {@link ChompApiService} subscribes to.
40
+ */
41
+ type AllowedEvents = never;
42
+ /**
43
+ * The messenger which is restricted to actions and events accessed by
44
+ * {@link ChompApiService}.
45
+ */
46
+ export type ChompApiServiceMessenger = Messenger<typeof serviceName, ChompApiServiceActions | AllowedActions, ChompApiServiceEvents | AllowedEvents>;
47
+ /**
48
+ * This service is responsible for communicating with the CHOMP API.
49
+ *
50
+ * All requests are authenticated via JWT Bearer tokens obtained from the
51
+ * {@link AuthenticationControllerGetBearerTokenAction} messenger action.
52
+ */
53
+ export declare class ChompApiService extends BaseDataService<typeof serviceName, ChompApiServiceMessenger> {
54
+ #private;
55
+ /**
56
+ * Constructs a new ChompApiService.
57
+ *
58
+ * @param args - The constructor arguments.
59
+ * @param args.messenger - The messenger suited for this service.
60
+ * @param args.baseUrl - The base URL of the CHOMP API.
61
+ * @param args.queryClientConfig - Configuration for the underlying TanStack
62
+ * Query client.
63
+ * @param args.policyOptions - Options to pass to `createServicePolicy`.
64
+ */
65
+ constructor({ messenger, baseUrl, queryClientConfig, policyOptions, }: {
66
+ messenger: ChompApiServiceMessenger;
67
+ baseUrl: string;
68
+ queryClientConfig?: QueryClientConfig;
69
+ policyOptions?: CreateServicePolicyOptions;
70
+ });
71
+ /**
72
+ * Associates an address with a CHOMP profile.
73
+ *
74
+ * POST /v1/auth/address
75
+ *
76
+ * @param request - The association request containing signature, timestamp,
77
+ * and address.
78
+ * @returns The profile association result. Returns on both 201 and 409.
79
+ */
80
+ associateAddress(request: AssociateAddressRequest): Promise<AssociateAddressResponse>;
81
+ /**
82
+ * Creates an account upgrade request.
83
+ *
84
+ * POST /v1/account-upgrade
85
+ *
86
+ * @param request - The upgrade request containing signature components and
87
+ * chain details.
88
+ * @returns The upgrade result.
89
+ */
90
+ createUpgrade(request: CreateUpgradeRequest): Promise<UpgradeResponse>;
91
+ /**
92
+ * Fetches the upgrade record for a given address.
93
+ *
94
+ * GET /v1/account-upgrade/:address
95
+ *
96
+ * @param address - The address to look up.
97
+ * @returns The upgrade record, or null if not found.
98
+ */
99
+ getUpgrade(address: string): Promise<UpgradeResponse | null>;
100
+ /**
101
+ * Verifies a delegation signature.
102
+ *
103
+ * POST /v1/intent/verify-delegation
104
+ *
105
+ * @param request - The delegation verification request.
106
+ * @returns The verification result including validity and optional errors.
107
+ */
108
+ verifyDelegation(request: VerifyDelegationRequest): Promise<VerifyDelegationResponse>;
109
+ /**
110
+ * Submits one or more intents to the CHOMP API.
111
+ *
112
+ * POST /v1/intent
113
+ *
114
+ * @param intents - The array of intents to submit.
115
+ * @returns The array of intent responses.
116
+ */
117
+ createIntents(intents: SendIntentRequest[]): Promise<SendIntentResponse[]>;
118
+ /**
119
+ * Fetches intents associated with a given address.
120
+ *
121
+ * GET /v1/intent/account/:address
122
+ *
123
+ * @param address - The address to look up intents for.
124
+ * @returns The array of intents for the address.
125
+ */
126
+ getIntentsByAddress(address: string): Promise<IntentEntry[]>;
127
+ /**
128
+ * Creates a withdrawal for card spend flows.
129
+ *
130
+ * POST /v1/withdrawal
131
+ *
132
+ * @param request - The withdrawal request containing chainId, amount
133
+ * (decimal or hex string), and account address.
134
+ * @returns The withdrawal result.
135
+ */
136
+ createWithdrawal(request: CreateWithdrawalRequest): Promise<CreateWithdrawalResponse>;
137
+ }
138
+ export {};
139
+ //# sourceMappingURL=chomp-api-service.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chomp-api-service.d.cts","sourceRoot":"","sources":["../src/chomp-api-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,4CAA4C,EAAE,+CAA+C;AAa3G,OAAO,KAAK,EAAE,iBAAiB,EA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CAAC,EAAE,0BAA0B,CAAC;KAC5C;IA+BD;;;;;;;;OAQG;IACG,gBAAgB,CACpB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;IA6BpC;;;;;;;;OAQG;IACG,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,eAAe,CAAC;IA6B5E;;;;;;;OAOG;IACG,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAgClE;;;;;;;OAOG;IACG,gBAAgB,CACpB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;IA6BpC;;;;;;;OAOG;IACG,aAAa,CACjB,OAAO,EAAE,iBAAiB,EAAE,GAC3B,OAAO,CAAC,kBAAkB,EAAE,CAAC;IA6BhC;;;;;;;OAOG;IACG,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAwBlE;;;;;;;;OAQG;IACG,gBAAgB,CACpB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;CAyBrC"}
@@ -0,0 +1,139 @@
1
+ import { BaseDataService } from "@metamask/base-data-service";
2
+ import type { DataServiceCacheUpdatedEvent, DataServiceGranularCacheUpdatedEvent, DataServiceInvalidateQueriesAction } from "@metamask/base-data-service";
3
+ import type { CreateServicePolicyOptions } from "@metamask/controller-utils";
4
+ import type { Messenger } from "@metamask/messenger";
5
+ import type { AuthenticationControllerGetBearerTokenAction } from "@metamask/profile-sync-controller/auth";
6
+ import type { QueryClientConfig } from "@tanstack/query-core";
7
+ import type { ChompApiServiceMethodActions } from "./chomp-api-service-method-action-types.mjs";
8
+ import type { AssociateAddressRequest, AssociateAddressResponse, CreateUpgradeRequest, UpgradeResponse, CreateWithdrawalRequest, CreateWithdrawalResponse, IntentEntry, SendIntentRequest, SendIntentResponse, VerifyDelegationRequest, VerifyDelegationResponse } from "./types.mjs";
9
+ /**
10
+ * The name of the {@link ChompApiService}, used to namespace the service's
11
+ * actions and events.
12
+ */
13
+ export declare const serviceName = "ChompApiService";
14
+ /**
15
+ * Invalidates cached queries for {@link ChompApiService}.
16
+ */
17
+ export type ChompApiServiceInvalidateQueriesAction = DataServiceInvalidateQueriesAction<typeof serviceName>;
18
+ /**
19
+ * Actions that {@link ChompApiService} exposes to other consumers.
20
+ */
21
+ export type ChompApiServiceActions = ChompApiServiceMethodActions | ChompApiServiceInvalidateQueriesAction;
22
+ /**
23
+ * Actions from other messengers that {@link ChompApiService} calls.
24
+ */
25
+ type AllowedActions = AuthenticationControllerGetBearerTokenAction;
26
+ /**
27
+ * Published when {@link ChompApiService}'s cache is updated.
28
+ */
29
+ export type ChompApiServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<typeof serviceName>;
30
+ /**
31
+ * Published when a key within {@link ChompApiService}'s cache is updated.
32
+ */
33
+ export type ChompApiServiceGranularCacheUpdatedEvent = DataServiceGranularCacheUpdatedEvent<typeof serviceName>;
34
+ /**
35
+ * Events that {@link ChompApiService} exposes to other consumers.
36
+ */
37
+ export type ChompApiServiceEvents = ChompApiServiceCacheUpdatedEvent | ChompApiServiceGranularCacheUpdatedEvent;
38
+ /**
39
+ * Events from other messengers that {@link ChompApiService} subscribes to.
40
+ */
41
+ type AllowedEvents = never;
42
+ /**
43
+ * The messenger which is restricted to actions and events accessed by
44
+ * {@link ChompApiService}.
45
+ */
46
+ export type ChompApiServiceMessenger = Messenger<typeof serviceName, ChompApiServiceActions | AllowedActions, ChompApiServiceEvents | AllowedEvents>;
47
+ /**
48
+ * This service is responsible for communicating with the CHOMP API.
49
+ *
50
+ * All requests are authenticated via JWT Bearer tokens obtained from the
51
+ * {@link AuthenticationControllerGetBearerTokenAction} messenger action.
52
+ */
53
+ export declare class ChompApiService extends BaseDataService<typeof serviceName, ChompApiServiceMessenger> {
54
+ #private;
55
+ /**
56
+ * Constructs a new ChompApiService.
57
+ *
58
+ * @param args - The constructor arguments.
59
+ * @param args.messenger - The messenger suited for this service.
60
+ * @param args.baseUrl - The base URL of the CHOMP API.
61
+ * @param args.queryClientConfig - Configuration for the underlying TanStack
62
+ * Query client.
63
+ * @param args.policyOptions - Options to pass to `createServicePolicy`.
64
+ */
65
+ constructor({ messenger, baseUrl, queryClientConfig, policyOptions, }: {
66
+ messenger: ChompApiServiceMessenger;
67
+ baseUrl: string;
68
+ queryClientConfig?: QueryClientConfig;
69
+ policyOptions?: CreateServicePolicyOptions;
70
+ });
71
+ /**
72
+ * Associates an address with a CHOMP profile.
73
+ *
74
+ * POST /v1/auth/address
75
+ *
76
+ * @param request - The association request containing signature, timestamp,
77
+ * and address.
78
+ * @returns The profile association result. Returns on both 201 and 409.
79
+ */
80
+ associateAddress(request: AssociateAddressRequest): Promise<AssociateAddressResponse>;
81
+ /**
82
+ * Creates an account upgrade request.
83
+ *
84
+ * POST /v1/account-upgrade
85
+ *
86
+ * @param request - The upgrade request containing signature components and
87
+ * chain details.
88
+ * @returns The upgrade result.
89
+ */
90
+ createUpgrade(request: CreateUpgradeRequest): Promise<UpgradeResponse>;
91
+ /**
92
+ * Fetches the upgrade record for a given address.
93
+ *
94
+ * GET /v1/account-upgrade/:address
95
+ *
96
+ * @param address - The address to look up.
97
+ * @returns The upgrade record, or null if not found.
98
+ */
99
+ getUpgrade(address: string): Promise<UpgradeResponse | null>;
100
+ /**
101
+ * Verifies a delegation signature.
102
+ *
103
+ * POST /v1/intent/verify-delegation
104
+ *
105
+ * @param request - The delegation verification request.
106
+ * @returns The verification result including validity and optional errors.
107
+ */
108
+ verifyDelegation(request: VerifyDelegationRequest): Promise<VerifyDelegationResponse>;
109
+ /**
110
+ * Submits one or more intents to the CHOMP API.
111
+ *
112
+ * POST /v1/intent
113
+ *
114
+ * @param intents - The array of intents to submit.
115
+ * @returns The array of intent responses.
116
+ */
117
+ createIntents(intents: SendIntentRequest[]): Promise<SendIntentResponse[]>;
118
+ /**
119
+ * Fetches intents associated with a given address.
120
+ *
121
+ * GET /v1/intent/account/:address
122
+ *
123
+ * @param address - The address to look up intents for.
124
+ * @returns The array of intents for the address.
125
+ */
126
+ getIntentsByAddress(address: string): Promise<IntentEntry[]>;
127
+ /**
128
+ * Creates a withdrawal for card spend flows.
129
+ *
130
+ * POST /v1/withdrawal
131
+ *
132
+ * @param request - The withdrawal request containing chainId, amount
133
+ * (decimal or hex string), and account address.
134
+ * @returns The withdrawal result.
135
+ */
136
+ createWithdrawal(request: CreateWithdrawalRequest): Promise<CreateWithdrawalResponse>;
137
+ }
138
+ export {};
139
+ //# sourceMappingURL=chomp-api-service.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chomp-api-service.d.mts","sourceRoot":"","sources":["../src/chomp-api-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAC9D,OAAO,KAAK,EACV,4BAA4B,EAC5B,oCAAoC,EACpC,kCAAkC,EACnC,oCAAoC;AACrC,OAAO,KAAK,EAAE,0BAA0B,EAAE,mCAAmC;AAE7E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,4CAA4C,EAAE,+CAA+C;AAa3G,OAAO,KAAK,EAAE,iBAAiB,EAAE,6BAA6B;AAE9D,OAAO,KAAK,EAAE,4BAA4B,EAAE,oDAAgD;AAC5F,OAAO,KAAK,EACV,uBAAuB,EACvB,wBAAwB,EACxB,oBAAoB,EACpB,eAAe,EACf,uBAAuB,EACvB,wBAAwB,EACxB,WAAW,EACX,iBAAiB,EACjB,kBAAkB,EAClB,uBAAuB,EACvB,wBAAwB,EACzB,oBAAgB;AAIjB;;;GAGG;AACH,eAAO,MAAM,WAAW,oBAAoB,CAAC;AAkB7C;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAChD,kCAAkC,CAAC,OAAO,WAAW,CAAC,CAAC;AAEzD;;GAEG;AACH,MAAM,MAAM,sBAAsB,GAC9B,4BAA4B,GAC5B,sCAAsC,C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,EAAE,iBAAiB,EAAE,GAC3B,OAAO,CAAC,kBAAkB,EAAE,CAAC;IA6BhC;;;;;;;OAOG;IACG,mBAAmB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAwBlE;;;;;;;;OAQG;IACG,gBAAgB,CACpB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;CAyBrC"}
@@ -0,0 +1,311 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ 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");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _ChompApiService_instances, _ChompApiService_baseUrl, _ChompApiService_authHeaders;
13
+ import { BaseDataService } from "@metamask/base-data-service";
14
+ import { HttpError } from "@metamask/controller-utils";
15
+ import { array, boolean, create, define, enums, literal, optional, string, type } from "@metamask/superstruct";
16
+ import { isStrictHexString } from "@metamask/utils";
17
+ // === GENERAL ===
18
+ /**
19
+ * The name of the {@link ChompApiService}, used to namespace the service's
20
+ * actions and events.
21
+ */
22
+ export const serviceName = 'ChompApiService';
23
+ // === MESSENGER ===
24
+ /**
25
+ * All of the methods within {@link ChompApiService} that are exposed via the
26
+ * messenger.
27
+ */
28
+ const MESSENGER_EXPOSED_METHODS = [
29
+ 'associateAddress',
30
+ 'createUpgrade',
31
+ 'getUpgrade',
32
+ 'verifyDelegation',
33
+ 'createIntents',
34
+ 'getIntentsByAddress',
35
+ 'createWithdrawal',
36
+ ];
37
+ // === RESPONSE VALIDATION ===
38
+ const HexStringStruct = define('Hex string', (value) => isStrictHexString(value));
39
+ const AssociateAddressResponseStruct = type({
40
+ profileId: string(),
41
+ address: string(),
42
+ status: string(),
43
+ });
44
+ const UpgradeResponseStruct = type({
45
+ signerAddress: string(),
46
+ status: string(),
47
+ createdAt: string(),
48
+ });
49
+ const VerifyDelegationResponseStruct = type({
50
+ valid: boolean(),
51
+ delegationHash: optional(string()),
52
+ errors: optional(array(string())),
53
+ });
54
+ const SendIntentResponseArrayStruct = array(type({
55
+ delegationHash: string(),
56
+ metadata: type({
57
+ allowance: HexStringStruct,
58
+ tokenSymbol: string(),
59
+ tokenAddress: HexStringStruct,
60
+ type: enums(['cash-deposit', 'cash-withdrawal']),
61
+ }),
62
+ createdAt: string(),
63
+ }));
64
+ const IntentEntryArrayStruct = array(type({
65
+ account: HexStringStruct,
66
+ delegationHash: HexStringStruct,
67
+ chainId: HexStringStruct,
68
+ status: enums(['active', 'revoked']),
69
+ metadata: type({
70
+ allowance: HexStringStruct,
71
+ tokenAddress: HexStringStruct,
72
+ tokenSymbol: string(),
73
+ type: enums(['deposit', 'withdraw']),
74
+ }),
75
+ }));
76
+ const CreateWithdrawalResponseStruct = type({
77
+ success: literal(true),
78
+ });
79
+ // === SERVICE DEFINITION ===
80
+ /**
81
+ * This service is responsible for communicating with the CHOMP API.
82
+ *
83
+ * All requests are authenticated via JWT Bearer tokens obtained from the
84
+ * {@link AuthenticationControllerGetBearerTokenAction} messenger action.
85
+ */
86
+ export class ChompApiService extends BaseDataService {
87
+ /**
88
+ * Constructs a new ChompApiService.
89
+ *
90
+ * @param args - The constructor arguments.
91
+ * @param args.messenger - The messenger suited for this service.
92
+ * @param args.baseUrl - The base URL of the CHOMP API.
93
+ * @param args.queryClientConfig - Configuration for the underlying TanStack
94
+ * Query client.
95
+ * @param args.policyOptions - Options to pass to `createServicePolicy`.
96
+ */
97
+ constructor({ messenger, baseUrl, queryClientConfig = {}, policyOptions = {}, }) {
98
+ super({
99
+ name: serviceName,
100
+ messenger,
101
+ queryClientConfig,
102
+ policyOptions,
103
+ });
104
+ _ChompApiService_instances.add(this);
105
+ _ChompApiService_baseUrl.set(this, void 0);
106
+ __classPrivateFieldSet(this, _ChompApiService_baseUrl, baseUrl, "f");
107
+ this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
108
+ }
109
+ /**
110
+ * Associates an address with a CHOMP profile.
111
+ *
112
+ * POST /v1/auth/address
113
+ *
114
+ * @param request - The association request containing signature, timestamp,
115
+ * and address.
116
+ * @returns The profile association result. Returns on both 201 and 409.
117
+ */
118
+ async associateAddress(request) {
119
+ const jsonResponse = await this.fetchQuery({
120
+ queryKey: [`${this.name}:associateAddress`, request],
121
+ staleTime: 0,
122
+ queryFn: async () => {
123
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
124
+ const response = await fetch(new URL('/v1/auth/address', __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), {
125
+ method: 'POST',
126
+ headers,
127
+ body: JSON.stringify(request),
128
+ });
129
+ if (!response.ok && response.status !== 409) {
130
+ throw new HttpError(response.status, `POST /v1/auth/address failed with status '${response.status}'`);
131
+ }
132
+ return response.json();
133
+ },
134
+ });
135
+ return create(jsonResponse, AssociateAddressResponseStruct);
136
+ }
137
+ /**
138
+ * Creates an account upgrade request.
139
+ *
140
+ * POST /v1/account-upgrade
141
+ *
142
+ * @param request - The upgrade request containing signature components and
143
+ * chain details.
144
+ * @returns The upgrade result.
145
+ */
146
+ async createUpgrade(request) {
147
+ const jsonResponse = await this.fetchQuery({
148
+ queryKey: [`${this.name}:createUpgrade`, request],
149
+ staleTime: 0,
150
+ queryFn: async () => {
151
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
152
+ const response = await fetch(new URL('/v1/account-upgrade', __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), {
153
+ method: 'POST',
154
+ headers,
155
+ body: JSON.stringify(request),
156
+ });
157
+ if (!response.ok) {
158
+ throw new HttpError(response.status, `POST /v1/account-upgrade failed with status '${response.status}'`);
159
+ }
160
+ return response.json();
161
+ },
162
+ });
163
+ return create(jsonResponse, UpgradeResponseStruct);
164
+ }
165
+ /**
166
+ * Fetches the upgrade record for a given address.
167
+ *
168
+ * GET /v1/account-upgrade/:address
169
+ *
170
+ * @param address - The address to look up.
171
+ * @returns The upgrade record, or null if not found.
172
+ */
173
+ async getUpgrade(address) {
174
+ const jsonResponse = await this.fetchQuery({
175
+ queryKey: [`${this.name}:getUpgrade`, address],
176
+ queryFn: async () => {
177
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
178
+ const response = await fetch(new URL(`/v1/account-upgrade/${address}`, __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), { headers });
179
+ if (response.status === 404) {
180
+ return null;
181
+ }
182
+ if (!response.ok) {
183
+ throw new HttpError(response.status, `Get upgrade request failed with status '${response.status}'`);
184
+ }
185
+ return response.json();
186
+ },
187
+ });
188
+ if (jsonResponse === null) {
189
+ return null;
190
+ }
191
+ return create(jsonResponse, UpgradeResponseStruct);
192
+ }
193
+ /**
194
+ * Verifies a delegation signature.
195
+ *
196
+ * POST /v1/intent/verify-delegation
197
+ *
198
+ * @param request - The delegation verification request.
199
+ * @returns The verification result including validity and optional errors.
200
+ */
201
+ async verifyDelegation(request) {
202
+ const jsonResponse = await this.fetchQuery({
203
+ queryKey: [`${this.name}:verifyDelegation`, request],
204
+ staleTime: 0,
205
+ queryFn: async () => {
206
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
207
+ const response = await fetch(new URL('/v1/intent/verify-delegation', __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), {
208
+ method: 'POST',
209
+ headers,
210
+ body: JSON.stringify(request),
211
+ });
212
+ if (!response.ok) {
213
+ throw new HttpError(response.status, `POST /v1/intent/verify-delegation failed with status '${response.status}'`);
214
+ }
215
+ return response.json();
216
+ },
217
+ });
218
+ return create(jsonResponse, VerifyDelegationResponseStruct);
219
+ }
220
+ /**
221
+ * Submits one or more intents to the CHOMP API.
222
+ *
223
+ * POST /v1/intent
224
+ *
225
+ * @param intents - The array of intents to submit.
226
+ * @returns The array of intent responses.
227
+ */
228
+ async createIntents(intents) {
229
+ const jsonResponse = await this.fetchQuery({
230
+ queryKey: [`${this.name}:createIntents`, intents],
231
+ staleTime: 0,
232
+ queryFn: async () => {
233
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
234
+ const response = await fetch(new URL('/v1/intent', __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), {
235
+ method: 'POST',
236
+ headers,
237
+ body: JSON.stringify(intents),
238
+ });
239
+ if (!response.ok) {
240
+ throw new HttpError(response.status, `POST /v1/intent failed with status '${response.status}'`);
241
+ }
242
+ return response.json();
243
+ },
244
+ });
245
+ return create(jsonResponse, SendIntentResponseArrayStruct);
246
+ }
247
+ /**
248
+ * Fetches intents associated with a given address.
249
+ *
250
+ * GET /v1/intent/account/:address
251
+ *
252
+ * @param address - The address to look up intents for.
253
+ * @returns The array of intents for the address.
254
+ */
255
+ async getIntentsByAddress(address) {
256
+ const jsonResponse = await this.fetchQuery({
257
+ queryKey: [`${this.name}:getIntentsByAddress`, address],
258
+ queryFn: async () => {
259
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
260
+ const response = await fetch(new URL(`/v1/intent/account/${address}`, __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), { headers });
261
+ if (!response.ok) {
262
+ throw new HttpError(response.status, `Get intents request failed with status '${response.status}'`);
263
+ }
264
+ return response.json();
265
+ },
266
+ });
267
+ return create(jsonResponse, IntentEntryArrayStruct);
268
+ }
269
+ /**
270
+ * Creates a withdrawal for card spend flows.
271
+ *
272
+ * POST /v1/withdrawal
273
+ *
274
+ * @param request - The withdrawal request containing chainId, amount
275
+ * (decimal or hex string), and account address.
276
+ * @returns The withdrawal result.
277
+ */
278
+ async createWithdrawal(request) {
279
+ const jsonResponse = await this.fetchQuery({
280
+ queryKey: [`${this.name}:createWithdrawal`, request],
281
+ staleTime: 0,
282
+ queryFn: async () => {
283
+ const headers = await __classPrivateFieldGet(this, _ChompApiService_instances, "m", _ChompApiService_authHeaders).call(this);
284
+ const response = await fetch(new URL('/v1/withdrawal', __classPrivateFieldGet(this, _ChompApiService_baseUrl, "f")), {
285
+ method: 'POST',
286
+ headers,
287
+ body: JSON.stringify(request),
288
+ });
289
+ if (!response.ok) {
290
+ throw new HttpError(response.status, `POST /v1/withdrawal failed with status '${response.status}'`);
291
+ }
292
+ return response.json();
293
+ },
294
+ });
295
+ return create(jsonResponse, CreateWithdrawalResponseStruct);
296
+ }
297
+ }
298
+ _ChompApiService_baseUrl = new WeakMap(), _ChompApiService_instances = new WeakSet(), _ChompApiService_authHeaders =
299
+ /**
300
+ * Builds the standard headers for an authenticated CHOMP API request.
301
+ *
302
+ * @returns Headers including Authorization and Content-Type.
303
+ */
304
+ async function _ChompApiService_authHeaders() {
305
+ const token = await this.messenger.call('AuthenticationController:getBearerToken');
306
+ return {
307
+ Authorization: `Bearer ${token}`,
308
+ 'Content-Type': 'application/json',
309
+ };
310
+ };
311
+ //# sourceMappingURL=chomp-api-service.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chomp-api-service.mjs","sourceRoot":"","sources":["../src/chomp-api-service.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,eAAe,EAAE,oCAAoC;AAO9D,OAAO,EAAE,SAAS,EAAE,mCAAmC;AAGvD,OAAO,EACL,KAAK,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AC;IACvE,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,gBAAgB,CACpB,OAAgC;QAEhC,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC;YACzC,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,mBAAmB,EAAE,OAAO,CAAC;YACpD,SAAS,EAAE,CAAC;YACZ,OAAO,EAAE,KAAK,IAAI,EAAE;gBAClB,MAAM,OAAO,GAAG,MAAM,uBAAA,IAAI,gEAAa,MAAjB,IAAI,CAAe,CAAC;gBAC1C,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,IAAI,GAAG,CAAC,gBAAgB,EAAE,uBAAA,IAAI,gCAAS,CAAC,EAAE;oBACrE,MAAM,EAAE,MAAM;oBACd,OAAO;oBACP,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;iBAC9B,CAAC,CAAC;gBAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;oBACjB,MAAM,IAAI,SAAS,CACjB,QAAQ,CAAC,MAAM,EACf,2CAA2C,QAAQ,CAAC,MAAM,GAAG,CAC9D,CAAC;gBACJ,CAAC;gBAED,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;YACzB,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC,YAAY,EAAE,8BAA8B,CAAC,CAAC;IAC9D,CAAC;CACF;;AAvRC;;;;GAIG;AACH,KAAK;IACH,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,IAAI,CACrC,yCAAyC,CAC1C,CAAC;IACF,OAAO;QACL,aAAa,EAAE,UAAU,KAAK,EAAE;QAChC,cAAc,EAAE,kBAAkB;KACnC,CAAC;AACJ,CAAC","sourcesContent":["import { BaseDataService } from '@metamask/base-data-service';\nimport type {\n DataServiceCacheUpdatedEvent,\n DataServiceGranularCacheUpdatedEvent,\n DataServiceInvalidateQueriesAction,\n} from '@metamask/base-data-service';\nimport type { CreateServicePolicyOptions } from '@metamask/controller-utils';\nimport { HttpError } from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { AuthenticationControllerGetBearerTokenAction } from '@metamask/profile-sync-controller/auth';\nimport {\n array,\n boolean,\n create,\n define,\n enums,\n literal,\n optional,\n string,\n type,\n} from '@metamask/superstruct';\nimport { isStrictHexString } from '@metamask/utils';\nimport type { QueryClientConfig } from '@tanstack/query-core';\n\nimport type { ChompApiServiceMethodActions } from './chomp-api-service-method-action-types';\nimport type {\n AssociateAddressRequest,\n AssociateAddressResponse,\n CreateUpgradeRequest,\n UpgradeResponse,\n CreateWithdrawalRequest,\n CreateWithdrawalResponse,\n IntentEntry,\n SendIntentRequest,\n SendIntentResponse,\n VerifyDelegationRequest,\n VerifyDelegationResponse,\n} from './types';\n\n// === GENERAL ===\n\n/**\n * The name of the {@link ChompApiService}, used to namespace the service's\n * actions and events.\n */\nexport const serviceName = 'ChompApiService';\n\n// === MESSENGER ===\n\n/**\n * All of the methods within {@link ChompApiService} that are exposed via the\n * messenger.\n */\nconst MESSENGER_EXPOSED_METHODS = [\n 'associateAddress',\n 'createUpgrade',\n 'getUpgrade',\n 'verifyDelegation',\n 'createIntents',\n 'getIntentsByAddress',\n 'createWithdrawal',\n] as const;\n\n/**\n * Invalidates cached queries for {@link ChompApiService}.\n */\nexport type ChompApiServiceInvalidateQueriesAction =\n DataServiceInvalidateQueriesAction<typeof serviceName>;\n\n/**\n * Actions that {@link ChompApiService} exposes to other consumers.\n */\nexport type ChompApiServiceActions =\n | ChompApiServiceMethodActions\n | ChompApiServiceInvalidateQueriesAction;\n\n/**\n * Actions from other messengers that {@link ChompApiService} calls.\n */\ntype AllowedActions = AuthenticationControllerGetBearerTokenAction;\n\n/**\n * Published when {@link ChompApiService}'s cache is updated.\n */\nexport type ChompApiServiceCacheUpdatedEvent = DataServiceCacheUpdatedEvent<\n typeof serviceName\n>;\n\n/**\n * Published when a key within {@link ChompApiService}'s cache is updated.\n */\nexport type ChompApiServiceGranularCacheUpdatedEvent =\n DataServiceGranularCacheUpdatedEvent<typeof serviceName>;\n\n/**\n * Events that {@link ChompApiService} exposes to other consumers.\n */\nexport type ChompApiServiceEvents =\n | ChompApiServiceCacheUpdatedEvent\n | ChompApiServiceGranularCacheUpdatedEvent;\n\n/**\n * Events from other messengers that {@link ChompApiService} subscribes to.\n */\ntype AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link ChompApiService}.\n */\nexport type ChompApiServiceMessenger = Messenger<\n typeof serviceName,\n ChompApiServiceActions | AllowedActions,\n ChompApiServiceEvents | AllowedEvents\n>;\n\n// === RESPONSE VALIDATION ===\n\nconst HexStringStruct = define<string>('Hex string', (value) =>\n isStrictHexString(value),\n);\n\nconst AssociateAddressResponseStruct = type({\n profileId: string(),\n address: string(),\n status: string(),\n});\n\nconst UpgradeResponseStruct = type({\n signerAddress: string(),\n status: string(),\n createdAt: string(),\n});\n\nconst VerifyDelegationResponseStruct = type({\n valid: boolean(),\n delegationHash: optional(string()),\n errors: optional(array(string())),\n});\n\nconst SendIntentResponseArrayStruct = array(\n type({\n delegationHash: string(),\n metadata: type({\n allowance: HexStringStruct,\n tokenSymbol: string(),\n tokenAddress: HexStringStruct,\n type: enums(['cash-deposit', 'cash-withdrawal']),\n }),\n createdAt: string(),\n }),\n);\n\nconst IntentEntryArrayStruct = array(\n type({\n account: HexStringStruct,\n delegationHash: HexStringStruct,\n chainId: HexStringStruct,\n status: enums(['active', 'revoked']),\n metadata: type({\n allowance: HexStringStruct,\n tokenAddress: HexStringStruct,\n tokenSymbol: string(),\n type: enums(['deposit', 'withdraw']),\n }),\n }),\n);\n\nconst CreateWithdrawalResponseStruct = type({\n success: literal(true),\n});\n\n// === SERVICE DEFINITION ===\n\n/**\n * This service is responsible for communicating with the CHOMP API.\n *\n * All requests are authenticated via JWT Bearer tokens obtained from the\n * {@link AuthenticationControllerGetBearerTokenAction} messenger action.\n */\nexport class ChompApiService extends BaseDataService<\n typeof serviceName,\n ChompApiServiceMessenger\n> {\n readonly #baseUrl: string;\n\n /**\n * Constructs a new ChompApiService.\n *\n * @param args - The constructor arguments.\n * @param args.messenger - The messenger suited for this service.\n * @param args.baseUrl - The base URL of the CHOMP API.\n * @param args.queryClientConfig - Configuration for the underlying TanStack\n * Query client.\n * @param args.policyOptions - Options to pass to `createServicePolicy`.\n */\n constructor({\n messenger,\n baseUrl,\n queryClientConfig = {},\n policyOptions = {},\n }: {\n messenger: ChompApiServiceMessenger;\n baseUrl: string;\n queryClientConfig?: QueryClientConfig;\n policyOptions?: CreateServicePolicyOptions;\n }) {\n super({\n name: serviceName,\n messenger,\n queryClientConfig,\n policyOptions,\n });\n\n this.#baseUrl = baseUrl;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Builds the standard headers for an authenticated CHOMP API request.\n *\n * @returns Headers including Authorization and Content-Type.\n */\n async #authHeaders(): Promise<Record<string, string>> {\n const token = await this.messenger.call(\n 'AuthenticationController:getBearerToken',\n );\n return {\n Authorization: `Bearer ${token}`,\n 'Content-Type': 'application/json',\n };\n }\n\n /**\n * Associates an address with a CHOMP profile.\n *\n * POST /v1/auth/address\n *\n * @param request - The association request containing signature, timestamp,\n * and address.\n * @returns The profile association result. Returns on both 201 and 409.\n */\n async associateAddress(\n request: AssociateAddressRequest,\n ): Promise<AssociateAddressResponse> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:associateAddress`, request],\n staleTime: 0,\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(\n new URL('/v1/auth/address', this.#baseUrl),\n {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n },\n );\n\n if (!response.ok && response.status !== 409) {\n throw new HttpError(\n response.status,\n `POST /v1/auth/address failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(jsonResponse, AssociateAddressResponseStruct);\n }\n\n /**\n * Creates an account upgrade request.\n *\n * POST /v1/account-upgrade\n *\n * @param request - The upgrade request containing signature components and\n * chain details.\n * @returns The upgrade result.\n */\n async createUpgrade(request: CreateUpgradeRequest): Promise<UpgradeResponse> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:createUpgrade`, request],\n staleTime: 0,\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(\n new URL('/v1/account-upgrade', this.#baseUrl),\n {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n },\n );\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `POST /v1/account-upgrade failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(jsonResponse, UpgradeResponseStruct);\n }\n\n /**\n * Fetches the upgrade record for a given address.\n *\n * GET /v1/account-upgrade/:address\n *\n * @param address - The address to look up.\n * @returns The upgrade record, or null if not found.\n */\n async getUpgrade(address: string): Promise<UpgradeResponse | null> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:getUpgrade`, address],\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(\n new URL(`/v1/account-upgrade/${address}`, this.#baseUrl),\n { headers },\n );\n\n if (response.status === 404) {\n return null;\n }\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Get upgrade request failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n if (jsonResponse === null) {\n return null;\n }\n\n return create(jsonResponse, UpgradeResponseStruct);\n }\n\n /**\n * Verifies a delegation signature.\n *\n * POST /v1/intent/verify-delegation\n *\n * @param request - The delegation verification request.\n * @returns The verification result including validity and optional errors.\n */\n async verifyDelegation(\n request: VerifyDelegationRequest,\n ): Promise<VerifyDelegationResponse> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:verifyDelegation`, request],\n staleTime: 0,\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(\n new URL('/v1/intent/verify-delegation', this.#baseUrl),\n {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n },\n );\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `POST /v1/intent/verify-delegation failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(jsonResponse, VerifyDelegationResponseStruct);\n }\n\n /**\n * Submits one or more intents to the CHOMP API.\n *\n * POST /v1/intent\n *\n * @param intents - The array of intents to submit.\n * @returns The array of intent responses.\n */\n async createIntents(\n intents: SendIntentRequest[],\n ): Promise<SendIntentResponse[]> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:createIntents`, intents],\n staleTime: 0,\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(new URL('/v1/intent', this.#baseUrl), {\n method: 'POST',\n headers,\n body: JSON.stringify(intents),\n });\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `POST /v1/intent failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(\n jsonResponse,\n SendIntentResponseArrayStruct,\n ) as SendIntentResponse[];\n }\n\n /**\n * Fetches intents associated with a given address.\n *\n * GET /v1/intent/account/:address\n *\n * @param address - The address to look up intents for.\n * @returns The array of intents for the address.\n */\n async getIntentsByAddress(address: string): Promise<IntentEntry[]> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:getIntentsByAddress`, address],\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(\n new URL(`/v1/intent/account/${address}`, this.#baseUrl),\n { headers },\n );\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Get intents request failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(jsonResponse, IntentEntryArrayStruct) as IntentEntry[];\n }\n\n /**\n * Creates a withdrawal for card spend flows.\n *\n * POST /v1/withdrawal\n *\n * @param request - The withdrawal request containing chainId, amount\n * (decimal or hex string), and account address.\n * @returns The withdrawal result.\n */\n async createWithdrawal(\n request: CreateWithdrawalRequest,\n ): Promise<CreateWithdrawalResponse> {\n const jsonResponse = await this.fetchQuery({\n queryKey: [`${this.name}:createWithdrawal`, request],\n staleTime: 0,\n queryFn: async () => {\n const headers = await this.#authHeaders();\n const response = await fetch(new URL('/v1/withdrawal', this.#baseUrl), {\n method: 'POST',\n headers,\n body: JSON.stringify(request),\n });\n\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `POST /v1/withdrawal failed with status '${response.status}'`,\n );\n }\n\n return response.json();\n },\n });\n\n return create(jsonResponse, CreateWithdrawalResponseStruct);\n }\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChompApiService = void 0;
4
+ var chomp_api_service_1 = require("./chomp-api-service.cjs");
5
+ Object.defineProperty(exports, "ChompApiService", { enumerable: true, get: function () { return chomp_api_service_1.ChompApiService; } });
6
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,6DAAsD;AAA7C,oHAAA,eAAe,OAAA","sourcesContent":["export { ChompApiService } from './chomp-api-service';\nexport type {\n ChompApiServiceMessenger,\n ChompApiServiceActions,\n ChompApiServiceEvents,\n ChompApiServiceInvalidateQueriesAction,\n ChompApiServiceCacheUpdatedEvent,\n ChompApiServiceGranularCacheUpdatedEvent,\n} from './chomp-api-service';\nexport type {\n ChompApiServiceAssociateAddressAction,\n ChompApiServiceCreateUpgradeAction,\n ChompApiServiceGetUpgradeAction,\n ChompApiServiceVerifyDelegationAction,\n ChompApiServiceCreateIntentsAction,\n ChompApiServiceGetIntentsByAddressAction,\n ChompApiServiceCreateWithdrawalAction,\n} from './chomp-api-service-method-action-types';\nexport type {\n AssociateAddressRequest,\n AssociateAddressResponse,\n CreateUpgradeRequest,\n CreateWithdrawalRequest,\n CreateWithdrawalResponse,\n DelegationCaveat,\n UpgradeResponse,\n IntentEntry,\n IntentMetadataRequest,\n IntentMetadataResponse,\n SendIntentRequest,\n SendIntentResponse,\n SignedDelegation,\n VerifyDelegationRequest,\n VerifyDelegationResponse,\n} from './types';\n"]}