@swapkit/api-sdk-typescript 1.0.0 → 1.0.3

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.
@@ -0,0 +1,316 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import { getAuthToken } from '../core/auth';
4
+ import type { QuerySerializerOptions } from '../core/bodySerializer';
5
+ import { jsonBodySerializer } from '../core/bodySerializer';
6
+ import {
7
+ serializeArrayParam,
8
+ serializeObjectParam,
9
+ serializePrimitiveParam,
10
+ } from '../core/pathSerializer';
11
+ import { getUrl } from '../core/utils';
12
+ import type { Client, ClientOptions, Config, RequestOptions } from './types';
13
+
14
+ export const createQuerySerializer = <T = unknown>({
15
+ parameters = {},
16
+ ...args
17
+ }: QuerySerializerOptions = {}) => {
18
+ const querySerializer = (queryParams: T) => {
19
+ const search: string[] = [];
20
+ if (queryParams && typeof queryParams === 'object') {
21
+ for (const name in queryParams) {
22
+ const value = queryParams[name];
23
+
24
+ if (value === undefined || value === null) {
25
+ continue;
26
+ }
27
+
28
+ const options = parameters[name] || args;
29
+
30
+ if (Array.isArray(value)) {
31
+ const serializedArray = serializeArrayParam({
32
+ allowReserved: options.allowReserved,
33
+ explode: true,
34
+ name,
35
+ style: 'form',
36
+ value,
37
+ ...options.array,
38
+ });
39
+ if (serializedArray) search.push(serializedArray);
40
+ } else if (typeof value === 'object') {
41
+ const serializedObject = serializeObjectParam({
42
+ allowReserved: options.allowReserved,
43
+ explode: true,
44
+ name,
45
+ style: 'deepObject',
46
+ value: value as Record<string, unknown>,
47
+ ...options.object,
48
+ });
49
+ if (serializedObject) search.push(serializedObject);
50
+ } else {
51
+ const serializedPrimitive = serializePrimitiveParam({
52
+ allowReserved: options.allowReserved,
53
+ name,
54
+ value: value as string,
55
+ });
56
+ if (serializedPrimitive) search.push(serializedPrimitive);
57
+ }
58
+ }
59
+ }
60
+ return search.join('&');
61
+ };
62
+ return querySerializer;
63
+ };
64
+
65
+ /**
66
+ * Infers parseAs value from provided Content-Type header.
67
+ */
68
+ export const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {
69
+ if (!contentType) {
70
+ // If no Content-Type header is provided, the best we can do is return the raw response body,
71
+ // which is effectively the same as the 'stream' option.
72
+ return 'stream';
73
+ }
74
+
75
+ const cleanContent = contentType.split(';')[0]?.trim();
76
+
77
+ if (!cleanContent) {
78
+ return;
79
+ }
80
+
81
+ if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
82
+ return 'json';
83
+ }
84
+
85
+ if (cleanContent === 'multipart/form-data') {
86
+ return 'formData';
87
+ }
88
+
89
+ if (
90
+ ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))
91
+ ) {
92
+ return 'blob';
93
+ }
94
+
95
+ if (cleanContent.startsWith('text/')) {
96
+ return 'text';
97
+ }
98
+
99
+ return;
100
+ };
101
+
102
+ const checkForExistence = (
103
+ options: Pick<RequestOptions, 'auth' | 'query'> & {
104
+ headers: Headers;
105
+ },
106
+ name?: string,
107
+ ): boolean => {
108
+ if (!name) {
109
+ return false;
110
+ }
111
+ if (
112
+ options.headers.has(name) ||
113
+ options.query?.[name] ||
114
+ options.headers.get('Cookie')?.includes(`${name}=`)
115
+ ) {
116
+ return true;
117
+ }
118
+ return false;
119
+ };
120
+
121
+ export const setAuthParams = async ({
122
+ security,
123
+ ...options
124
+ }: Pick<Required<RequestOptions>, 'security'> &
125
+ Pick<RequestOptions, 'auth' | 'query'> & {
126
+ headers: Headers;
127
+ }) => {
128
+ for (const auth of security) {
129
+ if (checkForExistence(options, auth.name)) {
130
+ continue;
131
+ }
132
+
133
+ const token = await getAuthToken(auth, options.auth);
134
+
135
+ if (!token) {
136
+ continue;
137
+ }
138
+
139
+ const name = auth.name ?? 'Authorization';
140
+
141
+ switch (auth.in) {
142
+ case 'query':
143
+ if (!options.query) {
144
+ options.query = {};
145
+ }
146
+ options.query[name] = token;
147
+ break;
148
+ case 'cookie':
149
+ options.headers.append('Cookie', `${name}=${token}`);
150
+ break;
151
+ case 'header':
152
+ default:
153
+ options.headers.set(name, token);
154
+ break;
155
+ }
156
+ }
157
+ };
158
+
159
+ export const buildUrl: Client['buildUrl'] = (options) =>
160
+ getUrl({
161
+ baseUrl: options.baseUrl as string,
162
+ path: options.path,
163
+ query: options.query,
164
+ querySerializer:
165
+ typeof options.querySerializer === 'function'
166
+ ? options.querySerializer
167
+ : createQuerySerializer(options.querySerializer),
168
+ url: options.url,
169
+ });
170
+
171
+ export const mergeConfigs = (a: Config, b: Config): Config => {
172
+ const config = { ...a, ...b };
173
+ if (config.baseUrl?.endsWith('/')) {
174
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
175
+ }
176
+ config.headers = mergeHeaders(a.headers, b.headers);
177
+ return config;
178
+ };
179
+
180
+ const headersEntries = (headers: Headers): Array<[string, string]> => {
181
+ const entries: Array<[string, string]> = [];
182
+ headers.forEach((value, key) => {
183
+ entries.push([key, value]);
184
+ });
185
+ return entries;
186
+ };
187
+
188
+ export const mergeHeaders = (
189
+ ...headers: Array<Required<Config>['headers'] | undefined>
190
+ ): Headers => {
191
+ const mergedHeaders = new Headers();
192
+ for (const header of headers) {
193
+ if (!header) {
194
+ continue;
195
+ }
196
+
197
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
198
+
199
+ for (const [key, value] of iterator) {
200
+ if (value === null) {
201
+ mergedHeaders.delete(key);
202
+ } else if (Array.isArray(value)) {
203
+ for (const v of value) {
204
+ mergedHeaders.append(key, v as string);
205
+ }
206
+ } else if (value !== undefined) {
207
+ // assume object headers are meant to be JSON stringified, i.e. their
208
+ // content value in OpenAPI specification is 'application/json'
209
+ mergedHeaders.set(
210
+ key,
211
+ typeof value === 'object' ? JSON.stringify(value) : (value as string),
212
+ );
213
+ }
214
+ }
215
+ }
216
+ return mergedHeaders;
217
+ };
218
+
219
+ type ErrInterceptor<Err, Res, Req, Options> = (
220
+ error: Err,
221
+ response: Res,
222
+ request: Req,
223
+ options: Options,
224
+ ) => Err | Promise<Err>;
225
+
226
+ type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
227
+
228
+ type ResInterceptor<Res, Req, Options> = (
229
+ response: Res,
230
+ request: Req,
231
+ options: Options,
232
+ ) => Res | Promise<Res>;
233
+
234
+ class Interceptors<Interceptor> {
235
+ fns: Array<Interceptor | null> = [];
236
+
237
+ clear(): void {
238
+ this.fns = [];
239
+ }
240
+
241
+ eject(id: number | Interceptor): void {
242
+ const index = this.getInterceptorIndex(id);
243
+ if (this.fns[index]) {
244
+ this.fns[index] = null;
245
+ }
246
+ }
247
+
248
+ exists(id: number | Interceptor): boolean {
249
+ const index = this.getInterceptorIndex(id);
250
+ return Boolean(this.fns[index]);
251
+ }
252
+
253
+ getInterceptorIndex(id: number | Interceptor): number {
254
+ if (typeof id === 'number') {
255
+ return this.fns[id] ? id : -1;
256
+ }
257
+ return this.fns.indexOf(id);
258
+ }
259
+
260
+ update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
261
+ const index = this.getInterceptorIndex(id);
262
+ if (this.fns[index]) {
263
+ this.fns[index] = fn;
264
+ return id;
265
+ }
266
+ return false;
267
+ }
268
+
269
+ use(fn: Interceptor): number {
270
+ this.fns.push(fn);
271
+ return this.fns.length - 1;
272
+ }
273
+ }
274
+
275
+ export interface Middleware<Req, Res, Err, Options> {
276
+ error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
277
+ request: Interceptors<ReqInterceptor<Req, Options>>;
278
+ response: Interceptors<ResInterceptor<Res, Req, Options>>;
279
+ }
280
+
281
+ export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
282
+ Req,
283
+ Res,
284
+ Err,
285
+ Options
286
+ > => ({
287
+ error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
288
+ request: new Interceptors<ReqInterceptor<Req, Options>>(),
289
+ response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
290
+ });
291
+
292
+ const defaultQuerySerializer = createQuerySerializer({
293
+ allowReserved: false,
294
+ array: {
295
+ explode: true,
296
+ style: 'form',
297
+ },
298
+ object: {
299
+ explode: true,
300
+ style: 'deepObject',
301
+ },
302
+ });
303
+
304
+ const defaultHeaders = {
305
+ 'Content-Type': 'application/json',
306
+ };
307
+
308
+ export const createConfig = <T extends ClientOptions = ClientOptions>(
309
+ override: Config<Omit<ClientOptions, keyof T> & T> = {},
310
+ ): Config<Omit<ClientOptions, keyof T> & T> => ({
311
+ ...jsonBodySerializer,
312
+ headers: defaultHeaders,
313
+ parseAs: 'auto',
314
+ querySerializer: defaultQuerySerializer,
315
+ ...override,
316
+ });
package/src/index.ts ADDED
@@ -0,0 +1,92 @@
1
+ export { configureSwapKit, client } from "./config";
2
+ export type { SwapKitClientOptions } from "./config";
3
+
4
+ // Re-export all generated types
5
+ export type * from "./types";
6
+
7
+ // Re-export all generated SDK functions
8
+ export * from "./sdk";
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // SwapKitService — single unified service class with all SDK methods
12
+ //
13
+ // Maps generated path-derived names to user-friendly method names.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import {
17
+ getProviders,
18
+ getTokens,
19
+ getSwapTo,
20
+ getSwapFrom,
21
+ postV3Quote,
22
+ postV3Swap,
23
+ postTrack,
24
+ postScreen,
25
+ getGas,
26
+ getGasHistory,
27
+ postPriceCachedPrice,
28
+ postChainflipBrokerChannel,
29
+ } from "./sdk";
30
+
31
+ export class SwapKitService {
32
+ static getProviders = getProviders;
33
+ static getTokens = getTokens;
34
+ static getSwapTo = getSwapTo;
35
+ static getSwapFrom = getSwapFrom;
36
+ static getQuote = postV3Quote;
37
+ static getSwap = postV3Swap;
38
+ static trackTransaction = postTrack;
39
+ static screenAddress = postScreen;
40
+ static getGasPrices = getGas;
41
+ static getGasHistory = getGasHistory;
42
+ static getCachedPrice = postPriceCachedPrice;
43
+ static createBrokerChannel = postChainflipBrokerChannel;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Backward-compatible service namespace aliases (deprecated)
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /** @deprecated Use `SwapKitService` instead */
51
+ export const TokenlistService = {
52
+ getProviders,
53
+ getTokens,
54
+ getSwapTo,
55
+ getSwapFrom,
56
+ } as const;
57
+
58
+ /** @deprecated Use `SwapKitService` instead */
59
+ export const QuoteService = {
60
+ getQuote: postV3Quote,
61
+ } as const;
62
+
63
+ /** @deprecated Use `SwapKitService` instead */
64
+ export const SwapService = {
65
+ getSwap: postV3Swap,
66
+ } as const;
67
+
68
+ /** @deprecated Use `SwapKitService` instead */
69
+ export const TrackService = {
70
+ trackTransaction: postTrack,
71
+ } as const;
72
+
73
+ /** @deprecated Use `SwapKitService` instead */
74
+ export const ScreenService = {
75
+ screenAddress: postScreen,
76
+ } as const;
77
+
78
+ /** @deprecated Use `SwapKitService` instead */
79
+ export const GasService = {
80
+ getGasPrices: getGas,
81
+ getGasHistory,
82
+ } as const;
83
+
84
+ /** @deprecated Use `SwapKitService` instead */
85
+ export const PriceService = {
86
+ getCachedPrice: postPriceCachedPrice,
87
+ } as const;
88
+
89
+ /** @deprecated Use `SwapKitService` instead */
90
+ export const ChainflipService = {
91
+ createBrokerChannel: postChainflipBrokerChannel,
92
+ } as const;
package/src/sdk.ts ADDED
@@ -0,0 +1,115 @@
1
+ // This file is auto-generated by @hey-api/openapi-ts
2
+
3
+ import type { Client, Options as Options2, TDataShape } from './http';
4
+ import { client } from './client';
5
+ import type { GetGasData, GetGasHistoryData, GetGasHistoryResponses, GetGasResponses, GetProvidersData, GetProvidersErrors, GetProvidersResponses, GetSwapFromData, GetSwapFromErrors, GetSwapFromResponses, GetSwapToData, GetSwapToErrors, GetSwapToResponses, GetTokensData, GetTokensErrors, GetTokensResponses, PostChainflipBrokerChannelData, PostChainflipBrokerChannelResponses, PostPriceCachedPriceData, PostPriceCachedPriceResponses, PostScreenData, PostScreenErrors, PostScreenResponses, PostTrackData, PostTrackResponses, PostV3QuoteData, PostV3QuoteErrors, PostV3QuoteResponses, PostV3SwapData, PostV3SwapErrors, PostV3SwapResponses } from './types';
6
+
7
+ export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean> = Options2<TData, ThrowOnError> & {
8
+ /**
9
+ * You can provide a client instance returned by `createClient()` instead of
10
+ * individual options. This might be also useful if you want to implement a
11
+ * custom client.
12
+ */
13
+ client?: Client;
14
+ /**
15
+ * You can pass arbitrary values through the `meta` object. This can be
16
+ * used to access values that aren't defined as part of the SDK function.
17
+ */
18
+ meta?: Record<string, unknown>;
19
+ };
20
+
21
+ export const getProviders = <ThrowOnError extends boolean = false>(options?: Options<GetProvidersData, ThrowOnError>) => (options?.client ?? client).get<GetProvidersResponses, GetProvidersErrors, ThrowOnError>({
22
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
23
+ url: '/providers',
24
+ ...options
25
+ });
26
+
27
+ export const getTokens = <ThrowOnError extends boolean = false>(options?: Options<GetTokensData, ThrowOnError>) => (options?.client ?? client).get<GetTokensResponses, GetTokensErrors, ThrowOnError>({
28
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
29
+ url: '/tokens',
30
+ ...options
31
+ });
32
+
33
+ export const getSwapTo = <ThrowOnError extends boolean = false>(options: Options<GetSwapToData, ThrowOnError>) => (options.client ?? client).get<GetSwapToResponses, GetSwapToErrors, ThrowOnError>({
34
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
35
+ url: '/swapTo',
36
+ ...options
37
+ });
38
+
39
+ export const getSwapFrom = <ThrowOnError extends boolean = false>(options: Options<GetSwapFromData, ThrowOnError>) => (options.client ?? client).get<GetSwapFromResponses, GetSwapFromErrors, ThrowOnError>({
40
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
41
+ url: '/swapFrom',
42
+ ...options
43
+ });
44
+
45
+ export const postChainflipBrokerChannel = <ThrowOnError extends boolean = false>(options: Options<PostChainflipBrokerChannelData, ThrowOnError>) => (options.client ?? client).post<PostChainflipBrokerChannelResponses, unknown, ThrowOnError>({
46
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
47
+ url: '/chainflip/broker/channel',
48
+ ...options,
49
+ headers: {
50
+ 'Content-Type': 'application/json',
51
+ ...options.headers
52
+ }
53
+ });
54
+
55
+ export const postTrack = <ThrowOnError extends boolean = false>(options?: Options<PostTrackData, ThrowOnError>) => (options?.client ?? client).post<PostTrackResponses, unknown, ThrowOnError>({
56
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
57
+ url: '/track',
58
+ ...options,
59
+ headers: {
60
+ 'Content-Type': 'application/json',
61
+ ...options?.headers
62
+ }
63
+ });
64
+
65
+ export const postScreen = <ThrowOnError extends boolean = false>(options: Options<PostScreenData, ThrowOnError>) => (options.client ?? client).post<PostScreenResponses, PostScreenErrors, ThrowOnError>({
66
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
67
+ url: '/screen',
68
+ ...options,
69
+ headers: {
70
+ 'Content-Type': 'application/json',
71
+ ...options.headers
72
+ }
73
+ });
74
+
75
+ export const getGasHistory = <ThrowOnError extends boolean = false>(options?: Options<GetGasHistoryData, ThrowOnError>) => (options?.client ?? client).get<GetGasHistoryResponses, unknown, ThrowOnError>({
76
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
77
+ url: '/gas/history',
78
+ ...options
79
+ });
80
+
81
+ export const getGas = <ThrowOnError extends boolean = false>(options?: Options<GetGasData, ThrowOnError>) => (options?.client ?? client).get<GetGasResponses, unknown, ThrowOnError>({
82
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
83
+ url: '/gas',
84
+ ...options
85
+ });
86
+
87
+ export const postPriceCachedPrice = <ThrowOnError extends boolean = false>(options: Options<PostPriceCachedPriceData, ThrowOnError>) => (options.client ?? client).post<PostPriceCachedPriceResponses, unknown, ThrowOnError>({
88
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
89
+ url: '/price/cached-price',
90
+ ...options,
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ ...options.headers
94
+ }
95
+ });
96
+
97
+ export const postV3Quote = <ThrowOnError extends boolean = false>(options: Options<PostV3QuoteData, ThrowOnError>) => (options.client ?? client).post<PostV3QuoteResponses, PostV3QuoteErrors, ThrowOnError>({
98
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
99
+ url: '/v3/quote',
100
+ ...options,
101
+ headers: {
102
+ 'Content-Type': 'application/json',
103
+ ...options.headers
104
+ }
105
+ });
106
+
107
+ export const postV3Swap = <ThrowOnError extends boolean = false>(options: Options<PostV3SwapData, ThrowOnError>) => (options.client ?? client).post<PostV3SwapResponses, PostV3SwapErrors, ThrowOnError>({
108
+ security: [{ name: 'x-api-key', type: 'apiKey' }],
109
+ url: '/v3/swap',
110
+ ...options,
111
+ headers: {
112
+ 'Content-Type': 'application/json',
113
+ ...options.headers
114
+ }
115
+ });