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