@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
package/README.md
CHANGED
|
@@ -1,3 +1,186 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tickwise/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The typed TypeScript client for the [Tickwise API](https://tickwise.xyz/docs). It indexes Uniswap v4 positions, pools, tokens, wallets and hooks across chains.
|
|
4
|
+
|
|
5
|
+
- One method for each of the 16 `/v1` routes. Request and response types are generated from the API's OpenAPI description.
|
|
6
|
+
- Paging iterators, a batch helper for any number of ids, and CSV export.
|
|
7
|
+
- Retries for the failures that cannot have been charged, honouring `Retry-After`. Typed errors you can tell apart.
|
|
8
|
+
- No dependencies. Runs on Node 20.3 or later, Bun, Deno and edge runtimes (anything with `fetch`). ESM and CommonJS.
|
|
9
|
+
|
|
10
|
+
Full guide: <https://tickwise.xyz/docs/sdk>
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install @tickwise/sdk
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Create a **server** key at <https://tickwise.xyz/portal/keys> and keep it in an environment variable. The client reads `TICKWISE_API_KEY` when you do not pass `apiKey`.
|
|
19
|
+
|
|
20
|
+
## Quick start
|
|
21
|
+
|
|
22
|
+
Use it on your server: a script, a job, a route handler or an edge function.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { Tickwise } from '@tickwise/sdk';
|
|
26
|
+
|
|
27
|
+
const tw = new Tickwise({ apiKey: process.env.TICKWISE_API_KEY });
|
|
28
|
+
|
|
29
|
+
const { pools } = await tw.pools.list({ chainId: 1, sort: 'fees', limit: 10 });
|
|
30
|
+
const position = await tw.positions.get(1, 'uniswap-v4', '123456');
|
|
31
|
+
const chains = await tw.chains(); // free, no key sent
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
A Next.js route handler (the same works on any edge runtime):
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { Tickwise } from '@tickwise/sdk';
|
|
38
|
+
|
|
39
|
+
const tw = new Tickwise({ apiKey: process.env.TICKWISE_API_KEY });
|
|
40
|
+
|
|
41
|
+
export async function GET() {
|
|
42
|
+
const { pools } = await tw.pools.list({ sort: 'tvl', limit: 20, fields: ['poolId', 'token0.symbol', 'token1.symbol', 'metrics.tvlUsd'] });
|
|
43
|
+
return Response.json(pools);
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Methods
|
|
48
|
+
|
|
49
|
+
| Method | Route |
|
|
50
|
+
| --- | --- |
|
|
51
|
+
| `positions.list(query?)` | `GET /v1/positions` |
|
|
52
|
+
| `positions.batch({ chainId, ids })` | `GET /v1/positions/batch` (at most 100 ids) |
|
|
53
|
+
| `positions.batchAll({ chainId, ids })` | the batch route, in calls of 100, merged |
|
|
54
|
+
| `positions.get(chainId, protocol, positionId, query?)` | `GET /v1/positions/{chainId}/{protocol}/{positionId}` |
|
|
55
|
+
| `positions.transactions(chainId, protocol, positionId, query?)` | `GET …/transactions` |
|
|
56
|
+
| `positions.charts(chainId, protocol, positionId, query?)` | `GET …/charts` |
|
|
57
|
+
| `pools.list(query?)` | `GET /v1/pools` |
|
|
58
|
+
| `pools.get(chainId, protocol, poolId, query?)` | `GET /v1/pools/{chainId}/{protocol}/{poolId}` |
|
|
59
|
+
| `pools.charts(chainId, protocol, poolId, query?)` | `GET …/charts` |
|
|
60
|
+
| `tokens.get(chainId, address, query?)` | `GET /v1/tokens/{chainId}/{address}` |
|
|
61
|
+
| `wallets.summary(address, query?)` | `GET /v1/wallets/{address}` |
|
|
62
|
+
| `hooks.list(query?)` | `GET /v1/hooks` |
|
|
63
|
+
| `chains()`, `protocols()`, `plans()`, `stats()` | the free metadata routes |
|
|
64
|
+
| `pricing.units()` | `GET /v1/pricing/units`, the live unit price of every route |
|
|
65
|
+
|
|
66
|
+
Path parameters come first, in URL order. Then comes one object with the route's query parameters, with the same names, defaults and limits as the [endpoint docs](https://tickwise.xyz/docs/endpoints/positions). The last argument is optional options for that call: `signal`, `timeoutMs`, `maxRetries`.
|
|
67
|
+
|
|
68
|
+
- `chainId` is any number. `tw.chains()` lists the chains served right now.
|
|
69
|
+
- `fields` takes an array or a comma-separated string.
|
|
70
|
+
- With `fields` or `view: 'compact'`, the rows are typed as partial, because the API sends only what you asked for.
|
|
71
|
+
- Every route except the five free ones is metered in units. `tw.pricing.units()` returns the current prices; this package never hard-codes them.
|
|
72
|
+
|
|
73
|
+
## Paging
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// Rows, across pages. Each page is fetched only when you reach it.
|
|
77
|
+
for await (const pool of tw.pools.iterate({ chainId: 1, limit: 100 }, { maxPages: 5 })) {
|
|
78
|
+
console.log(pool.poolId, pool.metrics?.tvlUsd);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Whole pages
|
|
82
|
+
for await (const page of tw.hooks.pages({ limit: 100 })) console.log(page.pagination.page, page.hooks.length);
|
|
83
|
+
|
|
84
|
+
// A position's transactions, following the cursor
|
|
85
|
+
for await (const tx of tw.positions.iterateTransactions(1, 'uniswap-v4', '123456')) console.log(tx.type);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- `iterate` and `pages` exist on positions, pools and hooks. `tokens.iteratePools` pages through a token's pools.
|
|
89
|
+
- Hooks across all chains stop 1,000 rows deep (`HOOKS_ALL_CHAINS_MAX_ROWS`), the most the API serves without a `chainId`. Pass `chainId` to page one chain further.
|
|
90
|
+
- **Every page is a metered request.** `break` stops the spending; `maxPages` and `maxItems` set a hard stop.
|
|
91
|
+
- `positions.batchAll` takes any number of ids and sends calls of 100 one after another. The batch is priced per position returned, so it costs the same as the separate calls.
|
|
92
|
+
|
|
93
|
+
## CSV export
|
|
94
|
+
|
|
95
|
+
`exportCsv` on positions, pools and hooks fetches one page with `format=csv`. The filters, the 100-row limit and the unit cost are the same as JSON. You get:
|
|
96
|
+
|
|
97
|
+
- the CSV text exactly as served;
|
|
98
|
+
- `filename`;
|
|
99
|
+
- `pagination` (from the `X-Page`, `X-Limit`, `X-Total-Count`, `X-Total-Pages` and `X-Has-More` headers);
|
|
100
|
+
- the `partial`, `stale` and `countsPending` flags.
|
|
101
|
+
|
|
102
|
+
`exportCsvPages` walks every page. Each page has its own header row, so drop it from every page after the first:
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { writeFile } from 'node:fs/promises';
|
|
106
|
+
|
|
107
|
+
const parts: string[] = [];
|
|
108
|
+
for await (const page of tw.pools.exportCsvPages({ chainId: 1, limit: 100 }, { maxPages: 10 })) {
|
|
109
|
+
parts.push(parts.length === 0 ? page.csv : page.csv.slice(page.csv.indexOf('\r\n') + 2));
|
|
110
|
+
}
|
|
111
|
+
await writeFile('pools.csv', parts.join(''));
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The SDK does not parse CSV. Excel rounds big integers such as `liquidity` unless that column is imported as Text.
|
|
115
|
+
|
|
116
|
+
## Errors
|
|
117
|
+
|
|
118
|
+
Every error is a `TickwiseError`. Each has a stable `kind`, the `status`, the parsed `body`, the `headers` and, on a 429 or 503, `retryAfterSec`. Branch on the class or on `kind`, never on the message.
|
|
119
|
+
|
|
120
|
+
| Class | Status | Retried |
|
|
121
|
+
| --- | --- | --- |
|
|
122
|
+
| `BadRequestError` | 400 | no |
|
|
123
|
+
| `AuthenticationError` | 401 | no |
|
|
124
|
+
| `PermissionDeniedError` | 403 | no |
|
|
125
|
+
| `NotFoundError` | 404 | no |
|
|
126
|
+
| `RateLimitError` (a `TooManyRequestsError`) | 429, the 60-second burst limit | yes |
|
|
127
|
+
| `QuotaExceededError` (a `TooManyRequestsError`) | 429, the monthly quota | no |
|
|
128
|
+
| `ServiceUnavailableError` | 503 | yes |
|
|
129
|
+
| `APIError` | any other status | 502; 504 on free routes only |
|
|
130
|
+
| `ConnectionError` | no answer | when the connection was never opened (`connectFailed`); any on free routes |
|
|
131
|
+
| `TimeoutError` | an attempt passed `timeoutMs` | free routes only |
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { NotFoundError, QuotaExceededError } from '@tickwise/sdk';
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
await tw.pools.get(1, 'uniswap-v4', poolId);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
if (e instanceof NotFoundError) return null;
|
|
140
|
+
if (e instanceof QuotaExceededError) alertOps('Tickwise quota used up');
|
|
141
|
+
throw e;
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Retries and timeouts
|
|
146
|
+
|
|
147
|
+
| Option | Default | |
|
|
148
|
+
| --- | --- | --- |
|
|
149
|
+
| `maxRetries` | `2` | retries after the first attempt |
|
|
150
|
+
| `timeoutMs` | `30000` | per attempt |
|
|
151
|
+
| `maxRetryAfterSec` | `60` | a longer `Retry-After` is thrown at once, not waited out |
|
|
152
|
+
| `baseUrl` | `https://api.tickwise.xyz` | |
|
|
153
|
+
| `fetch` | `globalThis.fetch` | your own `fetch`, e.g. for a proxy or tests |
|
|
154
|
+
|
|
155
|
+
The client waits for `Retry-After` when the API sends one. Otherwise it backs off with jitter: 0.5 s, 1 s, 2 s and so on, capped at 8 s. Pass an `AbortSignal` as `signal` to cancel a call, including a wait between retries.
|
|
156
|
+
|
|
157
|
+
**A retry never costs extra units.** On a metered route the client retries only failures the API did not charge:
|
|
158
|
+
|
|
159
|
+
- the burst rate limit;
|
|
160
|
+
- a 503, which is credited back;
|
|
161
|
+
- a 502;
|
|
162
|
+
- a connection that was never opened (the name did not resolve, or the connection was refused).
|
|
163
|
+
|
|
164
|
+
A timeout, a connection lost mid-request and a 504 are thrown, not retried. The API may already have served that request, and charged it. Retry those yourself if a second charge is acceptable. Free routes retry all of them.
|
|
165
|
+
|
|
166
|
+
## Usage and limits on each answer
|
|
167
|
+
|
|
168
|
+
Every method returns a promise you can `await` for the data. Call `.withMeta()` on it for `{ data, meta }`. `meta` holds:
|
|
169
|
+
|
|
170
|
+
- the burst limit, `rateLimit` (limit, remaining, reset);
|
|
171
|
+
- the monthly quota, `quota` (limit, remaining, reset);
|
|
172
|
+
- on the batch, `unitsCharged`;
|
|
173
|
+
- `cacheControl`, `status`, and how many `retries` the call took.
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
const { data, meta } = await tw.positions.list({ chainId: 1 }).withMeta();
|
|
177
|
+
console.log(meta.quota?.remaining, 'units left this month');
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
## In a browser
|
|
181
|
+
|
|
182
|
+
Prefer calling the API from your own server. A browser request always carries an `Origin` header, and the API refuses a server key on any request that has one (403). If you must call it from a page, create a **browser** key with your site's origins registered. Every visitor can read that key, so anyone who copies it can spend it. The client logs a warning once when it sees a key in a browser.
|
|
183
|
+
|
|
184
|
+
## Licence
|
|
185
|
+
|
|
186
|
+
AGPL-3.0-only.
|
|
@@ -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,43 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.APIPromise = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* What every SDK method returns. `await` it for the data; call `.withMeta()` for the data plus the response
|
|
6
|
+
* metadata (rate-limit and quota headers, units charged on a batch, the status, how many retries it took).
|
|
7
|
+
*
|
|
8
|
+
* `then` / `catch` / `finally` are delegated to a plain promise of the data, so chaining never builds another
|
|
9
|
+
* `APIPromise` (the usual trap of subclassing `Promise`).
|
|
10
|
+
*/
|
|
11
|
+
class APIPromise extends Promise {
|
|
12
|
+
#raw;
|
|
13
|
+
#data;
|
|
14
|
+
constructor(raw) {
|
|
15
|
+
super((resolve) => {
|
|
16
|
+
// The base promise is never used; it is settled so it can never be an unhandled rejection.
|
|
17
|
+
resolve(undefined);
|
|
18
|
+
});
|
|
19
|
+
this.#raw = raw;
|
|
20
|
+
}
|
|
21
|
+
// Promise subclass methods (`then`, `Promise.resolve(apiPromise)`) look this up; plain promises are what they build.
|
|
22
|
+
static get [Symbol.species]() {
|
|
23
|
+
return Promise;
|
|
24
|
+
}
|
|
25
|
+
/** The data and the response metadata. */
|
|
26
|
+
withMeta() {
|
|
27
|
+
return this.#raw;
|
|
28
|
+
}
|
|
29
|
+
#parsed() {
|
|
30
|
+
this.#data ??= this.#raw.then((r) => r.data);
|
|
31
|
+
return this.#data;
|
|
32
|
+
}
|
|
33
|
+
then(onfulfilled, onrejected) {
|
|
34
|
+
return this.#parsed().then(onfulfilled, onrejected);
|
|
35
|
+
}
|
|
36
|
+
catch(onrejected) {
|
|
37
|
+
return this.#parsed().catch(onrejected);
|
|
38
|
+
}
|
|
39
|
+
finally(onfinally) {
|
|
40
|
+
return this.#parsed().finally(onfinally);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.APIPromise = APIPromise;
|
|
@@ -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,118 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Tickwise = void 0;
|
|
4
|
+
const hooks_js_1 = require("./resources/hooks.js");
|
|
5
|
+
const meta_js_1 = require("./resources/meta.js");
|
|
6
|
+
const pools_js_1 = require("./resources/pools.js");
|
|
7
|
+
const positions_js_1 = require("./resources/positions.js");
|
|
8
|
+
const tokens_js_1 = require("./resources/tokens.js");
|
|
9
|
+
const wallets_js_1 = require("./resources/wallets.js");
|
|
10
|
+
const transport_js_1 = require("./transport.js");
|
|
11
|
+
let warnedBrowserKey = false;
|
|
12
|
+
function envKey() {
|
|
13
|
+
const p = globalThis.process;
|
|
14
|
+
const v = p?.env?.TICKWISE_API_KEY;
|
|
15
|
+
return v && v.trim() ? v.trim() : undefined;
|
|
16
|
+
}
|
|
17
|
+
function positive(name, v, fallback, allowZero = false) {
|
|
18
|
+
return v === undefined ? fallback : (0, transport_js_1.checkNumber)(name, v, allowZero);
|
|
19
|
+
}
|
|
20
|
+
/** An HTTP header name (RFC 9110 token). */
|
|
21
|
+
const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
22
|
+
/** Keys are printable ASCII with no spaces. Anything else would make every request fail inside `fetch`. */
|
|
23
|
+
const API_KEY = /^[\x21-\x7E]+$/;
|
|
24
|
+
/**
|
|
25
|
+
* The Tickwise API client.
|
|
26
|
+
*
|
|
27
|
+
* ```ts
|
|
28
|
+
* const tw = new Tickwise({ apiKey: process.env.TICKWISE_API_KEY });
|
|
29
|
+
* const { pools } = await tw.pools.list({ chainId: 1, sort: 'fees', limit: 10 });
|
|
30
|
+
* ```
|
|
31
|
+
*
|
|
32
|
+
* Call it from your server or an edge function. A server key is refused (403) on any request that carries an
|
|
33
|
+
* `Origin` header, which every browser request does; in a browser use a browser key with your origins registered.
|
|
34
|
+
*/
|
|
35
|
+
class Tickwise {
|
|
36
|
+
positions;
|
|
37
|
+
pools;
|
|
38
|
+
tokens;
|
|
39
|
+
wallets;
|
|
40
|
+
hooks;
|
|
41
|
+
pricing;
|
|
42
|
+
#meta;
|
|
43
|
+
#baseUrl;
|
|
44
|
+
constructor(options = {}) {
|
|
45
|
+
const baseUrl = (options.baseUrl ?? transport_js_1.DEFAULT_BASE_URL).trim().replace(/\/+$/, '');
|
|
46
|
+
let parsed;
|
|
47
|
+
try {
|
|
48
|
+
parsed = new URL(baseUrl);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
throw new TypeError(`Tickwise: \`baseUrl\` is not a valid URL: ${baseUrl}`);
|
|
52
|
+
}
|
|
53
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
54
|
+
throw new TypeError('Tickwise: `baseUrl` must start with https:// or http://');
|
|
55
|
+
}
|
|
56
|
+
if (parsed.search || parsed.hash || parsed.username || parsed.password) {
|
|
57
|
+
throw new TypeError('Tickwise: `baseUrl` must not carry a query, fragment or credentials');
|
|
58
|
+
}
|
|
59
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
60
|
+
if (typeof f !== 'function') {
|
|
61
|
+
throw new TypeError('Tickwise: no global `fetch` on this runtime; pass one as `fetch` (Node 20.3+ has it built in)');
|
|
62
|
+
}
|
|
63
|
+
const apiKey = options.apiKey?.trim() || envKey();
|
|
64
|
+
// Checked here so a typo fails once, clearly, instead of every request failing inside `fetch`. The key is
|
|
65
|
+
// never put in the message.
|
|
66
|
+
if (apiKey !== undefined && !API_KEY.test(apiKey)) {
|
|
67
|
+
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)');
|
|
68
|
+
}
|
|
69
|
+
const keyHeader = options.keyHeader?.trim() || transport_js_1.DEFAULT_KEY_HEADER;
|
|
70
|
+
if (!HEADER_NAME.test(keyHeader))
|
|
71
|
+
throw new TypeError(`Tickwise: \`keyHeader\` is not a valid header name: ${keyHeader}`);
|
|
72
|
+
if (apiKey && (0, transport_js_1.isBrowser)() && !warnedBrowserKey) {
|
|
73
|
+
warnedBrowserKey = true;
|
|
74
|
+
console.warn('Tickwise: an API key is in use in a browser, where every visitor can read it. Use a browser key with your ' +
|
|
75
|
+
'origins registered (a server key is refused here with 403), or call the API from your own server.');
|
|
76
|
+
}
|
|
77
|
+
this.#baseUrl = baseUrl;
|
|
78
|
+
const transport = new transport_js_1.Transport({
|
|
79
|
+
apiKey,
|
|
80
|
+
baseUrl,
|
|
81
|
+
keyHeader,
|
|
82
|
+
timeoutMs: positive('timeoutMs', options.timeoutMs, transport_js_1.DEFAULT_TIMEOUT_MS),
|
|
83
|
+
maxRetries: Math.floor(positive('maxRetries', options.maxRetries, transport_js_1.DEFAULT_MAX_RETRIES, true)),
|
|
84
|
+
maxRetryAfterSec: positive('maxRetryAfterSec', options.maxRetryAfterSec, transport_js_1.DEFAULT_MAX_RETRY_AFTER_SEC, true),
|
|
85
|
+
maxBodyBytes: options.maxBodyBytes === undefined ? undefined : positive('maxBodyBytes', options.maxBodyBytes, 0),
|
|
86
|
+
// Called unbound: a native `fetch` called as a method of another object throws "Illegal invocation" in browsers.
|
|
87
|
+
fetch: (input, init) => f(input, init),
|
|
88
|
+
});
|
|
89
|
+
this.positions = new positions_js_1.Positions(transport);
|
|
90
|
+
this.pools = new pools_js_1.Pools(transport);
|
|
91
|
+
this.tokens = new tokens_js_1.Tokens(transport);
|
|
92
|
+
this.wallets = new wallets_js_1.Wallets(transport);
|
|
93
|
+
this.hooks = new hooks_js_1.Hooks(transport);
|
|
94
|
+
this.pricing = new meta_js_1.Pricing(transport);
|
|
95
|
+
this.#meta = new meta_js_1.Meta(transport);
|
|
96
|
+
}
|
|
97
|
+
/** The API base URL this client calls. */
|
|
98
|
+
get baseUrl() {
|
|
99
|
+
return this.#baseUrl;
|
|
100
|
+
}
|
|
101
|
+
/** `GET /v1/chains` (free): the chains served right now. The live list of valid `chainId`s. */
|
|
102
|
+
chains(options) {
|
|
103
|
+
return this.#meta.chains(options);
|
|
104
|
+
}
|
|
105
|
+
/** `GET /v1/protocols` (free): the protocols served and the chains each is live on. */
|
|
106
|
+
protocols(options) {
|
|
107
|
+
return this.#meta.protocols(options);
|
|
108
|
+
}
|
|
109
|
+
/** `GET /v1/plans` (free): the plans on sale. */
|
|
110
|
+
plans(options) {
|
|
111
|
+
return this.#meta.plans(options);
|
|
112
|
+
}
|
|
113
|
+
/** `GET /v1/stats` (free): headline counts of everything indexed. */
|
|
114
|
+
stats(options) {
|
|
115
|
+
return this.#meta.stats(options);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
exports.Tickwise = Tickwise;
|
|
@@ -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/cjs/csv.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.filenameOf = filenameOf;
|
|
4
|
+
exports.csvHasRows = csvHasRows;
|
|
5
|
+
exports.csvPageOf = csvPageOf;
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
function int(h, name) {
|
|
8
|
+
const v = h.get(name)?.trim();
|
|
9
|
+
if (!v || !/^\d+$/.test(v))
|
|
10
|
+
return undefined;
|
|
11
|
+
return Number(v);
|
|
12
|
+
}
|
|
13
|
+
const flag = (h, name) => h.get(name)?.trim().toLowerCase() === 'true';
|
|
14
|
+
function filenameOf(disposition) {
|
|
15
|
+
if (!disposition)
|
|
16
|
+
return undefined;
|
|
17
|
+
const quoted = /filename="([^"]*)"/i.exec(disposition);
|
|
18
|
+
if (quoted)
|
|
19
|
+
return quoted[1] || undefined;
|
|
20
|
+
const bare = /filename=([^;]+)/i.exec(disposition);
|
|
21
|
+
return bare?.[1]?.trim() || undefined;
|
|
22
|
+
}
|
|
23
|
+
/** Whether a CSV page has any data row below its header row. The CSV page iterators stop on a page that has none. */
|
|
24
|
+
function csvHasRows(text) {
|
|
25
|
+
const nl = text.indexOf('\n');
|
|
26
|
+
return nl !== -1 && text.slice(nl + 1).trim() !== '';
|
|
27
|
+
}
|
|
28
|
+
/** Reads a CSV answer. Throws when it is not one (a server that ignored `format=csv`). */
|
|
29
|
+
function csvPageOf(text, headers, url) {
|
|
30
|
+
const type = headers.get('content-type') ?? '';
|
|
31
|
+
const page = int(headers, 'X-Page');
|
|
32
|
+
const limit = int(headers, 'X-Limit');
|
|
33
|
+
const hasMore = headers.get('X-Has-More')?.trim().toLowerCase();
|
|
34
|
+
if (!/text\/csv/i.test(type) || page === undefined || limit === undefined || (hasMore !== 'true' && hasMore !== 'false')) {
|
|
35
|
+
throw new errors_js_1.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)', {
|
|
36
|
+
headers,
|
|
37
|
+
url,
|
|
38
|
+
body: text.slice(0, 500),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const pagination = { page, limit, hasMore: hasMore === 'true' };
|
|
42
|
+
const total = int(headers, 'X-Total-Count');
|
|
43
|
+
const totalPages = int(headers, 'X-Total-Pages');
|
|
44
|
+
if (total !== undefined)
|
|
45
|
+
pagination.total = total;
|
|
46
|
+
if (totalPages !== undefined)
|
|
47
|
+
pagination.totalPages = totalPages;
|
|
48
|
+
if (flag(headers, 'X-Total-Capped'))
|
|
49
|
+
pagination.totalCapped = true;
|
|
50
|
+
const out = { csv: text, pagination };
|
|
51
|
+
const filename = filenameOf(headers.get('content-disposition'));
|
|
52
|
+
if (filename)
|
|
53
|
+
out.filename = filename;
|
|
54
|
+
if (flag(headers, 'X-Partial')) {
|
|
55
|
+
const missingChains = (headers.get('X-Missing-Chains') ?? '')
|
|
56
|
+
.split(',')
|
|
57
|
+
.map((s) => s.trim())
|
|
58
|
+
.filter((s) => /^\d+$/.test(s))
|
|
59
|
+
.map(Number);
|
|
60
|
+
out.partial = { missingChains };
|
|
61
|
+
}
|
|
62
|
+
if (flag(headers, 'X-Stale')) {
|
|
63
|
+
const dataAsOf = headers.get('X-Data-As-Of')?.trim();
|
|
64
|
+
out.stale = dataAsOf ? { dataAsOf } : {};
|
|
65
|
+
}
|
|
66
|
+
if (flag(headers, 'X-Counts-Pending'))
|
|
67
|
+
out.countsPending = true;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
@@ -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;
|