@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.
Files changed (72) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +203 -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 +123 -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 +133 -0
  10. package/dist/cjs/errors.js +242 -0
  11. package/dist/cjs/generated/openapi.d.ts +1949 -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 +33 -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 +59 -0
  25. package/dist/cjs/resources/positions.js +187 -0
  26. package/dist/cjs/resources/tokens.d.ts +19 -0
  27. package/dist/cjs/resources/tokens.js +28 -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 +84 -0
  31. package/dist/cjs/routes.js +45 -0
  32. package/dist/cjs/transport.d.ts +92 -0
  33. package/dist/cjs/transport.js +314 -0
  34. package/dist/cjs/types.d.ts +112 -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 +119 -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 +133 -0
  45. package/dist/esm/errors.js +221 -0
  46. package/dist/esm/generated/openapi.d.ts +1949 -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 +59 -0
  59. package/dist/esm/resources/positions.js +183 -0
  60. package/dist/esm/resources/tokens.d.ts +19 -0
  61. package/dist/esm/resources/tokens.js +24 -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 +84 -0
  65. package/dist/esm/routes.js +41 -0
  66. package/dist/esm/transport.d.ts +92 -0
  67. package/dist/esm/transport.js +303 -0
  68. package/dist/esm/types.d.ts +112 -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,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,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.1";
@@ -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.1';
@@ -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
+ }
@@ -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 | undefined;
16
+ /** Default `https://api.tickwise.xyz`. */
17
+ baseUrl?: string | undefined;
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 | undefined;
20
+ /** Per attempt, in milliseconds. Default 30000. */
21
+ timeoutMs?: number | undefined;
22
+ /**
23
+ * Retries of failures the API did not charge: a 429 rate-limit, 503, or a connection that never opened (a free
24
+ * route also retries a timeout, a dropped connection, a 502 and a 504). Default 2; 0 turns them off.
25
+ */
26
+ maxRetries?: number | undefined;
27
+ /** A `Retry-After` longer than this (seconds) is thrown as the error instead of waited out. Default 60. */
28
+ maxRetryAfterSec?: number | undefined;
29
+ /** Refuse a response body larger than this many bytes. Off by default. */
30
+ maxBodyBytes?: number | undefined;
31
+ /** A `fetch` to use instead of the global one (tests, proxies, instrumentation). */
32
+ fetch?: typeof fetch | undefined;
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,119 @@
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
+ // An empty value (an environment variable set to nothing) means the default, as for `apiKey` and `keyHeader`.
43
+ const baseUrl = (options.baseUrl?.trim() || DEFAULT_BASE_URL).replace(/\/+$/, '');
44
+ let parsed;
45
+ try {
46
+ parsed = new URL(baseUrl);
47
+ }
48
+ catch {
49
+ throw new TypeError(`Tickwise: \`baseUrl\` is not a valid URL: ${baseUrl}`);
50
+ }
51
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
52
+ throw new TypeError('Tickwise: `baseUrl` must start with https:// or http://');
53
+ }
54
+ if (parsed.search || parsed.hash || parsed.username || parsed.password) {
55
+ throw new TypeError('Tickwise: `baseUrl` must not carry a query, fragment or credentials');
56
+ }
57
+ // Every route path starts with /v1, so a base URL that already ends in it would send every call to /v1/v1/....
58
+ if (/\/v1$/i.test(parsed.pathname.replace(/\/+$/, ''))) {
59
+ throw new TypeError('Tickwise: `baseUrl` is the API origin without `/v1` (for example https://api.tickwise.xyz)');
60
+ }
61
+ const f = options.fetch ?? globalThis.fetch;
62
+ if (typeof f !== 'function') {
63
+ throw new TypeError('Tickwise: no global `fetch` on this runtime; pass one as `fetch` (Node 20.3+ has it built in)');
64
+ }
65
+ const apiKey = options.apiKey?.trim() || envKey();
66
+ // Checked here so a typo fails once, clearly, instead of every request failing inside `fetch`. The key is
67
+ // never put in the message.
68
+ if (apiKey !== undefined && !API_KEY.test(apiKey)) {
69
+ 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)');
70
+ }
71
+ const keyHeader = options.keyHeader?.trim() || DEFAULT_KEY_HEADER;
72
+ if (!HEADER_NAME.test(keyHeader))
73
+ throw new TypeError(`Tickwise: \`keyHeader\` is not a valid header name: ${keyHeader}`);
74
+ if (apiKey && isBrowser() && !warnedBrowserKey) {
75
+ warnedBrowserKey = true;
76
+ console.warn('Tickwise: an API key is in use in a browser, where every visitor can read it. Use a browser key with your ' +
77
+ 'origins registered (a server key is refused here with 403), or call the API from your own server.');
78
+ }
79
+ this.#baseUrl = baseUrl;
80
+ const transport = new Transport({
81
+ apiKey,
82
+ baseUrl,
83
+ keyHeader,
84
+ timeoutMs: positive('timeoutMs', options.timeoutMs, DEFAULT_TIMEOUT_MS),
85
+ maxRetries: Math.floor(positive('maxRetries', options.maxRetries, DEFAULT_MAX_RETRIES, true)),
86
+ maxRetryAfterSec: positive('maxRetryAfterSec', options.maxRetryAfterSec, DEFAULT_MAX_RETRY_AFTER_SEC, true),
87
+ maxBodyBytes: options.maxBodyBytes === undefined ? undefined : positive('maxBodyBytes', options.maxBodyBytes, 0),
88
+ // Called unbound: a native `fetch` called as a method of another object throws "Illegal invocation" in browsers.
89
+ fetch: (input, init) => f(input, init),
90
+ });
91
+ this.positions = new Positions(transport);
92
+ this.pools = new Pools(transport);
93
+ this.tokens = new Tokens(transport);
94
+ this.wallets = new Wallets(transport);
95
+ this.hooks = new Hooks(transport);
96
+ this.pricing = new Pricing(transport);
97
+ this.#meta = new Meta(transport);
98
+ }
99
+ /** The API base URL this client calls. */
100
+ get baseUrl() {
101
+ return this.#baseUrl;
102
+ }
103
+ /** `GET /v1/chains` (free): the chains served right now. The live list of valid `chainId`s. */
104
+ chains(options) {
105
+ return this.#meta.chains(options);
106
+ }
107
+ /** `GET /v1/protocols` (free): the protocols served and the chains each is live on. */
108
+ protocols(options) {
109
+ return this.#meta.protocols(options);
110
+ }
111
+ /** `GET /v1/plans` (free): the plans on sale. */
112
+ plans(options) {
113
+ return this.#meta.plans(options);
114
+ }
115
+ /** `GET /v1/stats` (free): headline counts of everything indexed. */
116
+ stats(options) {
117
+ return this.#meta.stats(options);
118
+ }
119
+ }
@@ -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;
@@ -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,133 @@
1
+ /**
2
+ * Every error from the API or the network is a `TickwiseError`. The exceptions: a bad option or argument is a
3
+ * `TypeError` (thrown, or as the rejection of the call), and a call cancelled through `signal` rejects with the
4
+ * signal's reason (the platform's `AbortError` by default). Branch on `instanceof` or on `kind`, never on `message`: the API's
5
+ * error bodies are `{ error: string }` with no machine code, and their text can change. `kind` is derived from the
6
+ * status code and, for a 429, from the `X-RateLimit-Reason` header.
7
+ */
8
+ export type TickwiseErrorKind = 'bad_request' | 'authentication' | 'permission_denied' | 'not_found' | 'rate_limited' | 'quota_exceeded' | 'unavailable' | 'api_error' | 'redirect' | 'connection' | 'timeout' | 'incomplete';
9
+ export interface TickwiseErrorInit {
10
+ status?: number | undefined;
11
+ body?: unknown;
12
+ headers?: Headers | undefined;
13
+ retryAfterSec?: number | undefined;
14
+ url?: string | undefined;
15
+ cause?: unknown;
16
+ }
17
+ export declare class TickwiseError extends Error {
18
+ readonly kind: TickwiseErrorKind;
19
+ /** HTTP status, when the API answered. */
20
+ readonly status: number | undefined;
21
+ /** The parsed JSON body (or the text, when it was not JSON). */
22
+ readonly body: unknown;
23
+ readonly headers: Headers | undefined;
24
+ /** Seconds the API asked to wait (`Retry-After`), on a 429 or 503. */
25
+ readonly retryAfterSec: number | undefined;
26
+ /** The request URL (it never contains the key). */
27
+ readonly url: string | undefined;
28
+ constructor(kind: TickwiseErrorKind, message: string, init?: TickwiseErrorInit);
29
+ }
30
+ /** The API answered with a status the SDK does not treat as success. */
31
+ export declare class APIError extends TickwiseError {
32
+ constructor(kind: TickwiseErrorKind, message: string, init?: TickwiseErrorInit);
33
+ }
34
+ /** 400: a parameter is malformed or unknown. Costs no units. */
35
+ export declare class BadRequestError extends APIError {
36
+ constructor(message: string, init?: TickwiseErrorInit);
37
+ }
38
+ /** 401: the key is missing, unknown or revoked, or the account is suspended. */
39
+ export declare class AuthenticationError extends APIError {
40
+ constructor(message: string, init?: TickwiseErrorInit);
41
+ }
42
+ /** 403: a server key sent from a browser, or a browser key from an origin that is not registered. */
43
+ export declare class PermissionDeniedError extends APIError {
44
+ constructor(message: string, init?: TickwiseErrorInit);
45
+ }
46
+ /** 404: no such position, pool or token on that chain and protocol. */
47
+ export declare class NotFoundError extends APIError {
48
+ constructor(message: string, init?: TickwiseErrorInit);
49
+ }
50
+ /** 429, either limit. Catch this to handle both; the subclasses say which. */
51
+ export declare class TooManyRequestsError extends APIError {
52
+ constructor(kind: 'rate_limited' | 'quota_exceeded', message: string, init?: TickwiseErrorInit);
53
+ }
54
+ /** 429 from the 60-second burst limit. Retried automatically; wait `retryAfterSec`. */
55
+ export declare class RateLimitError extends TooManyRequestsError {
56
+ constructor(message: string, init?: TickwiseErrorInit);
57
+ }
58
+ /** 429 from the monthly unit quota. Never retried: nothing changes until the quota resets or the plan is upgraded. */
59
+ export declare class QuotaExceededError extends TooManyRequestsError {
60
+ constructor(message: string, init?: TickwiseErrorInit);
61
+ }
62
+ /** 503: a read did not finish in time. Retried automatically after `Retry-After`. Costs no units. */
63
+ export declare class ServiceUnavailableError extends APIError {
64
+ constructor(message: string, init?: TickwiseErrorInit);
65
+ }
66
+ /** No answer: DNS, refused or reset connection, TLS. */
67
+ export declare class ConnectionError extends TickwiseError {
68
+ /**
69
+ * True when the request certainly never reached the API (the name did not resolve, or the connection was
70
+ * refused or could not be opened). Only then is a metered call retried: a connection lost after the request was
71
+ * sent may have been served, and charged.
72
+ */
73
+ readonly connectFailed: boolean;
74
+ constructor(message: string, init?: TickwiseErrorInit & {
75
+ connectFailed?: boolean;
76
+ });
77
+ }
78
+ /** The attempt took longer than `timeoutMs`. */
79
+ export declare class TimeoutError extends TickwiseError {
80
+ constructor(message: string, init?: TickwiseErrorInit);
81
+ }
82
+ /**
83
+ * A helper that makes several requests (`positions.batchAll`, `positions.iterateTransactions`) could not get
84
+ * everything. What it did get is on the error; `cause` is the failure that stopped it, when one did.
85
+ */
86
+ export declare class IncompleteError extends TickwiseError {
87
+ constructor(message: string, init?: TickwiseErrorInit);
88
+ }
89
+ /**
90
+ * `positions.batchAll` stopped on a failed chunk after earlier chunks were served, and charged. The served rows are
91
+ * in `data`; pass `remainingIds` to `batchAll` again to finish without paying for the served ones twice. `cause` is
92
+ * the chunk's error (a `QuotaExceededError`, a `TimeoutError`, the signal's reason after an abort, ...).
93
+ */
94
+ export declare class BatchAllIncompleteError<T = unknown> extends IncompleteError {
95
+ /** The chunks served before the failure, merged as `batchAll` returns them. */
96
+ readonly data: T;
97
+ /** Units the served chunks were charged; undefined when a chunk's answer did not say. */
98
+ readonly unitsCharged: number | undefined;
99
+ /** The ids not served: the failed chunk's and every later one, in order. */
100
+ readonly remainingIds: string[];
101
+ constructor(message: string, init: TickwiseErrorInit & {
102
+ data: T;
103
+ unitsCharged: number | undefined;
104
+ remainingIds: string[];
105
+ });
106
+ }
107
+ /** Why the API said a position's transaction list is not complete (the flags on its last page). */
108
+ export type TransactionsIncompleteReason = 'transactionsPartial' | 'transactionsTruncated' | 'transactionsDegraded';
109
+ /**
110
+ * `positions.iterateTransactions` reached the oldest transaction the API had, but the last page said the list is not
111
+ * complete: `transactionsPartial` (only the newest transactions were ready; ask again in a few seconds),
112
+ * `transactionsTruncated` (the history is longer than the API reads; the oldest are missing) or
113
+ * `transactionsDegraded` (the list could not be read in full). Every row the API had was yielded before this is
114
+ * thrown.
115
+ */
116
+ export declare class TransactionsIncompleteError extends IncompleteError {
117
+ readonly reasons: TransactionsIncompleteReason[];
118
+ /** How many transactions were yielded. */
119
+ readonly yielded: number;
120
+ constructor(message: string, init: TickwiseErrorInit & {
121
+ reasons: TransactionsIncompleteReason[];
122
+ yielded: number;
123
+ });
124
+ }
125
+ /** The most useful text an error body carries: Nest validation detail first, then `error`. */
126
+ export declare function errorMessage(body: unknown, status: number): string;
127
+ /**
128
+ * `Retry-After` in whole seconds: the API sends seconds; a gateway may send an HTTP date, read as the seconds from
129
+ * now (0 when it has passed). Else the 429 body's `retryAfterSec`.
130
+ */
131
+ export declare function retryAfterOf(headers: Headers, body: unknown, now?: number): number | undefined;
132
+ /** The error for a non-2xx answer. */
133
+ export declare function errorFromResponse(status: number, headers: Headers, body: unknown, url: string): APIError;