@tickwise/sdk 0.1.0 → 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/README.md +30 -12
- package/dist/cjs/client.d.ts +10 -10
- package/dist/cjs/client.js +6 -1
- package/dist/cjs/errors.d.ts +56 -8
- package/dist/cjs/errors.js +65 -4
- package/dist/cjs/generated/openapi.d.ts +129 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +4 -1
- package/dist/cjs/resources/hooks.d.ts +2 -2
- package/dist/cjs/resources/pools.d.ts +7 -7
- package/dist/cjs/resources/positions.d.ts +27 -13
- package/dist/cjs/resources/positions.js +66 -12
- package/dist/cjs/resources/tokens.d.ts +9 -3
- package/dist/cjs/resources/tokens.js +8 -0
- package/dist/cjs/routes.d.ts +4 -0
- package/dist/cjs/routes.js +5 -0
- package/dist/cjs/transport.d.ts +8 -7
- package/dist/cjs/transport.js +8 -4
- package/dist/cjs/types.d.ts +26 -13
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/client.d.ts +10 -10
- package/dist/esm/client.js +6 -1
- package/dist/esm/errors.d.ts +56 -8
- package/dist/esm/errors.js +61 -3
- package/dist/esm/generated/openapi.d.ts +129 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/resources/hooks.d.ts +2 -2
- package/dist/esm/resources/pools.d.ts +7 -7
- package/dist/esm/resources/positions.d.ts +27 -13
- package/dist/esm/resources/positions.js +66 -12
- package/dist/esm/resources/tokens.d.ts +9 -3
- package/dist/esm/resources/tokens.js +8 -0
- package/dist/esm/routes.d.ts +4 -0
- package/dist/esm/routes.js +5 -0
- package/dist/esm/transport.d.ts +8 -7
- package/dist/esm/transport.js +8 -4
- package/dist/esm/types.d.ts +26 -13
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +1 -1
|
@@ -1,20 +1,23 @@
|
|
|
1
1
|
import { APIPromise } from '../api-promise.js';
|
|
2
2
|
import { type CsvPage } from '../csv.js';
|
|
3
3
|
import type { RequestOptions } from '../transport.js';
|
|
4
|
-
import type { PagingOptions, Position, PositionBatch, PositionChartsQuery, PositionDetail, PositionDetailQuery, PositionId, PositionList, PositionsBatchQuery, PositionsListQuery, PositionTransactionsQuery, ProtocolKey, RowOf, Shaped, Charts, Transaction, TransactionsPage, WithRows } from '../types.js';
|
|
4
|
+
import type { CsvPagingOptions, PagingOptions, Position, PositionBatch, PositionChartsQuery, PositionDetail, PositionDetailQuery, PositionId, PositionList, PositionsBatchQuery, PositionsListQuery, PositionTransactionsQuery, ProtocolKey, RowOf, Shaped, Charts, Transaction, TransactionsPage, WithRows } from '../types.js';
|
|
5
5
|
import { Resource } from './base.js';
|
|
6
6
|
/** Most ids one `GET /v1/positions/batch` call takes. */
|
|
7
7
|
export declare const POSITION_BATCH_MAX = 100;
|
|
8
8
|
export declare class Positions extends Resource {
|
|
9
9
|
/**
|
|
10
10
|
* `GET /v1/positions`: a ranked, filtered page of positions. The defaults hide closed, risky and small-pool
|
|
11
|
-
* positions
|
|
11
|
+
* positions. For everything a wallet holds pass
|
|
12
|
+
* `{ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true, sort: 'underlying_value' }`: the default
|
|
13
|
+
* sort (`apr`) ranks open positions only, so without a non-rate sort the closed ones are left out. These are the rows
|
|
14
|
+
* `wallets.summary` totals.
|
|
12
15
|
*/
|
|
13
|
-
list<Q extends PositionsListQuery =
|
|
16
|
+
list<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PositionList, 'positions', Q>>;
|
|
14
17
|
/** Every page of `list`, one request per page, fetched as you iterate. Starts at `query.page` (default 1). */
|
|
15
|
-
pages<Q extends PositionsListQuery =
|
|
18
|
+
pages<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PositionList, 'positions', Q>, void, undefined>;
|
|
16
19
|
/** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
|
|
17
|
-
iterate<Q extends PositionsListQuery =
|
|
20
|
+
iterate<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Position, Q>, void, undefined>;
|
|
18
21
|
/**
|
|
19
22
|
* `GET /v1/positions/batch`: up to 100 positions of one chain and protocol in one call, in the order of `ids`
|
|
20
23
|
* (duplicates dropped); ids not found are listed in `missing`. Priced per position returned
|
|
@@ -25,21 +28,32 @@ export declare class Positions extends Resource {
|
|
|
25
28
|
* Any number of ids: `batch` calls of 100, one after another, merged in order. Costs exactly what the separate
|
|
26
29
|
* calls cost (the batch is priced per position). `.withMeta()` gives the last call's metadata with
|
|
27
30
|
* `unitsCharged` and `retries` summed over all calls.
|
|
31
|
+
*
|
|
32
|
+
* When a chunk fails after earlier chunks were served (and charged), it throws `BatchAllIncompleteError` with the
|
|
33
|
+
* served rows in `data` and the rest in `remainingIds`; the chunk's own error is its `cause`. A failure on the
|
|
34
|
+
* first chunk is thrown as it is.
|
|
28
35
|
*/
|
|
29
36
|
batchAll<Q extends PositionsBatchQuery>(query: Q, options?: RequestOptions): APIPromise<WithRows<PositionBatch, 'positions', Q>>;
|
|
30
37
|
/** `GET /v1/positions/{chainId}/{protocol}/{positionId}`: one position, with its transactions. */
|
|
31
|
-
get<Q extends PositionDetailQuery =
|
|
32
|
-
/** `GET .../transactions`: one page of a position's transactions, newest first. */
|
|
33
|
-
transactions<Q extends PositionTransactionsQuery = PositionTransactionsQuery>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<WithRows<TransactionsPage, 'transactions', Q>>;
|
|
38
|
+
get<Q extends PositionDetailQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<PositionDetail, Q>>;
|
|
34
39
|
/**
|
|
35
|
-
*
|
|
36
|
-
*
|
|
40
|
+
* `GET .../transactions`: one page of a position's transactions. The first page holds the newest transactions and
|
|
41
|
+
* `transactionsNextCursor` (passed back as `before`) gives the next older page, but inside a page the rows are oldest
|
|
42
|
+
* to newest, as the API sends them. `iterateTransactions` yields newest first throughout.
|
|
37
43
|
*/
|
|
38
|
-
|
|
44
|
+
transactions<Q extends PositionTransactionsQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<WithRows<TransactionsPage, 'transactions', Q>>;
|
|
45
|
+
/**
|
|
46
|
+
* Every transaction of a position, newest first throughout, following the cursor (`transactionsNextCursor` →
|
|
47
|
+
* `before`). Each page's rows are yielded from its end, so the order holds across pages. Each page is a metered
|
|
48
|
+
* request. When the last page says the API's list is not the whole history (`transactionsPartial`,
|
|
49
|
+
* `transactionsTruncated` or `transactionsDegraded`), it throws `TransactionsIncompleteError` after yielding every
|
|
50
|
+
* row it got. Stopping at `maxPages` or `maxItems` throws nothing.
|
|
51
|
+
*/
|
|
52
|
+
iterateTransactions<Q extends PositionTransactionsQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Transaction, Q>, void, undefined>;
|
|
39
53
|
/** `GET .../charts`: the position's and its pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
|
|
40
|
-
charts<Q extends PositionChartsQuery =
|
|
54
|
+
charts<Q extends PositionChartsQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
|
|
41
55
|
/** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
|
|
42
56
|
exportCsv(query?: PositionsListQuery, options?: RequestOptions): APIPromise<CsvPage>;
|
|
43
57
|
/** Every page of `list` as CSV, each with its own header row. Each page is a metered request. */
|
|
44
|
-
exportCsvPages(query?: PositionsListQuery, options?: RequestOptions &
|
|
58
|
+
exportCsvPages(query?: PositionsListQuery, options?: RequestOptions & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
|
|
45
59
|
}
|
|
@@ -2,12 +2,22 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.Positions = exports.POSITION_BATCH_MAX = void 0;
|
|
4
4
|
const api_promise_js_1 = require("../api-promise.js");
|
|
5
|
+
const errors_js_1 = require("../errors.js");
|
|
5
6
|
const csv_js_1 = require("../csv.js");
|
|
6
7
|
const base_js_1 = require("./base.js");
|
|
8
|
+
const INCOMPLETE_FLAGS = ['transactionsPartial', 'transactionsTruncated', 'transactionsDegraded'];
|
|
7
9
|
/** Most ids one `GET /v1/positions/batch` call takes. */
|
|
8
10
|
exports.POSITION_BATCH_MAX = 100;
|
|
9
11
|
function idList(ids) {
|
|
10
|
-
const raw = typeof ids === 'string'
|
|
12
|
+
const raw = typeof ids === 'string'
|
|
13
|
+
? ids.split(',')
|
|
14
|
+
: ids.map((id) => {
|
|
15
|
+
// A number past 2^53 has already lost digits: sending it would ask for another position.
|
|
16
|
+
if (typeof id === 'number' && !Number.isSafeInteger(id)) {
|
|
17
|
+
throw new TypeError(`positions.batch: id ${id} is not a safe integer; pass a large id as a string or a bigint`);
|
|
18
|
+
}
|
|
19
|
+
return String(id);
|
|
20
|
+
});
|
|
11
21
|
const seen = new Set();
|
|
12
22
|
const out = [];
|
|
13
23
|
for (const id of raw.map((s) => s.trim()).filter(Boolean)) {
|
|
@@ -21,7 +31,10 @@ function idList(ids) {
|
|
|
21
31
|
class Positions extends base_js_1.Resource {
|
|
22
32
|
/**
|
|
23
33
|
* `GET /v1/positions`: a ranked, filtered page of positions. The defaults hide closed, risky and small-pool
|
|
24
|
-
* positions
|
|
34
|
+
* positions. For everything a wallet holds pass
|
|
35
|
+
* `{ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true, sort: 'underlying_value' }`: the default
|
|
36
|
+
* sort (`apr`) ranks open positions only, so without a non-rate sort the closed ones are left out. These are the rows
|
|
37
|
+
* `wallets.summary` totals.
|
|
25
38
|
*/
|
|
26
39
|
list(query, options) {
|
|
27
40
|
return this.call('positions.list', undefined, (0, base_js_1.toQuery)(query), options);
|
|
@@ -43,7 +56,13 @@ class Positions extends base_js_1.Resource {
|
|
|
43
56
|
* (`.withMeta()` → `meta.unitsCharged`).
|
|
44
57
|
*/
|
|
45
58
|
batch(query, options) {
|
|
46
|
-
|
|
59
|
+
let ids;
|
|
60
|
+
try {
|
|
61
|
+
ids = idList(query.ids);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
return new api_promise_js_1.APIPromise(Promise.reject(e));
|
|
65
|
+
}
|
|
47
66
|
if (ids.length === 0)
|
|
48
67
|
return new api_promise_js_1.APIPromise(Promise.reject(new TypeError('positions.batch: `ids` is empty')));
|
|
49
68
|
return this.call('positions.batch', undefined, (0, base_js_1.toQuery)(query, { ids: ids.join(',') }), options);
|
|
@@ -52,9 +71,19 @@ class Positions extends base_js_1.Resource {
|
|
|
52
71
|
* Any number of ids: `batch` calls of 100, one after another, merged in order. Costs exactly what the separate
|
|
53
72
|
* calls cost (the batch is priced per position). `.withMeta()` gives the last call's metadata with
|
|
54
73
|
* `unitsCharged` and `retries` summed over all calls.
|
|
74
|
+
*
|
|
75
|
+
* When a chunk fails after earlier chunks were served (and charged), it throws `BatchAllIncompleteError` with the
|
|
76
|
+
* served rows in `data` and the rest in `remainingIds`; the chunk's own error is its `cause`. A failure on the
|
|
77
|
+
* first chunk is thrown as it is.
|
|
55
78
|
*/
|
|
56
79
|
batchAll(query, options) {
|
|
57
|
-
|
|
80
|
+
let ids;
|
|
81
|
+
try {
|
|
82
|
+
ids = idList(query.ids);
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
return new api_promise_js_1.APIPromise(Promise.reject(e));
|
|
86
|
+
}
|
|
58
87
|
if (ids.length === 0)
|
|
59
88
|
return new api_promise_js_1.APIPromise(Promise.reject(new TypeError('positions.batchAll: `ids` is empty')));
|
|
60
89
|
const run = async () => {
|
|
@@ -65,7 +94,16 @@ class Positions extends base_js_1.Resource {
|
|
|
65
94
|
let retries = 0;
|
|
66
95
|
for (let i = 0; i < ids.length; i += exports.POSITION_BATCH_MAX) {
|
|
67
96
|
const chunk = ids.slice(i, i + exports.POSITION_BATCH_MAX);
|
|
68
|
-
|
|
97
|
+
let r;
|
|
98
|
+
try {
|
|
99
|
+
r = await this.batch({ ...query, ids: chunk }, options).withMeta();
|
|
100
|
+
}
|
|
101
|
+
catch (e) {
|
|
102
|
+
if (merged === undefined)
|
|
103
|
+
throw e;
|
|
104
|
+
const served = i;
|
|
105
|
+
throw new errors_js_1.BatchAllIncompleteError(`positions.batchAll: ${served} of ${ids.length} ids were served before a chunk failed: ${e instanceof Error ? e.message : String(e)}`, { cause: e, data: merged, unitsCharged: unitsKnown ? units : undefined, remainingIds: ids.slice(i) });
|
|
106
|
+
}
|
|
69
107
|
const data = r.data;
|
|
70
108
|
if (merged === undefined) {
|
|
71
109
|
merged = { ...data, positions: [...data.positions], missing: [...data.missing] };
|
|
@@ -89,13 +127,20 @@ class Positions extends base_js_1.Resource {
|
|
|
89
127
|
get(chainId, protocol, positionId, query, options) {
|
|
90
128
|
return this.call('positions.detail', { chainId, protocol, positionId }, (0, base_js_1.toQuery)(query), options);
|
|
91
129
|
}
|
|
92
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* `GET .../transactions`: one page of a position's transactions. The first page holds the newest transactions and
|
|
132
|
+
* `transactionsNextCursor` (passed back as `before`) gives the next older page, but inside a page the rows are oldest
|
|
133
|
+
* to newest, as the API sends them. `iterateTransactions` yields newest first throughout.
|
|
134
|
+
*/
|
|
93
135
|
transactions(chainId, protocol, positionId, query, options) {
|
|
94
136
|
return this.call('positions.transactions', { chainId, protocol, positionId }, (0, base_js_1.toQuery)(query), options);
|
|
95
137
|
}
|
|
96
138
|
/**
|
|
97
|
-
* Every transaction of a position, newest first, following the cursor (`transactionsNextCursor` →
|
|
98
|
-
* Each page is a metered
|
|
139
|
+
* Every transaction of a position, newest first throughout, following the cursor (`transactionsNextCursor` →
|
|
140
|
+
* `before`). Each page's rows are yielded from its end, so the order holds across pages. Each page is a metered
|
|
141
|
+
* request. When the last page says the API's list is not the whole history (`transactionsPartial`,
|
|
142
|
+
* `transactionsTruncated` or `transactionsDegraded`), it throws `TransactionsIncompleteError` after yielding every
|
|
143
|
+
* row it got. Stopping at `maxPages` or `maxItems` throws nothing.
|
|
99
144
|
*/
|
|
100
145
|
async *iterateTransactions(chainId, protocol, positionId, query, options) {
|
|
101
146
|
const [req, paging] = (0, base_js_1.splitOptions)(options);
|
|
@@ -105,14 +150,23 @@ class Positions extends base_js_1.Resource {
|
|
|
105
150
|
let items = 0;
|
|
106
151
|
for (let n = 0; paging.maxPages === undefined || n < paging.maxPages; n++) {
|
|
107
152
|
const page = (await this.transactions(chainId, protocol, positionId, { ...query, before }, req));
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
153
|
+
// A page arrives oldest to newest; walk it from the end so the whole sequence is newest first.
|
|
154
|
+
for (let i = page.transactions.length - 1; i >= 0; i--) {
|
|
155
|
+
yield page.transactions[i];
|
|
156
|
+
items++;
|
|
157
|
+
if (paging.maxItems !== undefined && items >= paging.maxItems)
|
|
111
158
|
return;
|
|
112
159
|
}
|
|
113
160
|
const next = page.transactionsNextCursor;
|
|
114
|
-
if (!next || page.transactions.length === 0 || next === before)
|
|
161
|
+
if (!next || page.transactions.length === 0 || next === before) {
|
|
162
|
+
// The oldest row the API had. Its flags say whether that is the position's whole history.
|
|
163
|
+
const reasons = INCOMPLETE_FLAGS.filter((flag) => page[flag] === true);
|
|
164
|
+
if (reasons.length > 0) {
|
|
165
|
+
throw new errors_js_1.TransactionsIncompleteError(`positions.iterateTransactions: the API's transaction list for this position is not complete (${reasons.join(', ')}); ` +
|
|
166
|
+
`${items} transactions were yielded`, { reasons, yielded: items });
|
|
167
|
+
}
|
|
115
168
|
return;
|
|
169
|
+
}
|
|
116
170
|
before = next;
|
|
117
171
|
}
|
|
118
172
|
}
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import type { APIPromise } from '../api-promise.js';
|
|
2
2
|
import type { RequestOptions } from '../transport.js';
|
|
3
|
-
import type { PagingOptions, Pool, RowOf, TokenLookup, TokenQuery, WithRows } from '../types.js';
|
|
3
|
+
import type { PagingOptions, Pool, RowOf, TokenLookup, TokenQuery, TokenSearch, TokenSearchQuery, WithRows } from '../types.js';
|
|
4
4
|
import { Resource } from './base.js';
|
|
5
5
|
export declare class Tokens extends Resource {
|
|
6
6
|
/**
|
|
7
7
|
* `GET /v1/tokens/{chainId}/{address}`: one token's USD price and where it came from, what the API knows about
|
|
8
8
|
* it, its risk flags, and a page of the pools holding it. The chain's native token is the zero address.
|
|
9
9
|
*/
|
|
10
|
-
get<Q extends TokenQuery =
|
|
10
|
+
get<Q extends TokenQuery = {}>(chainId: number, address: string, query?: Q, options?: RequestOptions): APIPromise<WithRows<TokenLookup, 'pools', Q>>;
|
|
11
|
+
/**
|
|
12
|
+
* `GET /v1/tokens/search`: find tokens by symbol, name or address (`q`, 1 to 100 characters), best match first,
|
|
13
|
+
* on one chain (`chainId`) or every chain. `limit` 1 to 20, default 5. One flat charge per answer; a `partial`
|
|
14
|
+
* answer (some chains not searchable yet, listed in `pendingChains`) is not charged.
|
|
15
|
+
*/
|
|
16
|
+
search(query: TokenSearchQuery, options?: RequestOptions): APIPromise<TokenSearch>;
|
|
11
17
|
/** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
|
|
12
|
-
iteratePools<Q extends TokenQuery =
|
|
18
|
+
iteratePools<Q extends TokenQuery = {}>(chainId: number, address: string, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
|
|
13
19
|
}
|
|
@@ -10,6 +10,14 @@ class Tokens extends base_js_1.Resource {
|
|
|
10
10
|
get(chainId, address, query, options) {
|
|
11
11
|
return this.call('tokens.detail', { chainId, address }, (0, base_js_1.toQuery)(query), options);
|
|
12
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* `GET /v1/tokens/search`: find tokens by symbol, name or address (`q`, 1 to 100 characters), best match first,
|
|
15
|
+
* on one chain (`chainId`) or every chain. `limit` 1 to 20, default 5. One flat charge per answer; a `partial`
|
|
16
|
+
* answer (some chains not searchable yet, listed in `pendingChains`) is not charged.
|
|
17
|
+
*/
|
|
18
|
+
search(query, options) {
|
|
19
|
+
return this.call('tokens.search', undefined, (0, base_js_1.toQuery)(query), options);
|
|
20
|
+
}
|
|
13
21
|
/** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
|
|
14
22
|
iteratePools(chainId, address, query, options) {
|
|
15
23
|
const [req, paging] = (0, base_js_1.splitOptions)(options);
|
package/dist/cjs/routes.d.ts
CHANGED
|
@@ -46,6 +46,10 @@ export declare const ROUTES: {
|
|
|
46
46
|
readonly path: "/v1/tokens/{chainId}/{address}";
|
|
47
47
|
readonly metered: true;
|
|
48
48
|
};
|
|
49
|
+
readonly 'tokens.search': {
|
|
50
|
+
readonly path: "/v1/tokens/search";
|
|
51
|
+
readonly metered: true;
|
|
52
|
+
};
|
|
49
53
|
readonly 'wallets.summary': {
|
|
50
54
|
readonly path: "/v1/wallets/{address}";
|
|
51
55
|
readonly metered: true;
|
package/dist/cjs/routes.js
CHANGED
|
@@ -16,6 +16,7 @@ exports.ROUTES = {
|
|
|
16
16
|
'pools.detail': { path: '/v1/pools/{chainId}/{protocol}/{poolId}', metered: true },
|
|
17
17
|
'pools.charts': { path: '/v1/pools/{chainId}/{protocol}/{poolId}/charts', metered: true },
|
|
18
18
|
'tokens.detail': { path: '/v1/tokens/{chainId}/{address}', metered: true },
|
|
19
|
+
'tokens.search': { path: '/v1/tokens/search', metered: true },
|
|
19
20
|
'wallets.summary': { path: '/v1/wallets/{address}', metered: true },
|
|
20
21
|
'hooks.list': { path: '/v1/hooks', metered: true },
|
|
21
22
|
chains: { path: '/v1/chains', metered: false },
|
|
@@ -31,6 +32,10 @@ function fillPath(op, params = {}) {
|
|
|
31
32
|
if (v === undefined || v === null || String(v) === '') {
|
|
32
33
|
throw new TypeError(`${op}: missing path parameter \`${name}\``);
|
|
33
34
|
}
|
|
35
|
+
// A number past 2^53 has already lost digits: sending it would ask for another id.
|
|
36
|
+
if (typeof v === 'number' && !Number.isSafeInteger(v)) {
|
|
37
|
+
throw new TypeError(`${op}: \`${name}\` ${v} is not a safe integer; pass a large id as a string or a bigint`);
|
|
38
|
+
}
|
|
34
39
|
// encodeURIComponent leaves `.` and `..` alone and URL parsing collapses them, which would call another route.
|
|
35
40
|
if (String(v) === '.' || String(v) === '..') {
|
|
36
41
|
throw new TypeError(`${op}: \`${name}\` cannot be \`${String(v)}\``);
|
package/dist/cjs/transport.d.ts
CHANGED
|
@@ -9,11 +9,11 @@ export type Query = Readonly<Record<string, QueryValue>>;
|
|
|
9
9
|
/** Per-call options, the last argument of every method. */
|
|
10
10
|
export interface RequestOptions {
|
|
11
11
|
/** Cancels the call, including a retry wait. The platform's `AbortError` (or the signal's reason) is thrown. */
|
|
12
|
-
signal?: AbortSignal;
|
|
12
|
+
signal?: AbortSignal | undefined;
|
|
13
13
|
/** Overrides the client's `timeoutMs` for this call (per attempt). */
|
|
14
|
-
timeoutMs?: number;
|
|
14
|
+
timeoutMs?: number | undefined;
|
|
15
15
|
/** Overrides the client's `maxRetries` for this call. */
|
|
16
|
-
maxRetries?: number;
|
|
16
|
+
maxRetries?: number | undefined;
|
|
17
17
|
}
|
|
18
18
|
export interface LimitInfo {
|
|
19
19
|
limit: number;
|
|
@@ -53,7 +53,7 @@ export interface TransportConfig {
|
|
|
53
53
|
export interface RawRequest {
|
|
54
54
|
/** Path with its parameters already filled in, e.g. `/v1/pools/1/uniswap-v4/0xabc`. */
|
|
55
55
|
path: string;
|
|
56
|
-
query?: Query;
|
|
56
|
+
query?: Query | undefined;
|
|
57
57
|
/** Metered routes send the key; free routes never do. */
|
|
58
58
|
metered: boolean;
|
|
59
59
|
accept: 'json' | 'csv';
|
|
@@ -74,9 +74,10 @@ export declare function metaOf(status: number, url: string, retries: number, hea
|
|
|
74
74
|
* Whether a failed attempt is retried.
|
|
75
75
|
*
|
|
76
76
|
* A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
|
|
77
|
-
* before any charge), a 503 (the API credits it back), a
|
|
78
|
-
* connection
|
|
79
|
-
*
|
|
77
|
+
* before any charge), a 503 (the API credits it back), and a connection that was never opened. A timeout, a
|
|
78
|
+
* connection lost mid-request, a 502 and a 504 are NOT retried on a metered route: the API may have served, and
|
|
79
|
+
* charged, the first attempt. A 502 comes from the gateway, not the API, so the API's refund of its own 5xx never
|
|
80
|
+
* ran (a process stopped by a deploy after the charge answers 502), and a retry could be billed twice.
|
|
80
81
|
* A free route costs nothing, so those are retried there too.
|
|
81
82
|
* Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
|
|
82
83
|
*/
|
package/dist/cjs/transport.js
CHANGED
|
@@ -127,9 +127,10 @@ async function readText(res, max) {
|
|
|
127
127
|
* Whether a failed attempt is retried.
|
|
128
128
|
*
|
|
129
129
|
* A metered call is retried only when the API cannot have charged it: the burst rate limit (429 `rate`, refused
|
|
130
|
-
* before any charge), a 503 (the API credits it back), a
|
|
131
|
-
* connection
|
|
132
|
-
*
|
|
130
|
+
* before any charge), a 503 (the API credits it back), and a connection that was never opened. A timeout, a
|
|
131
|
+
* connection lost mid-request, a 502 and a 504 are NOT retried on a metered route: the API may have served, and
|
|
132
|
+
* charged, the first attempt. A 502 comes from the gateway, not the API, so the API's refund of its own 5xx never
|
|
133
|
+
* ran (a process stopped by a deploy after the charge answers 502), and a retry could be billed twice.
|
|
133
134
|
* A free route costs nothing, so those are retried there too.
|
|
134
135
|
* Never retried: the monthly quota (nothing changes until it resets), 400 / 401 / 403 / 404, and 500.
|
|
135
136
|
*/
|
|
@@ -140,7 +141,7 @@ function isRetryable(e, metered) {
|
|
|
140
141
|
return !metered || e.connectFailed;
|
|
141
142
|
if (e instanceof errors_js_1.TimeoutError)
|
|
142
143
|
return !metered;
|
|
143
|
-
return e instanceof errors_js_1.APIError && (e.status === 502 ||
|
|
144
|
+
return e instanceof errors_js_1.APIError && (e.status === 502 || e.status === 504) && !metered;
|
|
144
145
|
}
|
|
145
146
|
/** Error codes that mean no connection was made, so nothing reached the API (Node / undici names). */
|
|
146
147
|
const CONNECT_FAILED_CODES = new Set([
|
|
@@ -267,6 +268,9 @@ class Transport {
|
|
|
267
268
|
});
|
|
268
269
|
}
|
|
269
270
|
const text = await readText(res, this.#config.maxBodyBytes);
|
|
271
|
+
// An error answer over the cap still gets its own class (and `Retry-After`), so a 429 / 503 is still retried.
|
|
272
|
+
if (text === null && (res.status < 200 || res.status >= 300))
|
|
273
|
+
throw (0, errors_js_1.errorFromResponse)(res.status, res.headers, undefined, url);
|
|
270
274
|
if (text === null) {
|
|
271
275
|
throw new errors_js_1.APIError('api_error', `The response is larger than maxBodyBytes (${this.#config.maxBodyBytes})`, {
|
|
272
276
|
status: res.status,
|
package/dist/cjs/types.d.ts
CHANGED
|
@@ -18,6 +18,9 @@ export type TokenPrice = S['TokenPrice'];
|
|
|
18
18
|
export type TokenSecurity = S['TokenSecurity'];
|
|
19
19
|
export type TokenTrust = S['TokenTrust'];
|
|
20
20
|
export type TokenLookup = S['TokenLookup'];
|
|
21
|
+
export type TokenSearch = S['TokenSearch'];
|
|
22
|
+
export type TokenSearchMatch = S['TokenSearchMatch'];
|
|
23
|
+
export type TokenSearchPool = S['TokenSearchPool'];
|
|
21
24
|
export type Hook = S['Hook'];
|
|
22
25
|
export type HookList = S['HookList'];
|
|
23
26
|
export type WalletFigures = S['WalletFigures'];
|
|
@@ -36,7 +39,10 @@ export type ErrorBody = S['Error'];
|
|
|
36
39
|
* type error. `GET /v1/protocols` (`tw.protocols()`) is the live list.
|
|
37
40
|
*/
|
|
38
41
|
export type ProtocolKey = 'uniswap-v4' | (string & {});
|
|
39
|
-
/**
|
|
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
|
+
*/
|
|
40
46
|
export type PositionId = string | bigint | number;
|
|
41
47
|
/** Dotted field paths, e.g. `['positionId', 'metrics.apr']` or `'positionId,metrics.apr'`. At most 60. */
|
|
42
48
|
export type Fields = string | readonly string[];
|
|
@@ -45,10 +51,14 @@ type RawQuery<Op extends keyof operations> = NonNullable<operations[Op]['paramet
|
|
|
45
51
|
export type OmitKeys<T, K extends PropertyKey> = {
|
|
46
52
|
[P in keyof T as P extends K ? never : P]: T[P];
|
|
47
53
|
};
|
|
48
|
-
|
|
49
|
-
|
|
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;
|
|
50
60
|
} : unknown) & ('fields' extends keyof Q ? {
|
|
51
|
-
fields?: Fields;
|
|
61
|
+
fields?: Fields | undefined;
|
|
52
62
|
} : unknown);
|
|
53
63
|
export type PositionsListQuery = Widen<RawQuery<'positions.list'>>;
|
|
54
64
|
export type PositionsBatchQuery = OmitKeys<Widen<RawQuery<'positions.batch'>>, 'ids'> & {
|
|
@@ -62,21 +72,22 @@ export type PoolsListQuery = Widen<RawQuery<'pools.list'>>;
|
|
|
62
72
|
export type PoolDetailQuery = Widen<RawQuery<'pools.detail'>>;
|
|
63
73
|
export type PoolChartsQuery = Widen<RawQuery<'pools.charts'>>;
|
|
64
74
|
export type TokenQuery = Widen<RawQuery<'tokens.detail'>>;
|
|
75
|
+
export type TokenSearchQuery = Widen<RawQuery<'tokens.search'>>;
|
|
65
76
|
export type WalletSummaryQuery = Widen<RawQuery<'wallets.summary'>>;
|
|
66
77
|
export type HooksListQuery = Widen<RawQuery<'hooks.list'>>;
|
|
67
78
|
/** Every property optional, all the way down. */
|
|
68
79
|
export type DeepPartial<T> = T extends readonly (infer U)[] ? DeepPartial<U>[] : T extends object ? {
|
|
69
80
|
[K in keyof T]?: DeepPartial<T[K]>;
|
|
70
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;
|
|
71
84
|
/**
|
|
72
|
-
* True
|
|
73
|
-
*
|
|
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.
|
|
74
89
|
*/
|
|
75
|
-
export type IsProjected<Q> = Q extends
|
|
76
|
-
fields: Fields;
|
|
77
|
-
} ? true : Q extends {
|
|
78
|
-
view: 'compact';
|
|
79
|
-
} ? true : false;
|
|
90
|
+
export type IsProjected<Q> = KeyOff<Q, 'fields', undefined> extends true ? (KeyOff<Q, 'view', 'full' | undefined> extends true ? false : true) : true;
|
|
80
91
|
type ElementOf<A> = A extends readonly (infer U)[] ? U : never;
|
|
81
92
|
/** `L` with the rows under `K` made `DeepPartial` when `Q` projects them. */
|
|
82
93
|
export type WithRows<L, K extends keyof L, Q> = IsProjected<Q> extends true ? OmitKeys<L, K> & {
|
|
@@ -92,8 +103,10 @@ export type RowOf<T, Q> = IsProjected<Q> extends true ? DeepPartial<T> : T;
|
|
|
92
103
|
*/
|
|
93
104
|
export interface PagingOptions {
|
|
94
105
|
/** Stop after this many pages. */
|
|
95
|
-
maxPages?: number;
|
|
106
|
+
maxPages?: number | undefined;
|
|
96
107
|
/** Stop after this many rows (`iterate*` only). */
|
|
97
|
-
maxItems?: number;
|
|
108
|
+
maxItems?: number | undefined;
|
|
98
109
|
}
|
|
110
|
+
/** Limits for `exportCsvPages`: a CSV page is counted whole, so only `maxPages` applies. */
|
|
111
|
+
export type CsvPagingOptions = Pick<PagingOptions, 'maxPages'>;
|
|
99
112
|
export {};
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** The package version, sent in `User-Agent`. `test/version.spec.ts` holds it to `package.json`. */
|
|
2
|
-
export declare const VERSION = "0.1.
|
|
2
|
+
export declare const VERSION = "0.1.1";
|
package/dist/cjs/version.js
CHANGED
package/dist/esm/client.d.ts
CHANGED
|
@@ -12,24 +12,24 @@ export interface TickwiseOptions {
|
|
|
12
12
|
* Your API key from the Tickwise portal. When omitted, `TICKWISE_API_KEY` is read from the environment (on
|
|
13
13
|
* runtimes that have `process.env`). Only metered routes send it; the free routes never do.
|
|
14
14
|
*/
|
|
15
|
-
apiKey?: string;
|
|
15
|
+
apiKey?: string | undefined;
|
|
16
16
|
/** Default `https://api.tickwise.xyz`. */
|
|
17
|
-
baseUrl?: string;
|
|
17
|
+
baseUrl?: string | undefined;
|
|
18
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;
|
|
19
|
+
keyHeader?: string | undefined;
|
|
20
20
|
/** Per attempt, in milliseconds. Default 30000. */
|
|
21
|
-
timeoutMs?: number;
|
|
21
|
+
timeoutMs?: number | undefined;
|
|
22
22
|
/**
|
|
23
|
-
* Retries of failures the API did not charge: a 429 rate-limit, 503,
|
|
24
|
-
* route also retries a timeout, a dropped connection and a 504). Default 2; 0 turns them off.
|
|
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
25
|
*/
|
|
26
|
-
maxRetries?: number;
|
|
26
|
+
maxRetries?: number | undefined;
|
|
27
27
|
/** A `Retry-After` longer than this (seconds) is thrown as the error instead of waited out. Default 60. */
|
|
28
|
-
maxRetryAfterSec?: number;
|
|
28
|
+
maxRetryAfterSec?: number | undefined;
|
|
29
29
|
/** Refuse a response body larger than this many bytes. Off by default. */
|
|
30
|
-
maxBodyBytes?: number;
|
|
30
|
+
maxBodyBytes?: number | undefined;
|
|
31
31
|
/** A `fetch` to use instead of the global one (tests, proxies, instrumentation). */
|
|
32
|
-
fetch?: typeof fetch;
|
|
32
|
+
fetch?: typeof fetch | undefined;
|
|
33
33
|
}
|
|
34
34
|
/**
|
|
35
35
|
* The Tickwise API client.
|
package/dist/esm/client.js
CHANGED
|
@@ -39,7 +39,8 @@ export class Tickwise {
|
|
|
39
39
|
#meta;
|
|
40
40
|
#baseUrl;
|
|
41
41
|
constructor(options = {}) {
|
|
42
|
-
|
|
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(/\/+$/, '');
|
|
43
44
|
let parsed;
|
|
44
45
|
try {
|
|
45
46
|
parsed = new URL(baseUrl);
|
|
@@ -53,6 +54,10 @@ export class Tickwise {
|
|
|
53
54
|
if (parsed.search || parsed.hash || parsed.username || parsed.password) {
|
|
54
55
|
throw new TypeError('Tickwise: `baseUrl` must not carry a query, fragment or credentials');
|
|
55
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
|
+
}
|
|
56
61
|
const f = options.fetch ?? globalThis.fetch;
|
|
57
62
|
if (typeof f !== 'function') {
|
|
58
63
|
throw new TypeError('Tickwise: no global `fetch` on this runtime; pass one as `fetch` (Node 20.3+ has it built in)');
|
package/dist/esm/errors.d.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Every error the
|
|
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
|
|
3
5
|
* error bodies are `{ error: string }` with no machine code, and their text can change. `kind` is derived from the
|
|
4
6
|
* status code and, for a 429, from the `X-RateLimit-Reason` header.
|
|
5
7
|
*/
|
|
6
|
-
export type TickwiseErrorKind = 'bad_request' | 'authentication' | 'permission_denied' | 'not_found' | 'rate_limited' | 'quota_exceeded' | 'unavailable' | 'api_error' | 'redirect' | 'connection' | 'timeout';
|
|
8
|
+
export type TickwiseErrorKind = 'bad_request' | 'authentication' | 'permission_denied' | 'not_found' | 'rate_limited' | 'quota_exceeded' | 'unavailable' | 'api_error' | 'redirect' | 'connection' | 'timeout' | 'incomplete';
|
|
7
9
|
export interface TickwiseErrorInit {
|
|
8
|
-
status?: number;
|
|
10
|
+
status?: number | undefined;
|
|
9
11
|
body?: unknown;
|
|
10
|
-
headers?: Headers;
|
|
11
|
-
retryAfterSec?: number;
|
|
12
|
-
url?: string;
|
|
12
|
+
headers?: Headers | undefined;
|
|
13
|
+
retryAfterSec?: number | undefined;
|
|
14
|
+
url?: string | undefined;
|
|
13
15
|
cause?: unknown;
|
|
14
16
|
}
|
|
15
17
|
export declare class TickwiseError extends Error {
|
|
@@ -77,9 +79,55 @@ export declare class ConnectionError extends TickwiseError {
|
|
|
77
79
|
export declare class TimeoutError extends TickwiseError {
|
|
78
80
|
constructor(message: string, init?: TickwiseErrorInit);
|
|
79
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
|
+
}
|
|
80
125
|
/** The most useful text an error body carries: Nest validation detail first, then `error`. */
|
|
81
126
|
export declare function errorMessage(body: unknown, status: number): string;
|
|
82
|
-
/**
|
|
83
|
-
|
|
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;
|
|
84
132
|
/** The error for a non-2xx answer. */
|
|
85
133
|
export declare function errorFromResponse(status: number, headers: Headers, body: unknown, url: string): APIError;
|