@tickwise/sdk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +203 -2
- package/dist/cjs/api-promise.d.ts +22 -0
- package/dist/cjs/api-promise.js +43 -0
- package/dist/cjs/client.d.ts +64 -0
- package/dist/cjs/client.js +123 -0
- package/dist/cjs/csv.d.ts +37 -0
- package/dist/cjs/csv.js +69 -0
- package/dist/cjs/errors.d.ts +133 -0
- package/dist/cjs/errors.js +242 -0
- package/dist/cjs/generated/openapi.d.ts +1949 -0
- package/dist/cjs/generated/openapi.js +6 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +33 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/base.d.ts +21 -0
- package/dist/cjs/resources/base.js +81 -0
- package/dist/cjs/resources/hooks.d.ts +26 -0
- package/dist/cjs/resources/hooks.js +46 -0
- package/dist/cjs/resources/meta.d.ts +23 -0
- package/dist/cjs/resources/meta.js +35 -0
- package/dist/cjs/resources/pools.d.ts +21 -0
- package/dist/cjs/resources/pools.js +40 -0
- package/dist/cjs/resources/positions.d.ts +59 -0
- package/dist/cjs/resources/positions.js +187 -0
- package/dist/cjs/resources/tokens.d.ts +19 -0
- package/dist/cjs/resources/tokens.js +28 -0
- package/dist/cjs/resources/wallets.d.ts +11 -0
- package/dist/cjs/resources/wallets.js +14 -0
- package/dist/cjs/routes.d.ts +84 -0
- package/dist/cjs/routes.js +45 -0
- package/dist/cjs/transport.d.ts +92 -0
- package/dist/cjs/transport.js +314 -0
- package/dist/cjs/types.d.ts +112 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/esm/api-promise.d.ts +22 -0
- package/dist/esm/api-promise.js +39 -0
- package/dist/esm/client.d.ts +64 -0
- package/dist/esm/client.js +119 -0
- package/dist/esm/csv.d.ts +37 -0
- package/dist/esm/csv.js +64 -0
- package/dist/esm/errors.d.ts +133 -0
- package/dist/esm/errors.js +221 -0
- package/dist/esm/generated/openapi.d.ts +1949 -0
- package/dist/esm/generated/openapi.js +5 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +8 -0
- package/dist/esm/resources/base.d.ts +21 -0
- package/dist/esm/resources/base.js +73 -0
- package/dist/esm/resources/hooks.d.ts +26 -0
- package/dist/esm/resources/hooks.js +42 -0
- package/dist/esm/resources/meta.d.ts +23 -0
- package/dist/esm/resources/meta.js +30 -0
- package/dist/esm/resources/pools.d.ts +21 -0
- package/dist/esm/resources/pools.js +36 -0
- package/dist/esm/resources/positions.d.ts +59 -0
- package/dist/esm/resources/positions.js +183 -0
- package/dist/esm/resources/tokens.d.ts +19 -0
- package/dist/esm/resources/tokens.js +24 -0
- package/dist/esm/resources/wallets.d.ts +11 -0
- package/dist/esm/resources/wallets.js +10 -0
- package/dist/esm/routes.d.ts +84 -0
- package/dist/esm/routes.js +41 -0
- package/dist/esm/transport.d.ts +92 -0
- package/dist/esm/transport.js +303 -0
- package/dist/esm/types.d.ts +112 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/package.json +64 -4
package/README.md
CHANGED
|
@@ -1,3 +1,204 @@
|
|
|
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 17 `/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
|
+
| `tokens.search({ q, chainId?, limit? })` | `GET /v1/tokens/search` |
|
|
62
|
+
| `wallets.summary(address, query?)` | `GET /v1/wallets/{address}` |
|
|
63
|
+
| `hooks.list(query?)` | `GET /v1/hooks` |
|
|
64
|
+
| `chains()`, `protocols()`, `plans()`, `stats()` | the free metadata routes |
|
|
65
|
+
| `pricing.units()` | `GET /v1/pricing/units`, the live unit price of every route |
|
|
66
|
+
|
|
67
|
+
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`.
|
|
68
|
+
|
|
69
|
+
- `chainId` is any number. `tw.chains()` lists the chains served right now.
|
|
70
|
+
- `fields` takes an array or a comma-separated string.
|
|
71
|
+
- With `fields` or `view: 'compact'`, the rows are typed as partial, because the API sends only what you asked for. They are also typed as partial when that is only known at run time: a `fields` that may be `undefined`, a `view` typed `'compact' | 'full'`, or a whole `PositionsListQuery` passed through a function of yours. A query with no `fields` and no `view`, or with `view: 'full'`, gets full rows.
|
|
72
|
+
- A position id is a string, a `bigint` or a `number`. A `number` above 2^53 − 1 has already lost digits, so it is a `TypeError`: pass large ids as strings or bigints.
|
|
73
|
+
- Every route except the five free ones is metered in units. `tw.pricing.units()` returns the current prices; this package never hard-codes them.
|
|
74
|
+
- Every position a wallet holds, open and closed: `tw.positions.iterate({ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true, sort: 'underlying_value' })`. Keep the `sort`: the default sort ranks by rate, and a rate sort leaves closed positions out. `tw.wallets.summary(owner)` gives the totals of the same rows.
|
|
75
|
+
|
|
76
|
+
## Paging
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
// Rows, across pages. Each page is fetched only when you reach it.
|
|
80
|
+
for await (const pool of tw.pools.iterate({ chainId: 1, limit: 100 }, { maxPages: 5 })) {
|
|
81
|
+
console.log(pool.poolId, pool.metrics?.tvlUsd);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Whole pages
|
|
85
|
+
for await (const page of tw.hooks.pages({ limit: 100 })) console.log(page.pagination.page, page.hooks.length);
|
|
86
|
+
|
|
87
|
+
// A position's transactions, newest first, following the cursor
|
|
88
|
+
for await (const tx of tw.positions.iterateTransactions(1, 'uniswap-v4', '123456')) console.log(tx.type);
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`positions.transactions` returns one page as the API sends it: pages run from newest to oldest, and the rows inside a page are oldest to newest. `iterateTransactions` yields every row newest first. When its last page says the API's list is not the position's whole history (`transactionsPartial`: only the newest were ready, ask again in a few seconds; `transactionsTruncated`: the history is longer than the API reads; `transactionsDegraded`), it throws `TransactionsIncompleteError` after yielding every row it got. `reasons` names the flags.
|
|
92
|
+
|
|
93
|
+
- `iterate` and `pages` exist on positions, pools and hooks. `tokens.iteratePools` pages through a token's pools.
|
|
94
|
+
- 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.
|
|
95
|
+
- **Every page is a metered request.** `break` stops the spending; `maxPages` and `maxItems` set a hard stop. `exportCsvPages` takes `maxPages` only, because a CSV page is counted whole.
|
|
96
|
+
- `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. If a call fails after earlier ones were served (and charged), it throws `BatchAllIncompleteError`: the served rows are in `data`, the ids still to fetch in `remainingIds`, and the call's own error in `cause`. Pass `remainingIds` to `batchAll` again to finish without paying twice.
|
|
97
|
+
|
|
98
|
+
## CSV export
|
|
99
|
+
|
|
100
|
+
`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:
|
|
101
|
+
|
|
102
|
+
- the CSV text exactly as served;
|
|
103
|
+
- `filename`;
|
|
104
|
+
- `pagination` (from the `X-Page`, `X-Limit`, `X-Total-Count`, `X-Total-Pages` and `X-Has-More` headers);
|
|
105
|
+
- the `partial`, `stale` and `countsPending` flags.
|
|
106
|
+
|
|
107
|
+
`exportCsvPages` walks every page. Each page has its own header row, so drop it from every page after the first:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { writeFile } from 'node:fs/promises';
|
|
111
|
+
|
|
112
|
+
const parts: string[] = [];
|
|
113
|
+
for await (const page of tw.pools.exportCsvPages({ chainId: 1, limit: 100 }, { maxPages: 10 })) {
|
|
114
|
+
parts.push(parts.length === 0 ? page.csv : page.csv.slice(page.csv.indexOf('\r\n') + 2));
|
|
115
|
+
}
|
|
116
|
+
await writeFile('pools.csv', parts.join(''));
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The SDK does not parse CSV. A cell that holds a list joins its items with `|`. Excel rounds big integers such as `liquidity` unless that column is imported as Text.
|
|
120
|
+
|
|
121
|
+
## Errors
|
|
122
|
+
|
|
123
|
+
Every error from the API or the network 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.
|
|
124
|
+
|
|
125
|
+
Two kinds of error are not a `TickwiseError`:
|
|
126
|
+
|
|
127
|
+
- A call you cancel with `signal` rejects with the signal's reason, as `fetch` does (an `AbortError` `DOMException` unless you passed your own reason). The one exception is `batchAll` after a served chunk: the abort is the `cause` of a `BatchAllIncompleteError`.
|
|
128
|
+
- A bad argument, such as a malformed option, a `baseUrl` that ends in `/v1` or a `number` id past 2^53, throws a `TypeError` (or rejects with one) before any request is sent.
|
|
129
|
+
|
|
130
|
+
On a `QuotaExceededError`, `retryAfterSec` is the time until the quota resets (00:00 UTC on the 1st of the month), so it can be weeks. A `ConnectionError` keeps the network error (for example `ECONNREFUSED`) in `cause`.
|
|
131
|
+
|
|
132
|
+
The ESM and CommonJS builds each have their own error classes. If one program loads the package both ways, `instanceof` across the two fails; compare `kind` there instead.
|
|
133
|
+
|
|
134
|
+
| Class | Status | Retried |
|
|
135
|
+
| --- | --- | --- |
|
|
136
|
+
| `BadRequestError` | 400 | no |
|
|
137
|
+
| `AuthenticationError` | 401 | no |
|
|
138
|
+
| `PermissionDeniedError` | 403 | no |
|
|
139
|
+
| `NotFoundError` | 404 | no |
|
|
140
|
+
| `RateLimitError` (a `TooManyRequestsError`) | 429, the 60-second burst limit | yes |
|
|
141
|
+
| `QuotaExceededError` (a `TooManyRequestsError`) | 429, the monthly quota | no |
|
|
142
|
+
| `ServiceUnavailableError` | 503 | yes |
|
|
143
|
+
| `APIError` | any other status | 502 and 504 on free routes only |
|
|
144
|
+
| `ConnectionError` | no answer | when the connection was never opened (`connectFailed`); any on free routes |
|
|
145
|
+
| `TimeoutError` | an attempt passed `timeoutMs` | free routes only |
|
|
146
|
+
| `BatchAllIncompleteError` (an `IncompleteError`) | `batchAll` stopped after served chunks | no |
|
|
147
|
+
| `TransactionsIncompleteError` (an `IncompleteError`) | `iterateTransactions` reached the end of an incomplete list | no |
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { NotFoundError, QuotaExceededError } from '@tickwise/sdk';
|
|
151
|
+
|
|
152
|
+
try {
|
|
153
|
+
await tw.pools.get(1, 'uniswap-v4', poolId);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
if (e instanceof NotFoundError) return null;
|
|
156
|
+
if (e instanceof QuotaExceededError) alertOps('Tickwise quota used up');
|
|
157
|
+
throw e;
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Retries and timeouts
|
|
162
|
+
|
|
163
|
+
| Option | Default | |
|
|
164
|
+
| --- | --- | --- |
|
|
165
|
+
| `apiKey` | `TICKWISE_API_KEY` from the environment | sent only on metered routes |
|
|
166
|
+
| `maxRetries` | `2` | retries after the first attempt |
|
|
167
|
+
| `timeoutMs` | `30000` | per attempt |
|
|
168
|
+
| `maxRetryAfterSec` | `60` | a longer `Retry-After` is thrown at once, not waited out |
|
|
169
|
+
| `baseUrl` | `https://api.tickwise.xyz` | the API origin, without `/v1`; an empty value means the default |
|
|
170
|
+
| `keyHeader` | `KC-APIKey` | the header the key is sent in |
|
|
171
|
+
| `maxBodyBytes` | off | refuse a response body larger than this |
|
|
172
|
+
| `fetch` | `globalThis.fetch` | your own `fetch`, e.g. for a proxy or tests |
|
|
173
|
+
|
|
174
|
+
The client waits for `Retry-After` when the API (or a gateway, in seconds or as a date) sends one. Otherwise it waits a random time up to 0.5 s, then up to 1 s, then up to 2 s and so on, capped at 8 s. Pass an `AbortSignal` as `signal` to cancel a call, including a wait between retries.
|
|
175
|
+
|
|
176
|
+
**A retry never costs extra units.** On a metered route the client retries only failures the API did not charge:
|
|
177
|
+
|
|
178
|
+
- the burst rate limit;
|
|
179
|
+
- a 503, which is credited back;
|
|
180
|
+
- a connection that was never opened (the name did not resolve, or the connection was refused).
|
|
181
|
+
|
|
182
|
+
A timeout, a connection lost mid-request, a 502 and a 504 are thrown, not retried. The API may already have served that request, and charged it: a 502 or 504 comes from the gateway in front of the API, so the API never got to credit it back. Retry those yourself if a second charge is acceptable. Free routes retry all of them.
|
|
183
|
+
|
|
184
|
+
## Usage and limits on each answer
|
|
185
|
+
|
|
186
|
+
Every method returns a promise you can `await` for the data. Call `.withMeta()` on it for `{ data, meta }`. `meta` holds:
|
|
187
|
+
|
|
188
|
+
- the burst limit, `rateLimit` (limit, remaining, reset);
|
|
189
|
+
- the monthly quota, `quota` (limit, remaining, reset);
|
|
190
|
+
- on the batch, `unitsCharged`;
|
|
191
|
+
- `cacheControl`, `status`, and how many `retries` the call took.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const { data, meta } = await tw.positions.list({ chainId: 1 }).withMeta();
|
|
195
|
+
console.log(meta.quota?.remaining, 'units left this month');
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## In a browser
|
|
199
|
+
|
|
200
|
+
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.
|
|
201
|
+
|
|
202
|
+
## Licence
|
|
203
|
+
|
|
204
|
+
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 | 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,123 @@
|
|
|
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
|
+
// An empty value (an environment variable set to nothing) means the default, as for `apiKey` and `keyHeader`.
|
|
46
|
+
const baseUrl = (options.baseUrl?.trim() || transport_js_1.DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = new URL(baseUrl);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new TypeError(`Tickwise: \`baseUrl\` is not a valid URL: ${baseUrl}`);
|
|
53
|
+
}
|
|
54
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
55
|
+
throw new TypeError('Tickwise: `baseUrl` must start with https:// or http://');
|
|
56
|
+
}
|
|
57
|
+
if (parsed.search || parsed.hash || parsed.username || parsed.password) {
|
|
58
|
+
throw new TypeError('Tickwise: `baseUrl` must not carry a query, fragment or credentials');
|
|
59
|
+
}
|
|
60
|
+
// Every route path starts with /v1, so a base URL that already ends in it would send every call to /v1/v1/....
|
|
61
|
+
if (/\/v1$/i.test(parsed.pathname.replace(/\/+$/, ''))) {
|
|
62
|
+
throw new TypeError('Tickwise: `baseUrl` is the API origin without `/v1` (for example https://api.tickwise.xyz)');
|
|
63
|
+
}
|
|
64
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
65
|
+
if (typeof f !== 'function') {
|
|
66
|
+
throw new TypeError('Tickwise: no global `fetch` on this runtime; pass one as `fetch` (Node 20.3+ has it built in)');
|
|
67
|
+
}
|
|
68
|
+
const apiKey = options.apiKey?.trim() || envKey();
|
|
69
|
+
// Checked here so a typo fails once, clearly, instead of every request failing inside `fetch`. The key is
|
|
70
|
+
// never put in the message.
|
|
71
|
+
if (apiKey !== undefined && !API_KEY.test(apiKey)) {
|
|
72
|
+
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)');
|
|
73
|
+
}
|
|
74
|
+
const keyHeader = options.keyHeader?.trim() || transport_js_1.DEFAULT_KEY_HEADER;
|
|
75
|
+
if (!HEADER_NAME.test(keyHeader))
|
|
76
|
+
throw new TypeError(`Tickwise: \`keyHeader\` is not a valid header name: ${keyHeader}`);
|
|
77
|
+
if (apiKey && (0, transport_js_1.isBrowser)() && !warnedBrowserKey) {
|
|
78
|
+
warnedBrowserKey = true;
|
|
79
|
+
console.warn('Tickwise: an API key is in use in a browser, where every visitor can read it. Use a browser key with your ' +
|
|
80
|
+
'origins registered (a server key is refused here with 403), or call the API from your own server.');
|
|
81
|
+
}
|
|
82
|
+
this.#baseUrl = baseUrl;
|
|
83
|
+
const transport = new transport_js_1.Transport({
|
|
84
|
+
apiKey,
|
|
85
|
+
baseUrl,
|
|
86
|
+
keyHeader,
|
|
87
|
+
timeoutMs: positive('timeoutMs', options.timeoutMs, transport_js_1.DEFAULT_TIMEOUT_MS),
|
|
88
|
+
maxRetries: Math.floor(positive('maxRetries', options.maxRetries, transport_js_1.DEFAULT_MAX_RETRIES, true)),
|
|
89
|
+
maxRetryAfterSec: positive('maxRetryAfterSec', options.maxRetryAfterSec, transport_js_1.DEFAULT_MAX_RETRY_AFTER_SEC, true),
|
|
90
|
+
maxBodyBytes: options.maxBodyBytes === undefined ? undefined : positive('maxBodyBytes', options.maxBodyBytes, 0),
|
|
91
|
+
// Called unbound: a native `fetch` called as a method of another object throws "Illegal invocation" in browsers.
|
|
92
|
+
fetch: (input, init) => f(input, init),
|
|
93
|
+
});
|
|
94
|
+
this.positions = new positions_js_1.Positions(transport);
|
|
95
|
+
this.pools = new pools_js_1.Pools(transport);
|
|
96
|
+
this.tokens = new tokens_js_1.Tokens(transport);
|
|
97
|
+
this.wallets = new wallets_js_1.Wallets(transport);
|
|
98
|
+
this.hooks = new hooks_js_1.Hooks(transport);
|
|
99
|
+
this.pricing = new meta_js_1.Pricing(transport);
|
|
100
|
+
this.#meta = new meta_js_1.Meta(transport);
|
|
101
|
+
}
|
|
102
|
+
/** The API base URL this client calls. */
|
|
103
|
+
get baseUrl() {
|
|
104
|
+
return this.#baseUrl;
|
|
105
|
+
}
|
|
106
|
+
/** `GET /v1/chains` (free): the chains served right now. The live list of valid `chainId`s. */
|
|
107
|
+
chains(options) {
|
|
108
|
+
return this.#meta.chains(options);
|
|
109
|
+
}
|
|
110
|
+
/** `GET /v1/protocols` (free): the protocols served and the chains each is live on. */
|
|
111
|
+
protocols(options) {
|
|
112
|
+
return this.#meta.protocols(options);
|
|
113
|
+
}
|
|
114
|
+
/** `GET /v1/plans` (free): the plans on sale. */
|
|
115
|
+
plans(options) {
|
|
116
|
+
return this.#meta.plans(options);
|
|
117
|
+
}
|
|
118
|
+
/** `GET /v1/stats` (free): headline counts of everything indexed. */
|
|
119
|
+
stats(options) {
|
|
120
|
+
return this.#meta.stats(options);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
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
|
+
}
|