@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.
Files changed (42) hide show
  1. package/README.md +30 -12
  2. package/dist/cjs/client.d.ts +10 -10
  3. package/dist/cjs/client.js +6 -1
  4. package/dist/cjs/errors.d.ts +56 -8
  5. package/dist/cjs/errors.js +65 -4
  6. package/dist/cjs/generated/openapi.d.ts +129 -1
  7. package/dist/cjs/index.d.ts +1 -1
  8. package/dist/cjs/index.js +4 -1
  9. package/dist/cjs/resources/hooks.d.ts +2 -2
  10. package/dist/cjs/resources/pools.d.ts +7 -7
  11. package/dist/cjs/resources/positions.d.ts +27 -13
  12. package/dist/cjs/resources/positions.js +66 -12
  13. package/dist/cjs/resources/tokens.d.ts +9 -3
  14. package/dist/cjs/resources/tokens.js +8 -0
  15. package/dist/cjs/routes.d.ts +4 -0
  16. package/dist/cjs/routes.js +5 -0
  17. package/dist/cjs/transport.d.ts +8 -7
  18. package/dist/cjs/transport.js +8 -4
  19. package/dist/cjs/types.d.ts +26 -13
  20. package/dist/cjs/version.d.ts +1 -1
  21. package/dist/cjs/version.js +1 -1
  22. package/dist/esm/client.d.ts +10 -10
  23. package/dist/esm/client.js +6 -1
  24. package/dist/esm/errors.d.ts +56 -8
  25. package/dist/esm/errors.js +61 -3
  26. package/dist/esm/generated/openapi.d.ts +129 -1
  27. package/dist/esm/index.d.ts +1 -1
  28. package/dist/esm/index.js +1 -1
  29. package/dist/esm/resources/hooks.d.ts +2 -2
  30. package/dist/esm/resources/pools.d.ts +7 -7
  31. package/dist/esm/resources/positions.d.ts +27 -13
  32. package/dist/esm/resources/positions.js +66 -12
  33. package/dist/esm/resources/tokens.d.ts +9 -3
  34. package/dist/esm/resources/tokens.js +8 -0
  35. package/dist/esm/routes.d.ts +4 -0
  36. package/dist/esm/routes.js +5 -0
  37. package/dist/esm/transport.d.ts +8 -7
  38. package/dist/esm/transport.js +8 -4
  39. package/dist/esm/types.d.ts +26 -13
  40. package/dist/esm/version.d.ts +1 -1
  41. package/dist/esm/version.js +1 -1
  42. package/package.json +1 -1
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Every error the SDK throws is a `TickwiseError`. Branch on `instanceof` or on `kind`, never on `message`: the API's
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
  */
@@ -109,6 +111,54 @@ export class TimeoutError extends TickwiseError {
109
111
  this.name = 'TimeoutError';
110
112
  }
111
113
  }
114
+ /**
115
+ * A helper that makes several requests (`positions.batchAll`, `positions.iterateTransactions`) could not get
116
+ * everything. What it did get is on the error; `cause` is the failure that stopped it, when one did.
117
+ */
118
+ export class IncompleteError extends TickwiseError {
119
+ constructor(message, init = {}) {
120
+ super('incomplete', message, init);
121
+ this.name = 'IncompleteError';
122
+ }
123
+ }
124
+ /**
125
+ * `positions.batchAll` stopped on a failed chunk after earlier chunks were served, and charged. The served rows are
126
+ * in `data`; pass `remainingIds` to `batchAll` again to finish without paying for the served ones twice. `cause` is
127
+ * the chunk's error (a `QuotaExceededError`, a `TimeoutError`, the signal's reason after an abort, ...).
128
+ */
129
+ export class BatchAllIncompleteError extends IncompleteError {
130
+ /** The chunks served before the failure, merged as `batchAll` returns them. */
131
+ data;
132
+ /** Units the served chunks were charged; undefined when a chunk's answer did not say. */
133
+ unitsCharged;
134
+ /** The ids not served: the failed chunk's and every later one, in order. */
135
+ remainingIds;
136
+ constructor(message, init) {
137
+ super(message, init);
138
+ this.name = 'BatchAllIncompleteError';
139
+ this.data = init.data;
140
+ this.unitsCharged = init.unitsCharged;
141
+ this.remainingIds = init.remainingIds;
142
+ }
143
+ }
144
+ /**
145
+ * `positions.iterateTransactions` reached the oldest transaction the API had, but the last page said the list is not
146
+ * complete: `transactionsPartial` (only the newest transactions were ready; ask again in a few seconds),
147
+ * `transactionsTruncated` (the history is longer than the API reads; the oldest are missing) or
148
+ * `transactionsDegraded` (the list could not be read in full). Every row the API had was yielded before this is
149
+ * thrown.
150
+ */
151
+ export class TransactionsIncompleteError extends IncompleteError {
152
+ reasons;
153
+ /** How many transactions were yielded. */
154
+ yielded;
155
+ constructor(message, init) {
156
+ super(message, init);
157
+ this.name = 'TransactionsIncompleteError';
158
+ this.reasons = init.reasons;
159
+ this.yielded = init.yielded;
160
+ }
161
+ }
112
162
  /** The most useful text an error body carries: Nest validation detail first, then `error`. */
113
163
  export function errorMessage(body, status) {
114
164
  if (typeof body === 'string' && body.trim())
@@ -128,11 +178,19 @@ export function errorMessage(body, status) {
128
178
  }
129
179
  return `HTTP ${status}`;
130
180
  }
131
- /** `Retry-After` in whole seconds (the API sends seconds), else the 429 body's `retryAfterSec`. */
132
- export function retryAfterOf(headers, body) {
181
+ /**
182
+ * `Retry-After` in whole seconds: the API sends seconds; a gateway may send an HTTP date, read as the seconds from
183
+ * now (0 when it has passed). Else the 429 body's `retryAfterSec`.
184
+ */
185
+ export function retryAfterOf(headers, body, now = Date.now()) {
133
186
  const h = headers.get('retry-after')?.trim();
134
187
  if (h && /^\d+$/.test(h))
135
188
  return Number(h);
189
+ if (h && /[a-z]/i.test(h)) {
190
+ const at = Date.parse(h);
191
+ if (Number.isFinite(at))
192
+ return Math.max(0, Math.ceil((at - now) / 1000));
193
+ }
136
194
  const b = body && typeof body === 'object' ? body.retryAfterSec : undefined;
137
195
  return typeof b === 'number' && Number.isFinite(b) && b >= 0 ? b : undefined;
138
196
  }
@@ -156,6 +156,23 @@ export interface paths {
156
156
  patch?: never;
157
157
  trace?: never;
158
158
  };
159
+ "/v1/tokens/search": {
160
+ parameters: {
161
+ query?: never;
162
+ header?: never;
163
+ path?: never;
164
+ cookie?: never;
165
+ };
166
+ /** Search tokens */
167
+ get: operations["tokens.search"];
168
+ put?: never;
169
+ post?: never;
170
+ delete?: never;
171
+ options?: never;
172
+ head?: never;
173
+ patch?: never;
174
+ trace?: never;
175
+ };
159
176
  "/v1/wallets/{address}": {
160
177
  parameters: {
161
178
  query?: never;
@@ -571,7 +588,14 @@ export interface components {
571
588
  } & {
572
589
  [key: string]: unknown;
573
590
  });
574
- PoolDetail: components["schemas"]["Pool"];
591
+ PoolDetail: components["schemas"]["Pool"] & ({
592
+ /** @description Share of the pool's open-position USD value held by its 5 largest wallets, in percent (0 to 100). Recomputed about every 10 minutes, off the request. `null` while it is being computed (ask again in a few seconds) or when it cannot be given: no priced open position, or a pool with more than 50,000 open positions. */
593
+ top5HoldersShare?: number | null;
594
+ /** @description Share of the pool's open-position USD value in positions that are in range now, in percent (0 to 100). Computed with `top5HoldersShare`, and `null` in the same cases. */
595
+ inRangeShare?: number | null;
596
+ } & {
597
+ [key: string]: unknown;
598
+ });
575
599
  TokenPrice: {
576
600
  /** @description USD price, or `null` when the API has no price it would value the token with (see `unavailableReason`). */
577
601
  usd: number | null;
@@ -668,6 +692,67 @@ export interface components {
668
692
  } & {
669
693
  [key: string]: unknown;
670
694
  });
695
+ TokenSearchPool: {
696
+ poolId: string;
697
+ /** @description The two symbols, token0 first, e.g. `USDC/WETH`. */
698
+ pair: string;
699
+ /** @description The pool fee in hundredths of a basis point (500 = 0.05%); `null` when not stored. */
700
+ fee: number | null;
701
+ tvlUsd: number;
702
+ /** @description The pool page on the Tickwise website, `/pool/{chainId}/{poolId}`. */
703
+ path: string;
704
+ /** @description `path` as an absolute link. */
705
+ url: string;
706
+ } & {
707
+ [key: string]: unknown;
708
+ };
709
+ TokenSearchMatch: {
710
+ chainId: number;
711
+ /** @description The chain's name. */
712
+ chain: string;
713
+ protocol: string;
714
+ /** @description The token contract, lower case. Pass it to `GET /v1/tokens/{chainId}/{address}`. */
715
+ address: string;
716
+ symbol: string;
717
+ /** @description The token's stored name; `null` when none is stored (most major tokens). */
718
+ name: string | null;
719
+ /**
720
+ * @description How `q` matched: the contract `address`, the exact `symbol`, a common name for a major token (`alias`), the exact stored `name`, the start of the symbol or name (`symbol-prefix`, `name-prefix`), or text inside the name (`name-contains`).
721
+ * @enum {string}
722
+ */
723
+ match: "address" | "symbol" | "alias" | "name" | "symbol-prefix" | "name-prefix" | "name-contains";
724
+ /** @description Summed TVL of the listed pools holding the token on this chain. */
725
+ tvlUsd: number;
726
+ /** @description How many listed pools hold the token on this chain. */
727
+ pools: number;
728
+ /** @description The token page on the Tickwise website, `/token/{chainId}/{address}`. */
729
+ path: string;
730
+ /** @description `path` as an absolute link. */
731
+ url: string;
732
+ /** @description Its biggest pools by TVL, at most 3. */
733
+ topPools: components["schemas"]["TokenSearchPool"][];
734
+ } & {
735
+ [key: string]: unknown;
736
+ };
737
+ TokenSearch: {
738
+ /** @description `q` as it was searched (trimmed). */
739
+ query: string;
740
+ /** @description Best match first; empty when nothing matched. */
741
+ matches: components["schemas"]["TokenSearchMatch"][];
742
+ /** @description Chains that could not be searched yet. Empty on a complete answer. */
743
+ pendingChains: number[];
744
+ /** @description Chains with more listed pools than the index holds; their smallest pools were not searched. */
745
+ truncatedChains: number[];
746
+ /**
747
+ * Format: date-time
748
+ * @description When the oldest index used was built; `null` when no chain could be searched.
749
+ */
750
+ asOf: string | null;
751
+ /** @description Present and true only when `pendingChains` is not empty. The request is not charged. */
752
+ partial?: boolean;
753
+ } & {
754
+ [key: string]: unknown;
755
+ };
671
756
  Hook: {
672
757
  rank: number;
673
758
  chainId: number;
@@ -1604,6 +1689,49 @@ export interface operations {
1604
1689
  503: components["responses"]["Unavailable"];
1605
1690
  };
1606
1691
  };
1692
+ "tokens.search": {
1693
+ parameters: {
1694
+ query: {
1695
+ /**
1696
+ * @description A symbol (`USDC`), a name (`pepe`, `ethereum`) or a token contract (`0x` plus 40 hex), 1 to 100 characters, any case. Missing, blank or with no letter or digit in it is a 400.
1697
+ * @example usdc
1698
+ */
1699
+ q: string;
1700
+ /** @description Search one chain. Omit to search every enabled chain. */
1701
+ chainId?: number;
1702
+ /** @description How many tokens to return, 1–20. A larger value is a 400, not a silent clamp. */
1703
+ limit?: number;
1704
+ };
1705
+ header?: never;
1706
+ path?: never;
1707
+ cookie?: never;
1708
+ };
1709
+ requestBody?: never;
1710
+ responses: {
1711
+ /** @description The matching tokens, best match first. */
1712
+ 200: {
1713
+ headers: {
1714
+ "X-RateLimit-Limit": components["headers"]["XRateLimitLimit"];
1715
+ "X-RateLimit-Remaining": components["headers"]["XRateLimitRemaining"];
1716
+ "X-RateLimit-Reset": components["headers"]["XRateLimitReset"];
1717
+ "X-Quota-Limit": components["headers"]["XQuotaLimit"];
1718
+ "X-Quota-Remaining": components["headers"]["XQuotaRemaining"];
1719
+ "X-Quota-Reset": components["headers"]["XQuotaReset"];
1720
+ "Cache-Control": components["headers"]["CacheControl"];
1721
+ Vary: components["headers"]["Vary"];
1722
+ [name: string]: unknown;
1723
+ };
1724
+ content: {
1725
+ "application/json": components["schemas"]["TokenSearch"];
1726
+ };
1727
+ };
1728
+ 400: components["responses"]["BadRequest"];
1729
+ 401: components["responses"]["Unauthorized"];
1730
+ 403: components["responses"]["Forbidden"];
1731
+ 429: components["responses"]["TooManyRequests"];
1732
+ 503: components["responses"]["Unavailable"];
1733
+ };
1734
+ };
1607
1735
  "wallets.summary": {
1608
1736
  parameters: {
1609
1737
  query?: {
@@ -1,6 +1,6 @@
1
1
  export { Tickwise, type TickwiseOptions } from './client.js';
2
2
  export { APIPromise, type WithMeta } from './api-promise.js';
3
- export { APIError, AuthenticationError, BadRequestError, ConnectionError, NotFoundError, PermissionDeniedError, QuotaExceededError, RateLimitError, ServiceUnavailableError, TickwiseError, type TickwiseErrorKind, TimeoutError, TooManyRequestsError, } from './errors.js';
3
+ export { APIError, AuthenticationError, BadRequestError, BatchAllIncompleteError, ConnectionError, IncompleteError, NotFoundError, PermissionDeniedError, QuotaExceededError, RateLimitError, ServiceUnavailableError, TickwiseError, type TickwiseErrorKind, TimeoutError, TooManyRequestsError, TransactionsIncompleteError, type TransactionsIncompleteReason, } from './errors.js';
4
4
  export type { CsvPage, CsvPagination } from './csv.js';
5
5
  export { DEFAULT_BASE_URL, type LimitInfo, type RequestOptions, type ResponseMeta } from './transport.js';
6
6
  export { POSITION_BATCH_MAX } from './resources/positions.js';
package/dist/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { Tickwise } from './client.js';
2
2
  export { APIPromise } from './api-promise.js';
3
- export { APIError, AuthenticationError, BadRequestError, ConnectionError, NotFoundError, PermissionDeniedError, QuotaExceededError, RateLimitError, ServiceUnavailableError, TickwiseError, TimeoutError, TooManyRequestsError, } from './errors.js';
3
+ export { APIError, AuthenticationError, BadRequestError, BatchAllIncompleteError, ConnectionError, IncompleteError, NotFoundError, PermissionDeniedError, QuotaExceededError, RateLimitError, ServiceUnavailableError, TickwiseError, TimeoutError, TooManyRequestsError, TransactionsIncompleteError, } from './errors.js';
4
4
  export { DEFAULT_BASE_URL } from './transport.js';
5
5
  export { POSITION_BATCH_MAX } from './resources/positions.js';
6
6
  export { HOOKS_ALL_CHAINS_MAX_ROWS } from './resources/hooks.js';
@@ -1,7 +1,7 @@
1
1
  import type { APIPromise } from '../api-promise.js';
2
2
  import { type CsvPage } from '../csv.js';
3
3
  import type { RequestOptions } from '../transport.js';
4
- import type { Hook, HookList, HooksListQuery, PagingOptions } from '../types.js';
4
+ import type { Hook, HookList, HooksListQuery, CsvPagingOptions, PagingOptions } from '../types.js';
5
5
  import { Resource } from './base.js';
6
6
  /**
7
7
  * Deepest row an all-chains hooks page may reach (`page` × `limit`). The API refuses a deeper page with a 400 and
@@ -22,5 +22,5 @@ export declare class Hooks extends Resource {
22
22
  /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
23
23
  exportCsv(query?: HooksListQuery, options?: RequestOptions): APIPromise<CsvPage>;
24
24
  /** Every page of `list` as CSV, each with its own header row (at most 1,000 rows without `chainId`). Each page is a metered request. */
25
- exportCsvPages(query?: HooksListQuery, options?: RequestOptions & PagingOptions): AsyncGenerator<CsvPage, void, undefined>;
25
+ exportCsvPages(query?: HooksListQuery, options?: RequestOptions & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
26
26
  }
@@ -1,21 +1,21 @@
1
1
  import type { APIPromise } from '../api-promise.js';
2
2
  import { type CsvPage } from '../csv.js';
3
3
  import type { RequestOptions } from '../transport.js';
4
- import type { Charts, PagingOptions, Pool, PoolChartsQuery, PoolDetail, PoolDetailQuery, PoolList, PoolsListQuery, ProtocolKey, RowOf, Shaped, WithRows } from '../types.js';
4
+ import type { Charts, CsvPagingOptions, PagingOptions, Pool, PoolChartsQuery, PoolDetail, PoolDetailQuery, PoolList, PoolsListQuery, ProtocolKey, RowOf, Shaped, WithRows } from '../types.js';
5
5
  import { Resource } from './base.js';
6
6
  export declare class Pools extends Resource {
7
7
  /** `GET /v1/pools`: a ranked, filtered page of pools. */
8
- list<Q extends PoolsListQuery = PoolsListQuery>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PoolList, 'pools', Q>>;
8
+ list<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PoolList, 'pools', Q>>;
9
9
  /** Every page of `list`, fetched as you iterate. Starts at `query.page` (default 1). */
10
- pages<Q extends PoolsListQuery = PoolsListQuery>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PoolList, 'pools', Q>, void, undefined>;
10
+ pages<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PoolList, 'pools', Q>, void, undefined>;
11
11
  /** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
12
- iterate<Q extends PoolsListQuery = PoolsListQuery>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
12
+ iterate<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
13
13
  /** `GET /v1/pools/{chainId}/{protocol}/{poolId}`: one pool. */
14
- get<Q extends PoolDetailQuery = PoolDetailQuery>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<PoolDetail, Q>>;
14
+ get<Q extends PoolDetailQuery = {}>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<PoolDetail, Q>>;
15
15
  /** `GET .../charts`: the pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
16
- charts<Q extends PoolChartsQuery = PoolChartsQuery>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
16
+ charts<Q extends PoolChartsQuery = {}>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
17
17
  /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
18
18
  exportCsv(query?: PoolsListQuery, options?: RequestOptions): APIPromise<CsvPage>;
19
19
  /** Every page of `list` as CSV, each with its own header row. Each page is a metered request. */
20
- exportCsvPages(query?: PoolsListQuery, options?: RequestOptions & PagingOptions): AsyncGenerator<CsvPage, void, undefined>;
20
+ exportCsvPages(query?: PoolsListQuery, options?: RequestOptions & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
21
21
  }
@@ -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; for everything a wallet holds pass `{ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true }`.
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 = PositionsListQuery>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PositionList, 'positions', Q>>;
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 = PositionsListQuery>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PositionList, 'positions', Q>, void, undefined>;
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 = PositionsListQuery>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Position, Q>, void, undefined>;
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 = PositionDetailQuery>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<PositionDetail, Q>>;
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
- * Every transaction of a position, newest first, following the cursor (`transactionsNextCursor` → `before`).
36
- * Each page is a metered request.
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
- iterateTransactions<Q extends PositionTransactionsQuery = PositionTransactionsQuery>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Transaction, Q>, void, undefined>;
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 = PositionChartsQuery>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
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 & PagingOptions): AsyncGenerator<CsvPage, void, undefined>;
58
+ exportCsvPages(query?: PositionsListQuery, options?: RequestOptions & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
45
59
  }
@@ -1,10 +1,20 @@
1
1
  import { APIPromise } from '../api-promise.js';
2
+ import { BatchAllIncompleteError, TransactionsIncompleteError } from '../errors.js';
2
3
  import { csvHasRows } from '../csv.js';
3
4
  import { pageIterator, Resource, rowIterator, splitOptions, toQuery } from './base.js';
5
+ const INCOMPLETE_FLAGS = ['transactionsPartial', 'transactionsTruncated', 'transactionsDegraded'];
4
6
  /** Most ids one `GET /v1/positions/batch` call takes. */
5
7
  export const POSITION_BATCH_MAX = 100;
6
8
  function idList(ids) {
7
- const raw = typeof ids === 'string' ? ids.split(',') : ids.map(String);
9
+ const raw = typeof ids === 'string'
10
+ ? ids.split(',')
11
+ : ids.map((id) => {
12
+ // A number past 2^53 has already lost digits: sending it would ask for another position.
13
+ if (typeof id === 'number' && !Number.isSafeInteger(id)) {
14
+ throw new TypeError(`positions.batch: id ${id} is not a safe integer; pass a large id as a string or a bigint`);
15
+ }
16
+ return String(id);
17
+ });
8
18
  const seen = new Set();
9
19
  const out = [];
10
20
  for (const id of raw.map((s) => s.trim()).filter(Boolean)) {
@@ -18,7 +28,10 @@ function idList(ids) {
18
28
  export class Positions extends Resource {
19
29
  /**
20
30
  * `GET /v1/positions`: a ranked, filtered page of positions. The defaults hide closed, risky and small-pool
21
- * positions; for everything a wallet holds pass `{ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true }`.
31
+ * positions. For everything a wallet holds pass
32
+ * `{ owner, status: 'all', minValueUsd: 0, minPoolTvl: 0, includeRisky: true, sort: 'underlying_value' }`: the default
33
+ * sort (`apr`) ranks open positions only, so without a non-rate sort the closed ones are left out. These are the rows
34
+ * `wallets.summary` totals.
22
35
  */
23
36
  list(query, options) {
24
37
  return this.call('positions.list', undefined, toQuery(query), options);
@@ -40,7 +53,13 @@ export class Positions extends Resource {
40
53
  * (`.withMeta()` → `meta.unitsCharged`).
41
54
  */
42
55
  batch(query, options) {
43
- const ids = idList(query.ids);
56
+ let ids;
57
+ try {
58
+ ids = idList(query.ids);
59
+ }
60
+ catch (e) {
61
+ return new APIPromise(Promise.reject(e));
62
+ }
44
63
  if (ids.length === 0)
45
64
  return new APIPromise(Promise.reject(new TypeError('positions.batch: `ids` is empty')));
46
65
  return this.call('positions.batch', undefined, toQuery(query, { ids: ids.join(',') }), options);
@@ -49,9 +68,19 @@ export class Positions extends Resource {
49
68
  * Any number of ids: `batch` calls of 100, one after another, merged in order. Costs exactly what the separate
50
69
  * calls cost (the batch is priced per position). `.withMeta()` gives the last call's metadata with
51
70
  * `unitsCharged` and `retries` summed over all calls.
71
+ *
72
+ * When a chunk fails after earlier chunks were served (and charged), it throws `BatchAllIncompleteError` with the
73
+ * served rows in `data` and the rest in `remainingIds`; the chunk's own error is its `cause`. A failure on the
74
+ * first chunk is thrown as it is.
52
75
  */
53
76
  batchAll(query, options) {
54
- const ids = idList(query.ids);
77
+ let ids;
78
+ try {
79
+ ids = idList(query.ids);
80
+ }
81
+ catch (e) {
82
+ return new APIPromise(Promise.reject(e));
83
+ }
55
84
  if (ids.length === 0)
56
85
  return new APIPromise(Promise.reject(new TypeError('positions.batchAll: `ids` is empty')));
57
86
  const run = async () => {
@@ -62,7 +91,16 @@ export class Positions extends Resource {
62
91
  let retries = 0;
63
92
  for (let i = 0; i < ids.length; i += POSITION_BATCH_MAX) {
64
93
  const chunk = ids.slice(i, i + POSITION_BATCH_MAX);
65
- const r = await this.batch({ ...query, ids: chunk }, options).withMeta();
94
+ let r;
95
+ try {
96
+ r = await this.batch({ ...query, ids: chunk }, options).withMeta();
97
+ }
98
+ catch (e) {
99
+ if (merged === undefined)
100
+ throw e;
101
+ const served = i;
102
+ throw new 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) });
103
+ }
66
104
  const data = r.data;
67
105
  if (merged === undefined) {
68
106
  merged = { ...data, positions: [...data.positions], missing: [...data.missing] };
@@ -86,13 +124,20 @@ export class Positions extends Resource {
86
124
  get(chainId, protocol, positionId, query, options) {
87
125
  return this.call('positions.detail', { chainId, protocol, positionId }, toQuery(query), options);
88
126
  }
89
- /** `GET .../transactions`: one page of a position's transactions, newest first. */
127
+ /**
128
+ * `GET .../transactions`: one page of a position's transactions. The first page holds the newest transactions and
129
+ * `transactionsNextCursor` (passed back as `before`) gives the next older page, but inside a page the rows are oldest
130
+ * to newest, as the API sends them. `iterateTransactions` yields newest first throughout.
131
+ */
90
132
  transactions(chainId, protocol, positionId, query, options) {
91
133
  return this.call('positions.transactions', { chainId, protocol, positionId }, toQuery(query), options);
92
134
  }
93
135
  /**
94
- * Every transaction of a position, newest first, following the cursor (`transactionsNextCursor` → `before`).
95
- * Each page is a metered request.
136
+ * Every transaction of a position, newest first throughout, following the cursor (`transactionsNextCursor` →
137
+ * `before`). Each page's rows are yielded from its end, so the order holds across pages. Each page is a metered
138
+ * request. When the last page says the API's list is not the whole history (`transactionsPartial`,
139
+ * `transactionsTruncated` or `transactionsDegraded`), it throws `TransactionsIncompleteError` after yielding every
140
+ * row it got. Stopping at `maxPages` or `maxItems` throws nothing.
96
141
  */
97
142
  async *iterateTransactions(chainId, protocol, positionId, query, options) {
98
143
  const [req, paging] = splitOptions(options);
@@ -102,14 +147,23 @@ export class Positions extends Resource {
102
147
  let items = 0;
103
148
  for (let n = 0; paging.maxPages === undefined || n < paging.maxPages; n++) {
104
149
  const page = (await this.transactions(chainId, protocol, positionId, { ...query, before }, req));
105
- for (const t of page.transactions) {
106
- yield t;
107
- if (paging.maxItems !== undefined && ++items >= paging.maxItems)
150
+ // A page arrives oldest to newest; walk it from the end so the whole sequence is newest first.
151
+ for (let i = page.transactions.length - 1; i >= 0; i--) {
152
+ yield page.transactions[i];
153
+ items++;
154
+ if (paging.maxItems !== undefined && items >= paging.maxItems)
108
155
  return;
109
156
  }
110
157
  const next = page.transactionsNextCursor;
111
- if (!next || page.transactions.length === 0 || next === before)
158
+ if (!next || page.transactions.length === 0 || next === before) {
159
+ // The oldest row the API had. Its flags say whether that is the position's whole history.
160
+ const reasons = INCOMPLETE_FLAGS.filter((flag) => page[flag] === true);
161
+ if (reasons.length > 0) {
162
+ throw new TransactionsIncompleteError(`positions.iterateTransactions: the API's transaction list for this position is not complete (${reasons.join(', ')}); ` +
163
+ `${items} transactions were yielded`, { reasons, yielded: items });
164
+ }
112
165
  return;
166
+ }
113
167
  before = next;
114
168
  }
115
169
  }
@@ -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 = TokenQuery>(chainId: number, address: string, query?: Q, options?: RequestOptions): APIPromise<WithRows<TokenLookup, 'pools', Q>>;
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 = TokenQuery>(chainId: number, address: string, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
18
+ iteratePools<Q extends TokenQuery = {}>(chainId: number, address: string, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
13
19
  }
@@ -7,6 +7,14 @@ export class Tokens extends Resource {
7
7
  get(chainId, address, query, options) {
8
8
  return this.call('tokens.detail', { chainId, address }, toQuery(query), options);
9
9
  }
10
+ /**
11
+ * `GET /v1/tokens/search`: find tokens by symbol, name or address (`q`, 1 to 100 characters), best match first,
12
+ * on one chain (`chainId`) or every chain. `limit` 1 to 20, default 5. One flat charge per answer; a `partial`
13
+ * answer (some chains not searchable yet, listed in `pendingChains`) is not charged.
14
+ */
15
+ search(query, options) {
16
+ return this.call('tokens.search', undefined, toQuery(query), options);
17
+ }
10
18
  /** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
11
19
  iteratePools(chainId, address, query, options) {
12
20
  const [req, paging] = splitOptions(options);
@@ -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;
@@ -12,6 +12,7 @@ export const ROUTES = {
12
12
  'pools.detail': { path: '/v1/pools/{chainId}/{protocol}/{poolId}', metered: true },
13
13
  'pools.charts': { path: '/v1/pools/{chainId}/{protocol}/{poolId}/charts', metered: true },
14
14
  'tokens.detail': { path: '/v1/tokens/{chainId}/{address}', metered: true },
15
+ 'tokens.search': { path: '/v1/tokens/search', metered: true },
15
16
  'wallets.summary': { path: '/v1/wallets/{address}', metered: true },
16
17
  'hooks.list': { path: '/v1/hooks', metered: true },
17
18
  chains: { path: '/v1/chains', metered: false },
@@ -27,6 +28,10 @@ export function fillPath(op, params = {}) {
27
28
  if (v === undefined || v === null || String(v) === '') {
28
29
  throw new TypeError(`${op}: missing path parameter \`${name}\``);
29
30
  }
31
+ // A number past 2^53 has already lost digits: sending it would ask for another id.
32
+ if (typeof v === 'number' && !Number.isSafeInteger(v)) {
33
+ throw new TypeError(`${op}: \`${name}\` ${v} is not a safe integer; pass a large id as a string or a bigint`);
34
+ }
30
35
  // encodeURIComponent leaves `.` and `..` alone and URL parsing collapses them, which would call another route.
31
36
  if (String(v) === '.' || String(v) === '..') {
32
37
  throw new TypeError(`${op}: \`${name}\` cannot be \`${String(v)}\``);
@@ -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 502 (the API did not answer the gateway), and a
78
- * connection that was never opened. A timeout, a connection lost mid-request and a 504 are NOT retried on a metered
79
- * route: the API may have served, and charged, the first attempt, so a retry could be billed twice.
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
  */