@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.
- package/LICENSE +661 -0
- package/README.md +185 -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 +118 -0
- package/dist/cjs/csv.d.ts +37 -0
- package/dist/cjs/csv.js +69 -0
- package/dist/cjs/errors.d.ts +85 -0
- package/dist/cjs/errors.js +181 -0
- package/dist/cjs/generated/openapi.d.ts +1821 -0
- package/dist/cjs/generated/openapi.js +6 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +30 -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 +45 -0
- package/dist/cjs/resources/positions.js +133 -0
- package/dist/cjs/resources/tokens.d.ts +13 -0
- package/dist/cjs/resources/tokens.js +20 -0
- package/dist/cjs/resources/wallets.d.ts +11 -0
- package/dist/cjs/resources/wallets.js +14 -0
- package/dist/cjs/routes.d.ts +80 -0
- package/dist/cjs/routes.js +40 -0
- package/dist/cjs/transport.d.ts +91 -0
- package/dist/cjs/transport.js +310 -0
- package/dist/cjs/types.d.ts +99 -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 +114 -0
- package/dist/esm/csv.d.ts +37 -0
- package/dist/esm/csv.js +64 -0
- package/dist/esm/errors.d.ts +85 -0
- package/dist/esm/errors.js +163 -0
- package/dist/esm/generated/openapi.d.ts +1821 -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 +45 -0
- package/dist/esm/resources/positions.js +129 -0
- package/dist/esm/resources/tokens.d.ts +13 -0
- package/dist/esm/resources/tokens.js +16 -0
- package/dist/esm/resources/wallets.d.ts +11 -0
- package/dist/esm/resources/wallets.js +10 -0
- package/dist/esm/routes.d.ts +80 -0
- package/dist/esm/routes.js +36 -0
- package/dist/esm/transport.d.ts +91 -0
- package/dist/esm/transport.js +299 -0
- package/dist/esm/types.d.ts +99 -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,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every SDK method returns. `await` it for the data; call `.withMeta()` for the data plus the response
|
|
3
|
+
* metadata (rate-limit and quota headers, units charged on a batch, the status, how many retries it took).
|
|
4
|
+
*
|
|
5
|
+
* `then` / `catch` / `finally` are delegated to a plain promise of the data, so chaining never builds another
|
|
6
|
+
* `APIPromise` (the usual trap of subclassing `Promise`).
|
|
7
|
+
*/
|
|
8
|
+
export class APIPromise extends Promise {
|
|
9
|
+
#raw;
|
|
10
|
+
#data;
|
|
11
|
+
constructor(raw) {
|
|
12
|
+
super((resolve) => {
|
|
13
|
+
// The base promise is never used; it is settled so it can never be an unhandled rejection.
|
|
14
|
+
resolve(undefined);
|
|
15
|
+
});
|
|
16
|
+
this.#raw = raw;
|
|
17
|
+
}
|
|
18
|
+
// Promise subclass methods (`then`, `Promise.resolve(apiPromise)`) look this up; plain promises are what they build.
|
|
19
|
+
static get [Symbol.species]() {
|
|
20
|
+
return Promise;
|
|
21
|
+
}
|
|
22
|
+
/** The data and the response metadata. */
|
|
23
|
+
withMeta() {
|
|
24
|
+
return this.#raw;
|
|
25
|
+
}
|
|
26
|
+
#parsed() {
|
|
27
|
+
this.#data ??= this.#raw.then((r) => r.data);
|
|
28
|
+
return this.#data;
|
|
29
|
+
}
|
|
30
|
+
then(onfulfilled, onrejected) {
|
|
31
|
+
return this.#parsed().then(onfulfilled, onrejected);
|
|
32
|
+
}
|
|
33
|
+
catch(onrejected) {
|
|
34
|
+
return this.#parsed().catch(onrejected);
|
|
35
|
+
}
|
|
36
|
+
finally(onfinally) {
|
|
37
|
+
return this.#parsed().finally(onfinally);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { APIPromise } from './api-promise.js';
|
|
2
|
+
import { Hooks } from './resources/hooks.js';
|
|
3
|
+
import { Pricing } from './resources/meta.js';
|
|
4
|
+
import { Pools } from './resources/pools.js';
|
|
5
|
+
import { Positions } from './resources/positions.js';
|
|
6
|
+
import { Tokens } from './resources/tokens.js';
|
|
7
|
+
import { Wallets } from './resources/wallets.js';
|
|
8
|
+
import { type RequestOptions } from './transport.js';
|
|
9
|
+
import type { Chain, PlanList, Protocol, Stats } from './types.js';
|
|
10
|
+
export interface TickwiseOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Your API key from the Tickwise portal. When omitted, `TICKWISE_API_KEY` is read from the environment (on
|
|
13
|
+
* runtimes that have `process.env`). Only metered routes send it; the free routes never do.
|
|
14
|
+
*/
|
|
15
|
+
apiKey?: string;
|
|
16
|
+
/** Default `https://api.tickwise.xyz`. */
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
/** The header the key goes in. Default `KC-APIKey`; change it only for an API run with another `API_KEY_HEADER`. */
|
|
19
|
+
keyHeader?: string;
|
|
20
|
+
/** Per attempt, in milliseconds. Default 30000. */
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
/**
|
|
23
|
+
* Retries of failures the API did not charge: a 429 rate-limit, 503, 502, or a connection that never opened (a free
|
|
24
|
+
* route also retries a timeout, a dropped connection and a 504). Default 2; 0 turns them off.
|
|
25
|
+
*/
|
|
26
|
+
maxRetries?: number;
|
|
27
|
+
/** A `Retry-After` longer than this (seconds) is thrown as the error instead of waited out. Default 60. */
|
|
28
|
+
maxRetryAfterSec?: number;
|
|
29
|
+
/** Refuse a response body larger than this many bytes. Off by default. */
|
|
30
|
+
maxBodyBytes?: number;
|
|
31
|
+
/** A `fetch` to use instead of the global one (tests, proxies, instrumentation). */
|
|
32
|
+
fetch?: typeof fetch;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The Tickwise API client.
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* const tw = new Tickwise({ apiKey: process.env.TICKWISE_API_KEY });
|
|
39
|
+
* const { pools } = await tw.pools.list({ chainId: 1, sort: 'fees', limit: 10 });
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* Call it from your server or an edge function. A server key is refused (403) on any request that carries an
|
|
43
|
+
* `Origin` header, which every browser request does; in a browser use a browser key with your origins registered.
|
|
44
|
+
*/
|
|
45
|
+
export declare class Tickwise {
|
|
46
|
+
#private;
|
|
47
|
+
readonly positions: Positions;
|
|
48
|
+
readonly pools: Pools;
|
|
49
|
+
readonly tokens: Tokens;
|
|
50
|
+
readonly wallets: Wallets;
|
|
51
|
+
readonly hooks: Hooks;
|
|
52
|
+
readonly pricing: Pricing;
|
|
53
|
+
constructor(options?: TickwiseOptions);
|
|
54
|
+
/** The API base URL this client calls. */
|
|
55
|
+
get baseUrl(): string;
|
|
56
|
+
/** `GET /v1/chains` (free): the chains served right now. The live list of valid `chainId`s. */
|
|
57
|
+
chains(options?: RequestOptions): APIPromise<Chain[]>;
|
|
58
|
+
/** `GET /v1/protocols` (free): the protocols served and the chains each is live on. */
|
|
59
|
+
protocols(options?: RequestOptions): APIPromise<Protocol[]>;
|
|
60
|
+
/** `GET /v1/plans` (free): the plans on sale. */
|
|
61
|
+
plans(options?: RequestOptions): APIPromise<PlanList>;
|
|
62
|
+
/** `GET /v1/stats` (free): headline counts of everything indexed. */
|
|
63
|
+
stats(options?: RequestOptions): APIPromise<Stats>;
|
|
64
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { Hooks } from './resources/hooks.js';
|
|
2
|
+
import { Meta, Pricing } from './resources/meta.js';
|
|
3
|
+
import { Pools } from './resources/pools.js';
|
|
4
|
+
import { Positions } from './resources/positions.js';
|
|
5
|
+
import { Tokens } from './resources/tokens.js';
|
|
6
|
+
import { Wallets } from './resources/wallets.js';
|
|
7
|
+
import { DEFAULT_BASE_URL, DEFAULT_KEY_HEADER, DEFAULT_MAX_RETRIES, DEFAULT_MAX_RETRY_AFTER_SEC, DEFAULT_TIMEOUT_MS, checkNumber, isBrowser, Transport, } from './transport.js';
|
|
8
|
+
let warnedBrowserKey = false;
|
|
9
|
+
function envKey() {
|
|
10
|
+
const p = globalThis.process;
|
|
11
|
+
const v = p?.env?.TICKWISE_API_KEY;
|
|
12
|
+
return v && v.trim() ? v.trim() : undefined;
|
|
13
|
+
}
|
|
14
|
+
function positive(name, v, fallback, allowZero = false) {
|
|
15
|
+
return v === undefined ? fallback : checkNumber(name, v, allowZero);
|
|
16
|
+
}
|
|
17
|
+
/** An HTTP header name (RFC 9110 token). */
|
|
18
|
+
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
19
|
+
/** Keys are printable ASCII with no spaces. Anything else would make every request fail inside `fetch`. */
|
|
20
|
+
const API_KEY = /^[\x21-\x7E]+$/;
|
|
21
|
+
/**
|
|
22
|
+
* The Tickwise API client.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* const tw = new Tickwise({ apiKey: process.env.TICKWISE_API_KEY });
|
|
26
|
+
* const { pools } = await tw.pools.list({ chainId: 1, sort: 'fees', limit: 10 });
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* Call it from your server or an edge function. A server key is refused (403) on any request that carries an
|
|
30
|
+
* `Origin` header, which every browser request does; in a browser use a browser key with your origins registered.
|
|
31
|
+
*/
|
|
32
|
+
export class Tickwise {
|
|
33
|
+
positions;
|
|
34
|
+
pools;
|
|
35
|
+
tokens;
|
|
36
|
+
wallets;
|
|
37
|
+
hooks;
|
|
38
|
+
pricing;
|
|
39
|
+
#meta;
|
|
40
|
+
#baseUrl;
|
|
41
|
+
constructor(options = {}) {
|
|
42
|
+
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).trim().replace(/\/+$/, '');
|
|
43
|
+
let parsed;
|
|
44
|
+
try {
|
|
45
|
+
parsed = new URL(baseUrl);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new TypeError(`Tickwise: \`baseUrl\` is not a valid URL: ${baseUrl}`);
|
|
49
|
+
}
|
|
50
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
51
|
+
throw new TypeError('Tickwise: `baseUrl` must start with https:// or http://');
|
|
52
|
+
}
|
|
53
|
+
if (parsed.search || parsed.hash || parsed.username || parsed.password) {
|
|
54
|
+
throw new TypeError('Tickwise: `baseUrl` must not carry a query, fragment or credentials');
|
|
55
|
+
}
|
|
56
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
57
|
+
if (typeof f !== 'function') {
|
|
58
|
+
throw new TypeError('Tickwise: no global `fetch` on this runtime; pass one as `fetch` (Node 20.3+ has it built in)');
|
|
59
|
+
}
|
|
60
|
+
const apiKey = options.apiKey?.trim() || envKey();
|
|
61
|
+
// Checked here so a typo fails once, clearly, instead of every request failing inside `fetch`. The key is
|
|
62
|
+
// never put in the message.
|
|
63
|
+
if (apiKey !== undefined && !API_KEY.test(apiKey)) {
|
|
64
|
+
throw new TypeError('Tickwise: `apiKey` has a character an API key cannot contain (a space, or a non-ASCII character such as a curly quote)');
|
|
65
|
+
}
|
|
66
|
+
const keyHeader = options.keyHeader?.trim() || DEFAULT_KEY_HEADER;
|
|
67
|
+
if (!HEADER_NAME.test(keyHeader))
|
|
68
|
+
throw new TypeError(`Tickwise: \`keyHeader\` is not a valid header name: ${keyHeader}`);
|
|
69
|
+
if (apiKey && isBrowser() && !warnedBrowserKey) {
|
|
70
|
+
warnedBrowserKey = true;
|
|
71
|
+
console.warn('Tickwise: an API key is in use in a browser, where every visitor can read it. Use a browser key with your ' +
|
|
72
|
+
'origins registered (a server key is refused here with 403), or call the API from your own server.');
|
|
73
|
+
}
|
|
74
|
+
this.#baseUrl = baseUrl;
|
|
75
|
+
const transport = new Transport({
|
|
76
|
+
apiKey,
|
|
77
|
+
baseUrl,
|
|
78
|
+
keyHeader,
|
|
79
|
+
timeoutMs: positive('timeoutMs', options.timeoutMs, DEFAULT_TIMEOUT_MS),
|
|
80
|
+
maxRetries: Math.floor(positive('maxRetries', options.maxRetries, DEFAULT_MAX_RETRIES, true)),
|
|
81
|
+
maxRetryAfterSec: positive('maxRetryAfterSec', options.maxRetryAfterSec, DEFAULT_MAX_RETRY_AFTER_SEC, true),
|
|
82
|
+
maxBodyBytes: options.maxBodyBytes === undefined ? undefined : positive('maxBodyBytes', options.maxBodyBytes, 0),
|
|
83
|
+
// Called unbound: a native `fetch` called as a method of another object throws "Illegal invocation" in browsers.
|
|
84
|
+
fetch: (input, init) => f(input, init),
|
|
85
|
+
});
|
|
86
|
+
this.positions = new Positions(transport);
|
|
87
|
+
this.pools = new Pools(transport);
|
|
88
|
+
this.tokens = new Tokens(transport);
|
|
89
|
+
this.wallets = new Wallets(transport);
|
|
90
|
+
this.hooks = new Hooks(transport);
|
|
91
|
+
this.pricing = new Pricing(transport);
|
|
92
|
+
this.#meta = new Meta(transport);
|
|
93
|
+
}
|
|
94
|
+
/** The API base URL this client calls. */
|
|
95
|
+
get baseUrl() {
|
|
96
|
+
return this.#baseUrl;
|
|
97
|
+
}
|
|
98
|
+
/** `GET /v1/chains` (free): the chains served right now. The live list of valid `chainId`s. */
|
|
99
|
+
chains(options) {
|
|
100
|
+
return this.#meta.chains(options);
|
|
101
|
+
}
|
|
102
|
+
/** `GET /v1/protocols` (free): the protocols served and the chains each is live on. */
|
|
103
|
+
protocols(options) {
|
|
104
|
+
return this.#meta.protocols(options);
|
|
105
|
+
}
|
|
106
|
+
/** `GET /v1/plans` (free): the plans on sale. */
|
|
107
|
+
plans(options) {
|
|
108
|
+
return this.#meta.plans(options);
|
|
109
|
+
}
|
|
110
|
+
/** `GET /v1/stats` (free): headline counts of everything indexed. */
|
|
111
|
+
stats(options) {
|
|
112
|
+
return this.#meta.stats(options);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** The paging of one CSV page, read from the `X-*` headers (the CSV body has no envelope). */
|
|
2
|
+
export interface CsvPagination {
|
|
3
|
+
page: number;
|
|
4
|
+
limit: number;
|
|
5
|
+
/** Absent when the API does not know it yet. */
|
|
6
|
+
total?: number;
|
|
7
|
+
totalPages?: number;
|
|
8
|
+
/** Always exact. Page until it is false. */
|
|
9
|
+
hasMore: boolean;
|
|
10
|
+
/** `total` is a floor. */
|
|
11
|
+
totalCapped?: boolean;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* One page of a list as CSV. `csv` is the text exactly as served (RFC 4180, CRLF line endings, a header row of
|
|
15
|
+
* dotted JSON paths, no byte-order mark). The SDK does not parse it.
|
|
16
|
+
*/
|
|
17
|
+
export interface CsvPage {
|
|
18
|
+
csv: string;
|
|
19
|
+
/** From `Content-Disposition`, e.g. `tickwise-pools-1-p1.csv`. */
|
|
20
|
+
filename?: string;
|
|
21
|
+
pagination: CsvPagination;
|
|
22
|
+
/** All-chains reads only: some chains could not be read and are left out (the call is refunded). */
|
|
23
|
+
partial?: {
|
|
24
|
+
missingChains: number[];
|
|
25
|
+
};
|
|
26
|
+
/** The rows are older than usual. */
|
|
27
|
+
stale?: {
|
|
28
|
+
dataAsOf?: string;
|
|
29
|
+
};
|
|
30
|
+
/** Pools only: some holder counts are not in yet. */
|
|
31
|
+
countsPending?: boolean;
|
|
32
|
+
}
|
|
33
|
+
export declare function filenameOf(disposition: string | null): string | undefined;
|
|
34
|
+
/** Whether a CSV page has any data row below its header row. The CSV page iterators stop on a page that has none. */
|
|
35
|
+
export declare function csvHasRows(text: string): boolean;
|
|
36
|
+
/** Reads a CSV answer. Throws when it is not one (a server that ignored `format=csv`). */
|
|
37
|
+
export declare function csvPageOf(text: string, headers: Headers, url: string): CsvPage;
|
package/dist/esm/csv.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { APIError } from './errors.js';
|
|
2
|
+
function int(h, name) {
|
|
3
|
+
const v = h.get(name)?.trim();
|
|
4
|
+
if (!v || !/^\d+$/.test(v))
|
|
5
|
+
return undefined;
|
|
6
|
+
return Number(v);
|
|
7
|
+
}
|
|
8
|
+
const flag = (h, name) => h.get(name)?.trim().toLowerCase() === 'true';
|
|
9
|
+
export function filenameOf(disposition) {
|
|
10
|
+
if (!disposition)
|
|
11
|
+
return undefined;
|
|
12
|
+
const quoted = /filename="([^"]*)"/i.exec(disposition);
|
|
13
|
+
if (quoted)
|
|
14
|
+
return quoted[1] || undefined;
|
|
15
|
+
const bare = /filename=([^;]+)/i.exec(disposition);
|
|
16
|
+
return bare?.[1]?.trim() || undefined;
|
|
17
|
+
}
|
|
18
|
+
/** Whether a CSV page has any data row below its header row. The CSV page iterators stop on a page that has none. */
|
|
19
|
+
export function csvHasRows(text) {
|
|
20
|
+
const nl = text.indexOf('\n');
|
|
21
|
+
return nl !== -1 && text.slice(nl + 1).trim() !== '';
|
|
22
|
+
}
|
|
23
|
+
/** Reads a CSV answer. Throws when it is not one (a server that ignored `format=csv`). */
|
|
24
|
+
export function csvPageOf(text, headers, url) {
|
|
25
|
+
const type = headers.get('content-type') ?? '';
|
|
26
|
+
const page = int(headers, 'X-Page');
|
|
27
|
+
const limit = int(headers, 'X-Limit');
|
|
28
|
+
const hasMore = headers.get('X-Has-More')?.trim().toLowerCase();
|
|
29
|
+
if (!/text\/csv/i.test(type) || page === undefined || limit === undefined || (hasMore !== 'true' && hasMore !== 'false')) {
|
|
30
|
+
throw new APIError('api_error', 'The API did not answer with a CSV page (no text/csv body or no X-Page / X-Limit / X-Has-More headers)', {
|
|
31
|
+
headers,
|
|
32
|
+
url,
|
|
33
|
+
body: text.slice(0, 500),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
const pagination = { page, limit, hasMore: hasMore === 'true' };
|
|
37
|
+
const total = int(headers, 'X-Total-Count');
|
|
38
|
+
const totalPages = int(headers, 'X-Total-Pages');
|
|
39
|
+
if (total !== undefined)
|
|
40
|
+
pagination.total = total;
|
|
41
|
+
if (totalPages !== undefined)
|
|
42
|
+
pagination.totalPages = totalPages;
|
|
43
|
+
if (flag(headers, 'X-Total-Capped'))
|
|
44
|
+
pagination.totalCapped = true;
|
|
45
|
+
const out = { csv: text, pagination };
|
|
46
|
+
const filename = filenameOf(headers.get('content-disposition'));
|
|
47
|
+
if (filename)
|
|
48
|
+
out.filename = filename;
|
|
49
|
+
if (flag(headers, 'X-Partial')) {
|
|
50
|
+
const missingChains = (headers.get('X-Missing-Chains') ?? '')
|
|
51
|
+
.split(',')
|
|
52
|
+
.map((s) => s.trim())
|
|
53
|
+
.filter((s) => /^\d+$/.test(s))
|
|
54
|
+
.map(Number);
|
|
55
|
+
out.partial = { missingChains };
|
|
56
|
+
}
|
|
57
|
+
if (flag(headers, 'X-Stale')) {
|
|
58
|
+
const dataAsOf = headers.get('X-Data-As-Of')?.trim();
|
|
59
|
+
out.stale = dataAsOf ? { dataAsOf } : {};
|
|
60
|
+
}
|
|
61
|
+
if (flag(headers, 'X-Counts-Pending'))
|
|
62
|
+
out.countsPending = true;
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every error the SDK throws is a `TickwiseError`. Branch on `instanceof` or on `kind`, never on `message`: the API's
|
|
3
|
+
* error bodies are `{ error: string }` with no machine code, and their text can change. `kind` is derived from the
|
|
4
|
+
* status code and, for a 429, from the `X-RateLimit-Reason` header.
|
|
5
|
+
*/
|
|
6
|
+
export type TickwiseErrorKind = 'bad_request' | 'authentication' | 'permission_denied' | 'not_found' | 'rate_limited' | 'quota_exceeded' | 'unavailable' | 'api_error' | 'redirect' | 'connection' | 'timeout';
|
|
7
|
+
export interface TickwiseErrorInit {
|
|
8
|
+
status?: number;
|
|
9
|
+
body?: unknown;
|
|
10
|
+
headers?: Headers;
|
|
11
|
+
retryAfterSec?: number;
|
|
12
|
+
url?: string;
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
}
|
|
15
|
+
export declare class TickwiseError extends Error {
|
|
16
|
+
readonly kind: TickwiseErrorKind;
|
|
17
|
+
/** HTTP status, when the API answered. */
|
|
18
|
+
readonly status: number | undefined;
|
|
19
|
+
/** The parsed JSON body (or the text, when it was not JSON). */
|
|
20
|
+
readonly body: unknown;
|
|
21
|
+
readonly headers: Headers | undefined;
|
|
22
|
+
/** Seconds the API asked to wait (`Retry-After`), on a 429 or 503. */
|
|
23
|
+
readonly retryAfterSec: number | undefined;
|
|
24
|
+
/** The request URL (it never contains the key). */
|
|
25
|
+
readonly url: string | undefined;
|
|
26
|
+
constructor(kind: TickwiseErrorKind, message: string, init?: TickwiseErrorInit);
|
|
27
|
+
}
|
|
28
|
+
/** The API answered with a status the SDK does not treat as success. */
|
|
29
|
+
export declare class APIError extends TickwiseError {
|
|
30
|
+
constructor(kind: TickwiseErrorKind, message: string, init?: TickwiseErrorInit);
|
|
31
|
+
}
|
|
32
|
+
/** 400: a parameter is malformed or unknown. Costs no units. */
|
|
33
|
+
export declare class BadRequestError extends APIError {
|
|
34
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
35
|
+
}
|
|
36
|
+
/** 401: the key is missing, unknown or revoked, or the account is suspended. */
|
|
37
|
+
export declare class AuthenticationError extends APIError {
|
|
38
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
39
|
+
}
|
|
40
|
+
/** 403: a server key sent from a browser, or a browser key from an origin that is not registered. */
|
|
41
|
+
export declare class PermissionDeniedError extends APIError {
|
|
42
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
43
|
+
}
|
|
44
|
+
/** 404: no such position, pool or token on that chain and protocol. */
|
|
45
|
+
export declare class NotFoundError extends APIError {
|
|
46
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
47
|
+
}
|
|
48
|
+
/** 429, either limit. Catch this to handle both; the subclasses say which. */
|
|
49
|
+
export declare class TooManyRequestsError extends APIError {
|
|
50
|
+
constructor(kind: 'rate_limited' | 'quota_exceeded', message: string, init?: TickwiseErrorInit);
|
|
51
|
+
}
|
|
52
|
+
/** 429 from the 60-second burst limit. Retried automatically; wait `retryAfterSec`. */
|
|
53
|
+
export declare class RateLimitError extends TooManyRequestsError {
|
|
54
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
55
|
+
}
|
|
56
|
+
/** 429 from the monthly unit quota. Never retried: nothing changes until the quota resets or the plan is upgraded. */
|
|
57
|
+
export declare class QuotaExceededError extends TooManyRequestsError {
|
|
58
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
59
|
+
}
|
|
60
|
+
/** 503: a read did not finish in time. Retried automatically after `Retry-After`. Costs no units. */
|
|
61
|
+
export declare class ServiceUnavailableError extends APIError {
|
|
62
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
63
|
+
}
|
|
64
|
+
/** No answer: DNS, refused or reset connection, TLS. */
|
|
65
|
+
export declare class ConnectionError extends TickwiseError {
|
|
66
|
+
/**
|
|
67
|
+
* True when the request certainly never reached the API (the name did not resolve, or the connection was
|
|
68
|
+
* refused or could not be opened). Only then is a metered call retried: a connection lost after the request was
|
|
69
|
+
* sent may have been served, and charged.
|
|
70
|
+
*/
|
|
71
|
+
readonly connectFailed: boolean;
|
|
72
|
+
constructor(message: string, init?: TickwiseErrorInit & {
|
|
73
|
+
connectFailed?: boolean;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/** The attempt took longer than `timeoutMs`. */
|
|
77
|
+
export declare class TimeoutError extends TickwiseError {
|
|
78
|
+
constructor(message: string, init?: TickwiseErrorInit);
|
|
79
|
+
}
|
|
80
|
+
/** The most useful text an error body carries: Nest validation detail first, then `error`. */
|
|
81
|
+
export declare function errorMessage(body: unknown, status: number): string;
|
|
82
|
+
/** `Retry-After` in whole seconds (the API sends seconds), else the 429 body's `retryAfterSec`. */
|
|
83
|
+
export declare function retryAfterOf(headers: Headers, body: unknown): number | undefined;
|
|
84
|
+
/** The error for a non-2xx answer. */
|
|
85
|
+
export declare function errorFromResponse(status: number, headers: Headers, body: unknown, url: string): APIError;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every error the SDK throws is a `TickwiseError`. Branch on `instanceof` or on `kind`, never on `message`: the API's
|
|
3
|
+
* error bodies are `{ error: string }` with no machine code, and their text can change. `kind` is derived from the
|
|
4
|
+
* status code and, for a 429, from the `X-RateLimit-Reason` header.
|
|
5
|
+
*/
|
|
6
|
+
export class TickwiseError extends Error {
|
|
7
|
+
kind;
|
|
8
|
+
/** HTTP status, when the API answered. */
|
|
9
|
+
status;
|
|
10
|
+
/** The parsed JSON body (or the text, when it was not JSON). */
|
|
11
|
+
body;
|
|
12
|
+
headers;
|
|
13
|
+
/** Seconds the API asked to wait (`Retry-After`), on a 429 or 503. */
|
|
14
|
+
retryAfterSec;
|
|
15
|
+
/** The request URL (it never contains the key). */
|
|
16
|
+
url;
|
|
17
|
+
constructor(kind, message, init = {}) {
|
|
18
|
+
super(message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
19
|
+
this.name = 'TickwiseError';
|
|
20
|
+
this.kind = kind;
|
|
21
|
+
this.status = init.status;
|
|
22
|
+
this.body = init.body;
|
|
23
|
+
this.headers = init.headers;
|
|
24
|
+
this.retryAfterSec = init.retryAfterSec;
|
|
25
|
+
this.url = init.url;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** The API answered with a status the SDK does not treat as success. */
|
|
29
|
+
export class APIError extends TickwiseError {
|
|
30
|
+
constructor(kind, message, init = {}) {
|
|
31
|
+
super(kind, message, init);
|
|
32
|
+
this.name = 'APIError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** 400: a parameter is malformed or unknown. Costs no units. */
|
|
36
|
+
export class BadRequestError extends APIError {
|
|
37
|
+
constructor(message, init = {}) {
|
|
38
|
+
super('bad_request', message, init);
|
|
39
|
+
this.name = 'BadRequestError';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** 401: the key is missing, unknown or revoked, or the account is suspended. */
|
|
43
|
+
export class AuthenticationError extends APIError {
|
|
44
|
+
constructor(message, init = {}) {
|
|
45
|
+
super('authentication', message, init);
|
|
46
|
+
this.name = 'AuthenticationError';
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** 403: a server key sent from a browser, or a browser key from an origin that is not registered. */
|
|
50
|
+
export class PermissionDeniedError extends APIError {
|
|
51
|
+
constructor(message, init = {}) {
|
|
52
|
+
super('permission_denied', message, init);
|
|
53
|
+
this.name = 'PermissionDeniedError';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/** 404: no such position, pool or token on that chain and protocol. */
|
|
57
|
+
export class NotFoundError extends APIError {
|
|
58
|
+
constructor(message, init = {}) {
|
|
59
|
+
super('not_found', message, init);
|
|
60
|
+
this.name = 'NotFoundError';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** 429, either limit. Catch this to handle both; the subclasses say which. */
|
|
64
|
+
export class TooManyRequestsError extends APIError {
|
|
65
|
+
constructor(kind, message, init = {}) {
|
|
66
|
+
super(kind, message, init);
|
|
67
|
+
this.name = 'TooManyRequestsError';
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** 429 from the 60-second burst limit. Retried automatically; wait `retryAfterSec`. */
|
|
71
|
+
export class RateLimitError extends TooManyRequestsError {
|
|
72
|
+
constructor(message, init = {}) {
|
|
73
|
+
super('rate_limited', message, init);
|
|
74
|
+
this.name = 'RateLimitError';
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** 429 from the monthly unit quota. Never retried: nothing changes until the quota resets or the plan is upgraded. */
|
|
78
|
+
export class QuotaExceededError extends TooManyRequestsError {
|
|
79
|
+
constructor(message, init = {}) {
|
|
80
|
+
super('quota_exceeded', message, init);
|
|
81
|
+
this.name = 'QuotaExceededError';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/** 503: a read did not finish in time. Retried automatically after `Retry-After`. Costs no units. */
|
|
85
|
+
export class ServiceUnavailableError extends APIError {
|
|
86
|
+
constructor(message, init = {}) {
|
|
87
|
+
super('unavailable', message, init);
|
|
88
|
+
this.name = 'ServiceUnavailableError';
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** No answer: DNS, refused or reset connection, TLS. */
|
|
92
|
+
export class ConnectionError extends TickwiseError {
|
|
93
|
+
/**
|
|
94
|
+
* True when the request certainly never reached the API (the name did not resolve, or the connection was
|
|
95
|
+
* refused or could not be opened). Only then is a metered call retried: a connection lost after the request was
|
|
96
|
+
* sent may have been served, and charged.
|
|
97
|
+
*/
|
|
98
|
+
connectFailed;
|
|
99
|
+
constructor(message, init = {}) {
|
|
100
|
+
super('connection', message, init);
|
|
101
|
+
this.name = 'ConnectionError';
|
|
102
|
+
this.connectFailed = init.connectFailed ?? false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** The attempt took longer than `timeoutMs`. */
|
|
106
|
+
export class TimeoutError extends TickwiseError {
|
|
107
|
+
constructor(message, init = {}) {
|
|
108
|
+
super('timeout', message, init);
|
|
109
|
+
this.name = 'TimeoutError';
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** The most useful text an error body carries: Nest validation detail first, then `error`. */
|
|
113
|
+
export function errorMessage(body, status) {
|
|
114
|
+
if (typeof body === 'string' && body.trim())
|
|
115
|
+
return body.trim().slice(0, 500);
|
|
116
|
+
if (body && typeof body === 'object') {
|
|
117
|
+
const o = body;
|
|
118
|
+
const m = o.message;
|
|
119
|
+
if (Array.isArray(m) && m.length > 0)
|
|
120
|
+
return m.map(String).join('; ');
|
|
121
|
+
if (typeof m === 'string' && m)
|
|
122
|
+
return m;
|
|
123
|
+
if (typeof o.error === 'string' && o.error) {
|
|
124
|
+
// Some 400s name the offending value next to a generic error (an unknown `fields` path, a bad poolId).
|
|
125
|
+
const where = typeof o.path === 'string' ? o.path : typeof o.poolId === 'string' ? o.poolId : undefined;
|
|
126
|
+
return where ? `${o.error}: ${where}` : o.error;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return `HTTP ${status}`;
|
|
130
|
+
}
|
|
131
|
+
/** `Retry-After` in whole seconds (the API sends seconds), else the 429 body's `retryAfterSec`. */
|
|
132
|
+
export function retryAfterOf(headers, body) {
|
|
133
|
+
const h = headers.get('retry-after')?.trim();
|
|
134
|
+
if (h && /^\d+$/.test(h))
|
|
135
|
+
return Number(h);
|
|
136
|
+
const b = body && typeof body === 'object' ? body.retryAfterSec : undefined;
|
|
137
|
+
return typeof b === 'number' && Number.isFinite(b) && b >= 0 ? b : undefined;
|
|
138
|
+
}
|
|
139
|
+
/** The error for a non-2xx answer. */
|
|
140
|
+
export function errorFromResponse(status, headers, body, url) {
|
|
141
|
+
const message = errorMessage(body, status);
|
|
142
|
+
const init = { status, body, headers, url, retryAfterSec: retryAfterOf(headers, body) };
|
|
143
|
+
switch (status) {
|
|
144
|
+
case 400:
|
|
145
|
+
return new BadRequestError(message, init);
|
|
146
|
+
case 401:
|
|
147
|
+
return new AuthenticationError(message, init);
|
|
148
|
+
case 403:
|
|
149
|
+
return new PermissionDeniedError(message, init);
|
|
150
|
+
case 404:
|
|
151
|
+
return new NotFoundError(message, init);
|
|
152
|
+
case 429: {
|
|
153
|
+
const reason = headers.get('x-ratelimit-reason')?.trim().toLowerCase();
|
|
154
|
+
// The header is the contract; the body text is a fallback for a client that cannot read it.
|
|
155
|
+
const quota = reason === 'quota' || (!reason && /quota/i.test(message));
|
|
156
|
+
return quota ? new QuotaExceededError(message, init) : new RateLimitError(message, init);
|
|
157
|
+
}
|
|
158
|
+
case 503:
|
|
159
|
+
return new ServiceUnavailableError(message, init);
|
|
160
|
+
default:
|
|
161
|
+
return new APIError('api_error', message, init);
|
|
162
|
+
}
|
|
163
|
+
}
|