@tickwise/sdk 0.0.0-stage → 0.1.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 (72) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +185 -2
  3. package/dist/cjs/api-promise.d.ts +22 -0
  4. package/dist/cjs/api-promise.js +43 -0
  5. package/dist/cjs/client.d.ts +64 -0
  6. package/dist/cjs/client.js +118 -0
  7. package/dist/cjs/csv.d.ts +37 -0
  8. package/dist/cjs/csv.js +69 -0
  9. package/dist/cjs/errors.d.ts +85 -0
  10. package/dist/cjs/errors.js +181 -0
  11. package/dist/cjs/generated/openapi.d.ts +1821 -0
  12. package/dist/cjs/generated/openapi.js +6 -0
  13. package/dist/cjs/index.d.ts +11 -0
  14. package/dist/cjs/index.js +30 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/resources/base.d.ts +21 -0
  17. package/dist/cjs/resources/base.js +81 -0
  18. package/dist/cjs/resources/hooks.d.ts +26 -0
  19. package/dist/cjs/resources/hooks.js +46 -0
  20. package/dist/cjs/resources/meta.d.ts +23 -0
  21. package/dist/cjs/resources/meta.js +35 -0
  22. package/dist/cjs/resources/pools.d.ts +21 -0
  23. package/dist/cjs/resources/pools.js +40 -0
  24. package/dist/cjs/resources/positions.d.ts +45 -0
  25. package/dist/cjs/resources/positions.js +133 -0
  26. package/dist/cjs/resources/tokens.d.ts +13 -0
  27. package/dist/cjs/resources/tokens.js +20 -0
  28. package/dist/cjs/resources/wallets.d.ts +11 -0
  29. package/dist/cjs/resources/wallets.js +14 -0
  30. package/dist/cjs/routes.d.ts +80 -0
  31. package/dist/cjs/routes.js +40 -0
  32. package/dist/cjs/transport.d.ts +91 -0
  33. package/dist/cjs/transport.js +310 -0
  34. package/dist/cjs/types.d.ts +99 -0
  35. package/dist/cjs/types.js +2 -0
  36. package/dist/cjs/version.d.ts +2 -0
  37. package/dist/cjs/version.js +5 -0
  38. package/dist/esm/api-promise.d.ts +22 -0
  39. package/dist/esm/api-promise.js +39 -0
  40. package/dist/esm/client.d.ts +64 -0
  41. package/dist/esm/client.js +114 -0
  42. package/dist/esm/csv.d.ts +37 -0
  43. package/dist/esm/csv.js +64 -0
  44. package/dist/esm/errors.d.ts +85 -0
  45. package/dist/esm/errors.js +163 -0
  46. package/dist/esm/generated/openapi.d.ts +1821 -0
  47. package/dist/esm/generated/openapi.js +5 -0
  48. package/dist/esm/index.d.ts +11 -0
  49. package/dist/esm/index.js +8 -0
  50. package/dist/esm/resources/base.d.ts +21 -0
  51. package/dist/esm/resources/base.js +73 -0
  52. package/dist/esm/resources/hooks.d.ts +26 -0
  53. package/dist/esm/resources/hooks.js +42 -0
  54. package/dist/esm/resources/meta.d.ts +23 -0
  55. package/dist/esm/resources/meta.js +30 -0
  56. package/dist/esm/resources/pools.d.ts +21 -0
  57. package/dist/esm/resources/pools.js +36 -0
  58. package/dist/esm/resources/positions.d.ts +45 -0
  59. package/dist/esm/resources/positions.js +129 -0
  60. package/dist/esm/resources/tokens.d.ts +13 -0
  61. package/dist/esm/resources/tokens.js +16 -0
  62. package/dist/esm/resources/wallets.d.ts +11 -0
  63. package/dist/esm/resources/wallets.js +10 -0
  64. package/dist/esm/routes.d.ts +80 -0
  65. package/dist/esm/routes.js +36 -0
  66. package/dist/esm/transport.d.ts +91 -0
  67. package/dist/esm/transport.js +299 -0
  68. package/dist/esm/types.d.ts +99 -0
  69. package/dist/esm/types.js +1 -0
  70. package/dist/esm/version.d.ts +2 -0
  71. package/dist/esm/version.js +2 -0
  72. package/package.json +64 -4
@@ -0,0 +1,80 @@
1
+ import type { paths } from './generated/openapi.js';
2
+ export interface Route {
3
+ /** The OpenAPI path template. */
4
+ readonly path: keyof paths;
5
+ /** Metered routes need the key and cost units; free routes never send it. */
6
+ readonly metered: boolean;
7
+ }
8
+ /**
9
+ * Every `/v1` operation the SDK calls, keyed by the spec's `operationId`. `test/route-coverage.spec.ts` holds this
10
+ * to `openapi.json` both ways, so a route added to the API without an SDK method fails the build.
11
+ */
12
+ export declare const ROUTES: {
13
+ readonly 'positions.list': {
14
+ readonly path: "/v1/positions";
15
+ readonly metered: true;
16
+ };
17
+ readonly 'positions.batch': {
18
+ readonly path: "/v1/positions/batch";
19
+ readonly metered: true;
20
+ };
21
+ readonly 'positions.detail': {
22
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}";
23
+ readonly metered: true;
24
+ };
25
+ readonly 'positions.transactions': {
26
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}/transactions";
27
+ readonly metered: true;
28
+ };
29
+ readonly 'positions.charts': {
30
+ readonly path: "/v1/positions/{chainId}/{protocol}/{positionId}/charts";
31
+ readonly metered: true;
32
+ };
33
+ readonly 'pools.list': {
34
+ readonly path: "/v1/pools";
35
+ readonly metered: true;
36
+ };
37
+ readonly 'pools.detail': {
38
+ readonly path: "/v1/pools/{chainId}/{protocol}/{poolId}";
39
+ readonly metered: true;
40
+ };
41
+ readonly 'pools.charts': {
42
+ readonly path: "/v1/pools/{chainId}/{protocol}/{poolId}/charts";
43
+ readonly metered: true;
44
+ };
45
+ readonly 'tokens.detail': {
46
+ readonly path: "/v1/tokens/{chainId}/{address}";
47
+ readonly metered: true;
48
+ };
49
+ readonly 'wallets.summary': {
50
+ readonly path: "/v1/wallets/{address}";
51
+ readonly metered: true;
52
+ };
53
+ readonly 'hooks.list': {
54
+ readonly path: "/v1/hooks";
55
+ readonly metered: true;
56
+ };
57
+ readonly chains: {
58
+ readonly path: "/v1/chains";
59
+ readonly metered: false;
60
+ };
61
+ readonly protocols: {
62
+ readonly path: "/v1/protocols";
63
+ readonly metered: false;
64
+ };
65
+ readonly plans: {
66
+ readonly path: "/v1/plans";
67
+ readonly metered: false;
68
+ };
69
+ readonly 'pricing.units': {
70
+ readonly path: "/v1/pricing/units";
71
+ readonly metered: false;
72
+ };
73
+ readonly stats: {
74
+ readonly path: "/v1/stats";
75
+ readonly metered: false;
76
+ };
77
+ };
78
+ export type OperationId = keyof typeof ROUTES;
79
+ /** Fills a path template: `{name}` → the encoded value. */
80
+ export declare function fillPath(op: OperationId, params?: Readonly<Record<string, string | number | bigint>>): string;
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ROUTES = void 0;
4
+ exports.fillPath = fillPath;
5
+ /**
6
+ * Every `/v1` operation the SDK calls, keyed by the spec's `operationId`. `test/route-coverage.spec.ts` holds this
7
+ * to `openapi.json` both ways, so a route added to the API without an SDK method fails the build.
8
+ */
9
+ exports.ROUTES = {
10
+ 'positions.list': { path: '/v1/positions', metered: true },
11
+ 'positions.batch': { path: '/v1/positions/batch', metered: true },
12
+ 'positions.detail': { path: '/v1/positions/{chainId}/{protocol}/{positionId}', metered: true },
13
+ 'positions.transactions': { path: '/v1/positions/{chainId}/{protocol}/{positionId}/transactions', metered: true },
14
+ 'positions.charts': { path: '/v1/positions/{chainId}/{protocol}/{positionId}/charts', metered: true },
15
+ 'pools.list': { path: '/v1/pools', metered: true },
16
+ 'pools.detail': { path: '/v1/pools/{chainId}/{protocol}/{poolId}', metered: true },
17
+ 'pools.charts': { path: '/v1/pools/{chainId}/{protocol}/{poolId}/charts', metered: true },
18
+ 'tokens.detail': { path: '/v1/tokens/{chainId}/{address}', metered: true },
19
+ 'wallets.summary': { path: '/v1/wallets/{address}', metered: true },
20
+ 'hooks.list': { path: '/v1/hooks', metered: true },
21
+ chains: { path: '/v1/chains', metered: false },
22
+ protocols: { path: '/v1/protocols', metered: false },
23
+ plans: { path: '/v1/plans', metered: false },
24
+ 'pricing.units': { path: '/v1/pricing/units', metered: false },
25
+ stats: { path: '/v1/stats', metered: false },
26
+ };
27
+ /** Fills a path template: `{name}` → the encoded value. */
28
+ function fillPath(op, params = {}) {
29
+ return exports.ROUTES[op].path.replace(/\{([A-Za-z0-9_]+)\}/g, (_, name) => {
30
+ const v = params[name];
31
+ if (v === undefined || v === null || String(v) === '') {
32
+ throw new TypeError(`${op}: missing path parameter \`${name}\``);
33
+ }
34
+ // encodeURIComponent leaves `.` and `..` alone and URL parsing collapses them, which would call another route.
35
+ if (String(v) === '.' || String(v) === '..') {
36
+ throw new TypeError(`${op}: \`${name}\` cannot be \`${String(v)}\``);
37
+ }
38
+ return encodeURIComponent(String(v));
39
+ });
40
+ }
@@ -0,0 +1,91 @@
1
+ export declare const DEFAULT_BASE_URL = "https://api.tickwise.xyz";
2
+ export declare const DEFAULT_KEY_HEADER = "KC-APIKey";
3
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
4
+ export declare const DEFAULT_MAX_RETRIES = 2;
5
+ export declare const DEFAULT_MAX_RETRY_AFTER_SEC = 60;
6
+ export type QueryScalar = string | number | boolean | bigint;
7
+ export type QueryValue = QueryScalar | readonly (string | number | bigint)[] | null | undefined;
8
+ export type Query = Readonly<Record<string, QueryValue>>;
9
+ /** Per-call options, the last argument of every method. */
10
+ export interface RequestOptions {
11
+ /** Cancels the call, including a retry wait. The platform's `AbortError` (or the signal's reason) is thrown. */
12
+ signal?: AbortSignal;
13
+ /** Overrides the client's `timeoutMs` for this call (per attempt). */
14
+ timeoutMs?: number;
15
+ /** Overrides the client's `maxRetries` for this call. */
16
+ maxRetries?: number;
17
+ }
18
+ export interface LimitInfo {
19
+ limit: number;
20
+ remaining: number;
21
+ /** Seconds until it resets. */
22
+ resetSec: number;
23
+ }
24
+ /** What `.withMeta()` returns beside the data. */
25
+ export interface ResponseMeta {
26
+ status: number;
27
+ /** The request URL. It never contains the key (the key travels in a header). */
28
+ url: string;
29
+ /** How many retries it took (0 when the first attempt succeeded). */
30
+ retries: number;
31
+ headers: Headers;
32
+ /** `private, max-age=15`, or `no-store` on an answer flagged partial / stale. */
33
+ cacheControl: string | undefined;
34
+ /** The 60-second burst limit of this key (metered routes only). */
35
+ rateLimit: LimitInfo | undefined;
36
+ /** The monthly unit quota of the account (metered routes only). */
37
+ quota: LimitInfo | undefined;
38
+ /** Units this call was charged after refunds. Sent by the positions batch only, which is priced per position. */
39
+ unitsCharged: number | undefined;
40
+ }
41
+ export interface TransportConfig {
42
+ apiKey: string | undefined;
43
+ baseUrl: string;
44
+ keyHeader: string;
45
+ timeoutMs: number;
46
+ maxRetries: number;
47
+ maxRetryAfterSec: number;
48
+ maxBodyBytes: number | undefined;
49
+ fetch: typeof fetch;
50
+ /** Tests only: the jitter source. */
51
+ random?: () => number;
52
+ }
53
+ export interface RawRequest {
54
+ /** Path with its parameters already filled in, e.g. `/v1/pools/1/uniswap-v4/0xabc`. */
55
+ path: string;
56
+ query?: Query;
57
+ /** Metered routes send the key; free routes never do. */
58
+ metered: boolean;
59
+ accept: 'json' | 'csv';
60
+ }
61
+ export interface RawResponse {
62
+ /** Parsed JSON, or the text for a CSV request. */
63
+ body: unknown;
64
+ meta: ResponseMeta;
65
+ }
66
+ /** A finite number not below 0 (above 0 unless `allowZero`), else a TypeError naming the option. */
67
+ export declare function checkNumber(name: string, v: number, allowZero: boolean): number;
68
+ export declare function isBrowser(): boolean;
69
+ export declare function buildUrl(baseUrl: string, path: string, query?: Query): string;
70
+ /** A path segment, encoded. */
71
+ export declare function seg(v: string | number | bigint): string;
72
+ export declare function metaOf(status: number, url: string, retries: number, headers: Headers): ResponseMeta;
73
+ /**
74
+ * Whether a failed attempt is retried.
75
+ *
76
+ * A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
77
+ * before any charge), a 503 (the API credits it back), a 502 (the API did not answer the gateway), and a
78
+ * connection that was never opened. A timeout, a connection lost mid-request and a 504 are NOT retried on a metered
79
+ * route: the API may have served, and charged, the first attempt, so a retry could be billed twice.
80
+ * A free route costs nothing, so those are retried there too.
81
+ * Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
82
+ */
83
+ export declare function isRetryable(e: unknown, metered: boolean): boolean;
84
+ /** True only when every code found says the connection was never opened. No code (e.g. a browser) is false. */
85
+ export declare function connectFailed(e: unknown): boolean;
86
+ export declare class Transport {
87
+ #private;
88
+ constructor(config: TransportConfig);
89
+ get baseUrl(): string;
90
+ request(req: RawRequest, opts?: RequestOptions): Promise<RawResponse>;
91
+ }
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transport = exports.DEFAULT_MAX_RETRY_AFTER_SEC = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_KEY_HEADER = exports.DEFAULT_BASE_URL = void 0;
4
+ exports.checkNumber = checkNumber;
5
+ exports.isBrowser = isBrowser;
6
+ exports.buildUrl = buildUrl;
7
+ exports.seg = seg;
8
+ exports.metaOf = metaOf;
9
+ exports.isRetryable = isRetryable;
10
+ exports.connectFailed = connectFailed;
11
+ const errors_js_1 = require("./errors.js");
12
+ const version_js_1 = require("./version.js");
13
+ exports.DEFAULT_BASE_URL = 'https://api.tickwise.xyz';
14
+ exports.DEFAULT_KEY_HEADER = 'KC-APIKey';
15
+ exports.DEFAULT_TIMEOUT_MS = 30_000;
16
+ exports.DEFAULT_MAX_RETRIES = 2;
17
+ exports.DEFAULT_MAX_RETRY_AFTER_SEC = 60;
18
+ const BACKOFF_BASE_MS = 500;
19
+ const BACKOFF_CAP_MS = 8_000;
20
+ /** A finite number not below 0 (above 0 unless `allowZero`), else a TypeError naming the option. */
21
+ function checkNumber(name, v, allowZero) {
22
+ if (typeof v !== 'number' || !Number.isFinite(v) || v < 0 || (!allowZero && v === 0)) {
23
+ throw new TypeError(`Tickwise: \`${name}\` must be a ${allowZero ? 'non-negative' : 'positive'} finite number`);
24
+ }
25
+ return v;
26
+ }
27
+ function isBrowser() {
28
+ const g = globalThis;
29
+ return typeof g.window !== 'undefined' && typeof g.document !== 'undefined';
30
+ }
31
+ function buildUrl(baseUrl, path, query = {}) {
32
+ const qs = new URLSearchParams();
33
+ for (const [k, v] of Object.entries(query)) {
34
+ if (v === undefined || v === null)
35
+ continue;
36
+ if (Array.isArray(v)) {
37
+ if (v.length > 0)
38
+ qs.append(k, v.map(String).join(','));
39
+ }
40
+ else {
41
+ qs.append(k, String(v));
42
+ }
43
+ }
44
+ const s = qs.toString();
45
+ return `${baseUrl.replace(/\/+$/, '')}${path}${s ? `?${s}` : ''}`;
46
+ }
47
+ /** A path segment, encoded. */
48
+ function seg(v) {
49
+ return encodeURIComponent(String(v));
50
+ }
51
+ function intHeader(h, name) {
52
+ const v = h.get(name);
53
+ if (v === null || v.trim() === '')
54
+ return undefined;
55
+ const n = Number(v.trim());
56
+ return Number.isFinite(n) ? n : undefined;
57
+ }
58
+ function limitInfo(h, prefix) {
59
+ const limit = intHeader(h, `${prefix}-Limit`);
60
+ const remaining = intHeader(h, `${prefix}-Remaining`);
61
+ const resetSec = intHeader(h, `${prefix}-Reset`);
62
+ if (limit === undefined || remaining === undefined || resetSec === undefined)
63
+ return undefined;
64
+ return { limit, remaining, resetSec };
65
+ }
66
+ function metaOf(status, url, retries, headers) {
67
+ return {
68
+ status,
69
+ url,
70
+ retries,
71
+ headers,
72
+ cacheControl: headers.get('cache-control') ?? undefined,
73
+ rateLimit: limitInfo(headers, 'X-RateLimit'),
74
+ quota: limitInfo(headers, 'X-Quota'),
75
+ unitsCharged: intHeader(headers, 'X-Units-Charged'),
76
+ };
77
+ }
78
+ function abortReason(signal) {
79
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
80
+ }
81
+ function sleep(ms, signal) {
82
+ return new Promise((resolve, reject) => {
83
+ if (signal?.aborted) {
84
+ reject(abortReason(signal));
85
+ return;
86
+ }
87
+ const onAbort = () => {
88
+ clearTimeout(timer);
89
+ reject(abortReason(signal));
90
+ };
91
+ const timer = setTimeout(() => {
92
+ signal?.removeEventListener('abort', onAbort);
93
+ resolve();
94
+ }, ms);
95
+ signal?.addEventListener('abort', onAbort, { once: true });
96
+ });
97
+ }
98
+ /** The body as text, or null when it passes `max` bytes (a declared length over the cap is refused unread). */
99
+ async function readText(res, max) {
100
+ if (max === undefined)
101
+ return res.text();
102
+ const declared = Number(res.headers.get('content-length'));
103
+ if (Number.isFinite(declared) && declared > max) {
104
+ await res.body?.cancel().catch(() => { });
105
+ return null;
106
+ }
107
+ if (!res.body)
108
+ return '';
109
+ const reader = res.body.getReader();
110
+ const decoder = new TextDecoder();
111
+ let bytes = 0;
112
+ let text = '';
113
+ for (;;) {
114
+ const { done, value } = await reader.read();
115
+ if (done)
116
+ break;
117
+ bytes += value.byteLength;
118
+ if (bytes > max) {
119
+ await reader.cancel().catch(() => { });
120
+ return null;
121
+ }
122
+ text += decoder.decode(value, { stream: true });
123
+ }
124
+ return text + decoder.decode();
125
+ }
126
+ /**
127
+ * Whether a failed attempt is retried.
128
+ *
129
+ * A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
130
+ * before any charge), a 503 (the API credits it back), a 502 (the API did not answer the gateway), and a
131
+ * connection that was never opened. A timeout, a connection lost mid-request and a 504 are NOT retried on a metered
132
+ * route: the API may have served, and charged, the first attempt, so a retry could be billed twice.
133
+ * A free route costs nothing, so those are retried there too.
134
+ * Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
135
+ */
136
+ function isRetryable(e, metered) {
137
+ if (e instanceof errors_js_1.RateLimitError || e instanceof errors_js_1.ServiceUnavailableError)
138
+ return true;
139
+ if (e instanceof errors_js_1.ConnectionError)
140
+ return !metered || e.connectFailed;
141
+ if (e instanceof errors_js_1.TimeoutError)
142
+ return !metered;
143
+ return e instanceof errors_js_1.APIError && (e.status === 502 || (e.status === 504 && !metered));
144
+ }
145
+ /** Error codes that mean no connection was made, so nothing reached the API (Node / undici names). */
146
+ const CONNECT_FAILED_CODES = new Set([
147
+ 'ECONNREFUSED',
148
+ 'ENOTFOUND',
149
+ 'EAI_AGAIN',
150
+ 'ENETUNREACH',
151
+ 'ENETDOWN',
152
+ 'EHOSTUNREACH',
153
+ 'EHOSTDOWN',
154
+ 'UND_ERR_CONNECT_TIMEOUT',
155
+ ]);
156
+ /** Every `code` on the error, its `cause` chain and an `AggregateError`'s `errors` (happy-eyeballs connects). */
157
+ function errorCodes(e, out = [], depth = 0) {
158
+ if (depth > 5 || e === null || typeof e !== 'object')
159
+ return out;
160
+ const o = e;
161
+ if (typeof o.code === 'string')
162
+ out.push(o.code);
163
+ errorCodes(o.cause, out, depth + 1);
164
+ if (Array.isArray(o.errors))
165
+ for (const x of o.errors)
166
+ errorCodes(x, out, depth + 1);
167
+ return out;
168
+ }
169
+ /** True only when every code found says the connection was never opened. No code (e.g. a browser) is false. */
170
+ function connectFailed(e) {
171
+ const codes = errorCodes(e);
172
+ return codes.length > 0 && codes.every((c) => CONNECT_FAILED_CODES.has(c));
173
+ }
174
+ /**
175
+ * One attempt's signal: the caller's abort plus the timeout. Built on `AbortController` and `setTimeout` rather than
176
+ * `AbortSignal.timeout` / `AbortSignal.any`, which some browsers and edge runtimes lack; `done()` clears the timer.
177
+ */
178
+ function attemptSignal(timeoutMs, caller) {
179
+ const ac = new AbortController();
180
+ let timedOut = false;
181
+ const onAbort = () => ac.abort(caller?.reason);
182
+ const timer = setTimeout(() => {
183
+ timedOut = true;
184
+ ac.abort(new DOMException('The operation timed out', 'TimeoutError'));
185
+ }, timeoutMs);
186
+ caller?.addEventListener('abort', onAbort, { once: true });
187
+ return {
188
+ signal: ac.signal,
189
+ timedOut: () => timedOut,
190
+ done: () => {
191
+ clearTimeout(timer);
192
+ caller?.removeEventListener('abort', onAbort);
193
+ },
194
+ };
195
+ }
196
+ function parseJson(text) {
197
+ try {
198
+ return { ok: true, value: JSON.parse(text) };
199
+ }
200
+ catch {
201
+ return { ok: false };
202
+ }
203
+ }
204
+ class Transport {
205
+ #config;
206
+ #userAgent;
207
+ constructor(config) {
208
+ this.#config = config;
209
+ // Browsers forbid or ignore `User-Agent`, and a custom header would force a CORS preflight.
210
+ this.#userAgent = isBrowser() ? undefined : `tickwise-sdk/${version_js_1.VERSION}`;
211
+ }
212
+ get baseUrl() {
213
+ return this.#config.baseUrl;
214
+ }
215
+ async request(req, opts = {}) {
216
+ const cfg = this.#config;
217
+ const url = buildUrl(cfg.baseUrl, req.path, req.query);
218
+ const maxRetries = opts.maxRetries === undefined ? cfg.maxRetries : Math.floor(checkNumber('maxRetries', opts.maxRetries, true));
219
+ const timeoutMs = opts.timeoutMs === undefined ? cfg.timeoutMs : checkNumber('timeoutMs', opts.timeoutMs, false);
220
+ const headers = { Accept: req.accept === 'csv' ? 'text/csv' : 'application/json' };
221
+ if (req.metered && cfg.apiKey)
222
+ headers[cfg.keyHeader] = cfg.apiKey;
223
+ if (this.#userAgent)
224
+ headers['User-Agent'] = this.#userAgent;
225
+ for (let attempt = 0;; attempt++) {
226
+ if (opts.signal?.aborted)
227
+ throw abortReason(opts.signal);
228
+ let error;
229
+ try {
230
+ return await this.#attempt(url, headers, req, attempt, timeoutMs, opts.signal);
231
+ }
232
+ catch (e) {
233
+ if (opts.signal?.aborted)
234
+ throw abortReason(opts.signal);
235
+ if (!(e instanceof errors_js_1.TickwiseError))
236
+ throw e;
237
+ error = e;
238
+ }
239
+ if (attempt >= maxRetries || !isRetryable(error, req.metered))
240
+ throw error;
241
+ let wait;
242
+ if (error.retryAfterSec !== undefined) {
243
+ // A wait longer than the caller allows is handed back rather than slept through.
244
+ if (error.retryAfterSec > cfg.maxRetryAfterSec)
245
+ throw error;
246
+ wait = error.retryAfterSec * 1000;
247
+ }
248
+ else {
249
+ const cap = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
250
+ wait = Math.round((cfg.random ?? Math.random)() * cap);
251
+ }
252
+ await sleep(wait, opts.signal);
253
+ }
254
+ }
255
+ async #attempt(url, headers, req, attempt, timeoutMs, caller) {
256
+ const { signal, timedOut, done } = attemptSignal(timeoutMs, caller);
257
+ try {
258
+ // Redirects are not followed: fetch drops `Authorization` on a cross-host redirect but not a custom header, so
259
+ // following one would hand the key to wherever it points. The API does not redirect.
260
+ const res = await this.#config.fetch(url, { method: 'GET', headers, signal, redirect: 'manual' });
261
+ if (res.type === 'opaqueredirect' || (res.status >= 300 && res.status < 400)) {
262
+ await res.body?.cancel().catch(() => { });
263
+ throw new errors_js_1.APIError('redirect', `The API answered with a redirect (${res.status || 'opaque'}); it was not followed`, {
264
+ status: res.status || undefined,
265
+ headers: res.headers,
266
+ url,
267
+ });
268
+ }
269
+ const text = await readText(res, this.#config.maxBodyBytes);
270
+ if (text === null) {
271
+ throw new errors_js_1.APIError('api_error', `The response is larger than maxBodyBytes (${this.#config.maxBodyBytes})`, {
272
+ status: res.status,
273
+ headers: res.headers,
274
+ url,
275
+ });
276
+ }
277
+ const parsed = parseJson(text);
278
+ const body = parsed.ok ? parsed.value : text;
279
+ if (res.status < 200 || res.status >= 300)
280
+ throw (0, errors_js_1.errorFromResponse)(res.status, res.headers, body, url);
281
+ const meta = metaOf(res.status, url, attempt, res.headers);
282
+ if (req.accept === 'csv')
283
+ return { body: text, meta };
284
+ if (!parsed.ok) {
285
+ throw new errors_js_1.APIError('api_error', 'The API answered with a body that is not JSON', {
286
+ status: res.status,
287
+ body: text.slice(0, 500),
288
+ headers: res.headers,
289
+ url,
290
+ });
291
+ }
292
+ return { body, meta };
293
+ }
294
+ catch (e) {
295
+ if (e instanceof errors_js_1.TickwiseError)
296
+ throw e;
297
+ if (caller?.aborted)
298
+ throw abortReason(caller);
299
+ if (timedOut()) {
300
+ throw new errors_js_1.TimeoutError(`The Tickwise API did not answer within ${timeoutMs} ms`, { url, cause: e });
301
+ }
302
+ const why = e instanceof Error ? e.message : String(e);
303
+ throw new errors_js_1.ConnectionError(`Could not reach the Tickwise API: ${why}`, { url, cause: e, connectFailed: connectFailed(e) });
304
+ }
305
+ finally {
306
+ done();
307
+ }
308
+ }
309
+ }
310
+ exports.Transport = Transport;
@@ -0,0 +1,99 @@
1
+ import type { components, operations } from './generated/openapi.js';
2
+ type S = components['schemas'];
3
+ export type Pagination = S['Pagination'];
4
+ /** `partial` / `missingChains` (all-chains reads), `stale` / `dataAsOf`. */
5
+ export type Degradation = S['Degradation'];
6
+ export type Token = S['Token'];
7
+ export type Risk = S['Risk'];
8
+ export type Position = S['Position'];
9
+ export type PositionList = S['PositionList'];
10
+ export type PositionDetail = S['PositionDetail'];
11
+ export type PositionBatch = S['PositionBatch'];
12
+ export type Transaction = S['Transaction'];
13
+ export type TransactionsPage = S['TransactionsPage'];
14
+ export type Pool = S['Pool'];
15
+ export type PoolList = S['PoolList'];
16
+ export type PoolDetail = S['PoolDetail'];
17
+ export type TokenPrice = S['TokenPrice'];
18
+ export type TokenSecurity = S['TokenSecurity'];
19
+ export type TokenTrust = S['TokenTrust'];
20
+ export type TokenLookup = S['TokenLookup'];
21
+ export type Hook = S['Hook'];
22
+ export type HookList = S['HookList'];
23
+ export type WalletFigures = S['WalletFigures'];
24
+ export type WalletSummary = S['WalletSummary'];
25
+ export type ChartPoint = S['ChartPoint'];
26
+ export type Charts = S['Charts'];
27
+ export type Chain = S['Chain'];
28
+ export type Protocol = S['Protocol'];
29
+ export type PlanList = S['PlanList'];
30
+ export type UnitCostList = S['UnitCostList'];
31
+ export type Stats = S['Stats'];
32
+ /** The body of every error answer. */
33
+ export type ErrorBody = S['Error'];
34
+ /**
35
+ * A protocol key. `uniswap-v4` is the one served today; the type stays open so a protocol added later is not a
36
+ * type error. `GET /v1/protocols` (`tw.protocols()`) is the live list.
37
+ */
38
+ export type ProtocolKey = 'uniswap-v4' | (string & {});
39
+ /** A position id (an ERC-721 token id): digits. A `bigint` or `number` is sent as its decimal string. */
40
+ export type PositionId = string | bigint | number;
41
+ /** Dotted field paths, e.g. `['positionId', 'metrics.apr']` or `'positionId,metrics.apr'`. At most 60. */
42
+ export type Fields = string | readonly string[];
43
+ type RawQuery<Op extends keyof operations> = NonNullable<operations[Op]['parameters']['query']>;
44
+ /** `Omit` that keeps the named keys of a type with an index signature (the built-in one drops them). */
45
+ export type OmitKeys<T, K extends PropertyKey> = {
46
+ [P in keyof T as P extends K ? never : P]: T[P];
47
+ };
48
+ type Widen<Q> = OmitKeys<Q, 'protocol' | 'fields' | 'format'> & ('protocol' extends keyof Q ? {
49
+ protocol?: ProtocolKey;
50
+ } : unknown) & ('fields' extends keyof Q ? {
51
+ fields?: Fields;
52
+ } : unknown);
53
+ export type PositionsListQuery = Widen<RawQuery<'positions.list'>>;
54
+ export type PositionsBatchQuery = OmitKeys<Widen<RawQuery<'positions.batch'>>, 'ids'> & {
55
+ /** 1 to 100 ids (`batch`), or any number (`batchAll`). Duplicates are dropped. */
56
+ ids: readonly PositionId[] | string;
57
+ };
58
+ export type PositionDetailQuery = Widen<RawQuery<'positions.detail'>>;
59
+ export type PositionTransactionsQuery = Widen<RawQuery<'positions.transactions'>>;
60
+ export type PositionChartsQuery = Widen<RawQuery<'positions.charts'>>;
61
+ export type PoolsListQuery = Widen<RawQuery<'pools.list'>>;
62
+ export type PoolDetailQuery = Widen<RawQuery<'pools.detail'>>;
63
+ export type PoolChartsQuery = Widen<RawQuery<'pools.charts'>>;
64
+ export type TokenQuery = Widen<RawQuery<'tokens.detail'>>;
65
+ export type WalletSummaryQuery = Widen<RawQuery<'wallets.summary'>>;
66
+ export type HooksListQuery = Widen<RawQuery<'hooks.list'>>;
67
+ /** Every property optional, all the way down. */
68
+ export type DeepPartial<T> = T extends readonly (infer U)[] ? DeepPartial<U>[] : T extends object ? {
69
+ [K in keyof T]?: DeepPartial<T[K]>;
70
+ } : T;
71
+ /**
72
+ * True when the query asks for less than the whole row: a `fields` list, or `view: 'compact'`. The server then
73
+ * sends only what was asked for, so the rows are typed `DeepPartial`.
74
+ */
75
+ export type IsProjected<Q> = Q extends {
76
+ fields: Fields;
77
+ } ? true : Q extends {
78
+ view: 'compact';
79
+ } ? true : false;
80
+ type ElementOf<A> = A extends readonly (infer U)[] ? U : never;
81
+ /** `L` with the rows under `K` made `DeepPartial` when `Q` projects them. */
82
+ export type WithRows<L, K extends keyof L, Q> = IsProjected<Q> extends true ? OmitKeys<L, K> & {
83
+ [P in K]: DeepPartial<ElementOf<L[P]>>[];
84
+ } : L;
85
+ /** `T` made `DeepPartial` when `Q` projects it. */
86
+ export type Shaped<T, Q> = IsProjected<Q> extends true ? DeepPartial<T> : T;
87
+ /** One row of a list, as `Q` shapes it. */
88
+ export type RowOf<T, Q> = IsProjected<Q> extends true ? DeepPartial<T> : T;
89
+ /**
90
+ * Limits for the paging iterators. Every page is a metered request, so the iterators fetch a page only when the
91
+ * previous one has been consumed: `break` stops the spending.
92
+ */
93
+ export interface PagingOptions {
94
+ /** Stop after this many pages. */
95
+ maxPages?: number;
96
+ /** Stop after this many rows (`iterate*` only). */
97
+ maxItems?: number;
98
+ }
99
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ /** The package version, sent in `User-Agent`. `test/version.spec.ts` holds it to `package.json`. */
2
+ export declare const VERSION = "0.1.0";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VERSION = void 0;
4
+ /** The package version, sent in `User-Agent`. `test/version.spec.ts` holds it to `package.json`. */
5
+ exports.VERSION = '0.1.0';
@@ -0,0 +1,22 @@
1
+ import type { ResponseMeta } from './transport.js';
2
+ export interface WithMeta<T> {
3
+ data: T;
4
+ meta: ResponseMeta;
5
+ }
6
+ /**
7
+ * What every SDK method returns. `await` it for the data; call `.withMeta()` for the data plus the response
8
+ * metadata (rate-limit and quota headers, units charged on a batch, the status, how many retries it took).
9
+ *
10
+ * `then` / `catch` / `finally` are delegated to a plain promise of the data, so chaining never builds another
11
+ * `APIPromise` (the usual trap of subclassing `Promise`).
12
+ */
13
+ export declare class APIPromise<T> extends Promise<T> {
14
+ #private;
15
+ constructor(raw: Promise<WithMeta<T>>);
16
+ static get [Symbol.species](): PromiseConstructor;
17
+ /** The data and the response metadata. */
18
+ withMeta(): Promise<WithMeta<T>>;
19
+ then<R1 = T, R2 = never>(onfulfilled?: ((value: T) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
20
+ catch<R = never>(onrejected?: ((reason: unknown) => R | PromiseLike<R>) | null): Promise<T | R>;
21
+ finally(onfinally?: (() => void) | null): Promise<T>;
22
+ }