@tickwise/sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +203 -2
  3. package/dist/cjs/api-promise.d.ts +22 -0
  4. package/dist/cjs/api-promise.js +43 -0
  5. package/dist/cjs/client.d.ts +64 -0
  6. package/dist/cjs/client.js +123 -0
  7. package/dist/cjs/csv.d.ts +37 -0
  8. package/dist/cjs/csv.js +69 -0
  9. package/dist/cjs/errors.d.ts +133 -0
  10. package/dist/cjs/errors.js +242 -0
  11. package/dist/cjs/generated/openapi.d.ts +1949 -0
  12. package/dist/cjs/generated/openapi.js +6 -0
  13. package/dist/cjs/index.d.ts +11 -0
  14. package/dist/cjs/index.js +33 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/resources/base.d.ts +21 -0
  17. package/dist/cjs/resources/base.js +81 -0
  18. package/dist/cjs/resources/hooks.d.ts +26 -0
  19. package/dist/cjs/resources/hooks.js +46 -0
  20. package/dist/cjs/resources/meta.d.ts +23 -0
  21. package/dist/cjs/resources/meta.js +35 -0
  22. package/dist/cjs/resources/pools.d.ts +21 -0
  23. package/dist/cjs/resources/pools.js +40 -0
  24. package/dist/cjs/resources/positions.d.ts +59 -0
  25. package/dist/cjs/resources/positions.js +187 -0
  26. package/dist/cjs/resources/tokens.d.ts +19 -0
  27. package/dist/cjs/resources/tokens.js +28 -0
  28. package/dist/cjs/resources/wallets.d.ts +11 -0
  29. package/dist/cjs/resources/wallets.js +14 -0
  30. package/dist/cjs/routes.d.ts +84 -0
  31. package/dist/cjs/routes.js +45 -0
  32. package/dist/cjs/transport.d.ts +92 -0
  33. package/dist/cjs/transport.js +314 -0
  34. package/dist/cjs/types.d.ts +112 -0
  35. package/dist/cjs/types.js +2 -0
  36. package/dist/cjs/version.d.ts +2 -0
  37. package/dist/cjs/version.js +5 -0
  38. package/dist/esm/api-promise.d.ts +22 -0
  39. package/dist/esm/api-promise.js +39 -0
  40. package/dist/esm/client.d.ts +64 -0
  41. package/dist/esm/client.js +119 -0
  42. package/dist/esm/csv.d.ts +37 -0
  43. package/dist/esm/csv.js +64 -0
  44. package/dist/esm/errors.d.ts +133 -0
  45. package/dist/esm/errors.js +221 -0
  46. package/dist/esm/generated/openapi.d.ts +1949 -0
  47. package/dist/esm/generated/openapi.js +5 -0
  48. package/dist/esm/index.d.ts +11 -0
  49. package/dist/esm/index.js +8 -0
  50. package/dist/esm/resources/base.d.ts +21 -0
  51. package/dist/esm/resources/base.js +73 -0
  52. package/dist/esm/resources/hooks.d.ts +26 -0
  53. package/dist/esm/resources/hooks.js +42 -0
  54. package/dist/esm/resources/meta.d.ts +23 -0
  55. package/dist/esm/resources/meta.js +30 -0
  56. package/dist/esm/resources/pools.d.ts +21 -0
  57. package/dist/esm/resources/pools.js +36 -0
  58. package/dist/esm/resources/positions.d.ts +59 -0
  59. package/dist/esm/resources/positions.js +183 -0
  60. package/dist/esm/resources/tokens.d.ts +19 -0
  61. package/dist/esm/resources/tokens.js +24 -0
  62. package/dist/esm/resources/wallets.d.ts +11 -0
  63. package/dist/esm/resources/wallets.js +10 -0
  64. package/dist/esm/routes.d.ts +84 -0
  65. package/dist/esm/routes.js +41 -0
  66. package/dist/esm/transport.d.ts +92 -0
  67. package/dist/esm/transport.js +303 -0
  68. package/dist/esm/types.d.ts +112 -0
  69. package/dist/esm/types.js +1 -0
  70. package/dist/esm/version.d.ts +2 -0
  71. package/dist/esm/version.js +2 -0
  72. package/package.json +64 -4
@@ -0,0 +1,5 @@
1
+ /**
2
+ * This file was auto-generated by openapi-typescript.
3
+ * Do not make direct changes to the file.
4
+ */
5
+ export {};
@@ -0,0 +1,11 @@
1
+ export { Tickwise, type TickwiseOptions } from './client.js';
2
+ export { APIPromise, type WithMeta } from './api-promise.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
+ export type { CsvPage, CsvPagination } from './csv.js';
5
+ export { DEFAULT_BASE_URL, type LimitInfo, type RequestOptions, type ResponseMeta } from './transport.js';
6
+ export { POSITION_BATCH_MAX } from './resources/positions.js';
7
+ export { HOOKS_ALL_CHAINS_MAX_ROWS } from './resources/hooks.js';
8
+ export { ROUTES, type OperationId } from './routes.js';
9
+ export { VERSION } from './version.js';
10
+ export type * from './types.js';
11
+ export type { components, operations, paths } from './generated/openapi.js';
@@ -0,0 +1,8 @@
1
+ export { Tickwise } from './client.js';
2
+ export { APIPromise } from './api-promise.js';
3
+ export { APIError, AuthenticationError, BadRequestError, BatchAllIncompleteError, ConnectionError, IncompleteError, NotFoundError, PermissionDeniedError, QuotaExceededError, RateLimitError, ServiceUnavailableError, TickwiseError, TimeoutError, TooManyRequestsError, TransactionsIncompleteError, } from './errors.js';
4
+ export { DEFAULT_BASE_URL } from './transport.js';
5
+ export { POSITION_BATCH_MAX } from './resources/positions.js';
6
+ export { HOOKS_ALL_CHAINS_MAX_ROWS } from './resources/hooks.js';
7
+ export { ROUTES } from './routes.js';
8
+ export { VERSION } from './version.js';
@@ -0,0 +1,21 @@
1
+ import { APIPromise } from '../api-promise.js';
2
+ import { type CsvPage } from '../csv.js';
3
+ import { type OperationId } from '../routes.js';
4
+ import type { Query, RequestOptions, Transport } from '../transport.js';
5
+ import type { PagingOptions } from '../types.js';
6
+ /** A query object from the caller, as sent: `format` is the SDK's to set, never the caller's. */
7
+ export declare function toQuery(q: object | undefined, extra?: Record<string, unknown>): Query;
8
+ export declare class Resource {
9
+ protected readonly transport: Transport;
10
+ constructor(transport: Transport);
11
+ protected call<T>(op: OperationId, pathParams: Record<string, string | number | bigint> | undefined, query: Query | undefined, options: RequestOptions | undefined): APIPromise<T>;
12
+ protected callCsv(op: OperationId, query: Query, options: RequestOptions | undefined): APIPromise<CsvPage>;
13
+ }
14
+ /**
15
+ * Pages of a `page` / `limit` list, fetched one at a time and only when asked for. Stops when the page says there
16
+ * is no more, when a page comes back empty (a guard against a server bug looping forever), or at `maxPages`.
17
+ */
18
+ export declare function pageIterator<P>(query: object | undefined, fetchPage: (page: number) => Promise<P>, hasMore: (p: P) => boolean, size: (p: P) => number, opts?: PagingOptions): AsyncGenerator<P, void, undefined>;
19
+ /** The rows of a page iterator, up to `maxItems`. */
20
+ export declare function rowIterator<P, R>(pages: AsyncGenerator<P, void, undefined>, rows: (p: P) => readonly R[], opts?: PagingOptions): AsyncGenerator<R, void, undefined>;
21
+ export declare function splitOptions<O extends RequestOptions & PagingOptions>(o: O | undefined): [RequestOptions, PagingOptions];
@@ -0,0 +1,73 @@
1
+ import { APIPromise } from '../api-promise.js';
2
+ import { csvPageOf } from '../csv.js';
3
+ import { fillPath, ROUTES } from '../routes.js';
4
+ /** A query object from the caller, as sent: `format` is the SDK's to set, never the caller's. */
5
+ export function toQuery(q, extra = {}) {
6
+ const out = { ...(q ?? {}) };
7
+ delete out.format;
8
+ return { ...out, ...extra };
9
+ }
10
+ export class Resource {
11
+ transport;
12
+ constructor(transport) {
13
+ this.transport = transport;
14
+ }
15
+ call(op, pathParams, query, options) {
16
+ let raw;
17
+ try {
18
+ raw = this.transport.request({ path: fillPath(op, pathParams), query, metered: ROUTES[op].metered, accept: 'json' }, options);
19
+ }
20
+ catch (e) {
21
+ raw = Promise.reject(e);
22
+ }
23
+ return new APIPromise(raw.then((r) => ({ data: r.body, meta: r.meta })));
24
+ }
25
+ callCsv(op, query, options) {
26
+ const raw = this.transport.request({ path: fillPath(op), query: { ...query, format: 'csv' }, metered: ROUTES[op].metered, accept: 'csv' }, options);
27
+ return new APIPromise(raw.then((r) => ({ data: csvPageOf(r.body, r.meta.headers, r.meta.url), meta: r.meta })));
28
+ }
29
+ }
30
+ function startPage(q) {
31
+ const p = q?.page;
32
+ return typeof p === 'number' && Number.isInteger(p) && p >= 1 ? p : 1;
33
+ }
34
+ /**
35
+ * Pages of a `page` / `limit` list, fetched one at a time and only when asked for. Stops when the page says there
36
+ * is no more, when a page comes back empty (a guard against a server bug looping forever), or at `maxPages`.
37
+ */
38
+ export async function* pageIterator(query, fetchPage, hasMore, size, opts = {}) {
39
+ let page = startPage(query);
40
+ for (let n = 0; opts.maxPages === undefined || n < opts.maxPages; n++, page++) {
41
+ const p = await fetchPage(page);
42
+ yield p;
43
+ if (!hasMore(p) || size(p) === 0)
44
+ return;
45
+ }
46
+ }
47
+ /** The rows of a page iterator, up to `maxItems`. */
48
+ export async function* rowIterator(pages, rows, opts = {}) {
49
+ if (opts.maxItems !== undefined && opts.maxItems <= 0)
50
+ return;
51
+ let n = 0;
52
+ try {
53
+ for await (const p of pages) {
54
+ for (const r of rows(p)) {
55
+ yield r;
56
+ if (opts.maxItems !== undefined && ++n >= opts.maxItems)
57
+ return;
58
+ }
59
+ }
60
+ }
61
+ finally {
62
+ await pages.return(undefined);
63
+ }
64
+ }
65
+ export function splitOptions(o) {
66
+ const { maxPages, maxItems, ...rest } = o ?? {};
67
+ const paging = {};
68
+ if (maxPages !== undefined)
69
+ paging.maxPages = maxPages;
70
+ if (maxItems !== undefined)
71
+ paging.maxItems = maxItems;
72
+ return [rest, paging];
73
+ }
@@ -0,0 +1,26 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import { type CsvPage } from '../csv.js';
3
+ import type { RequestOptions } from '../transport.js';
4
+ import type { Hook, HookList, HooksListQuery, CsvPagingOptions, PagingOptions } from '../types.js';
5
+ import { Resource } from './base.js';
6
+ /**
7
+ * Deepest row an all-chains hooks page may reach (`page` × `limit`). The API refuses a deeper page with a 400 and
8
+ * still says `hasMore: true` on the last page it allows, so the iterators stop at the cap. Pass `chainId` to page
9
+ * one chain further.
10
+ */
11
+ export declare const HOOKS_ALL_CHAINS_MAX_ROWS = 1000;
12
+ export declare class Hooks extends Resource {
13
+ /** `GET /v1/hooks`: Uniswap v4 hooks with the TVL, volume and fees of their pools. */
14
+ list(query?: HooksListQuery, options?: RequestOptions): APIPromise<HookList>;
15
+ /**
16
+ * Every page of `list`, fetched as you iterate. Without `chainId` it stops at `HOOKS_ALL_CHAINS_MAX_ROWS` (1,000
17
+ * rows deep), the most the API serves across all chains; pass `chainId` to page further.
18
+ */
19
+ pages(query?: HooksListQuery, options?: RequestOptions & PagingOptions): AsyncGenerator<HookList, void, undefined>;
20
+ /** Every row of `list`, across pages (at most 1,000 without `chainId`). Each page is a metered request; `break` stops fetching. */
21
+ iterate(query?: HooksListQuery, options?: RequestOptions & PagingOptions): AsyncGenerator<Hook, void, undefined>;
22
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
23
+ exportCsv(query?: HooksListQuery, options?: RequestOptions): APIPromise<CsvPage>;
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 & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
26
+ }
@@ -0,0 +1,42 @@
1
+ import { csvHasRows } from '../csv.js';
2
+ import { pageIterator, Resource, rowIterator, splitOptions, toQuery } from './base.js';
3
+ /**
4
+ * Deepest row an all-chains hooks page may reach (`page` × `limit`). The API refuses a deeper page with a 400 and
5
+ * still says `hasMore: true` on the last page it allows, so the iterators stop at the cap. Pass `chainId` to page
6
+ * one chain further.
7
+ */
8
+ export const HOOKS_ALL_CHAINS_MAX_ROWS = 1_000;
9
+ /** More pages to fetch: the API says so and, across all chains, the next page stays within the cap. */
10
+ function hasMore(query) {
11
+ const allChains = query?.chainId === undefined || query?.chainId === null;
12
+ return (p) => p.pagination.hasMore && (!allChains || (p.pagination.page + 1) * p.pagination.limit <= HOOKS_ALL_CHAINS_MAX_ROWS);
13
+ }
14
+ export class Hooks extends Resource {
15
+ /** `GET /v1/hooks`: Uniswap v4 hooks with the TVL, volume and fees of their pools. */
16
+ list(query, options) {
17
+ return this.call('hooks.list', undefined, toQuery(query), options);
18
+ }
19
+ /**
20
+ * Every page of `list`, fetched as you iterate. Without `chainId` it stops at `HOOKS_ALL_CHAINS_MAX_ROWS` (1,000
21
+ * rows deep), the most the API serves across all chains; pass `chainId` to page further.
22
+ */
23
+ pages(query, options) {
24
+ const [req, paging] = splitOptions(options);
25
+ return pageIterator(query, (page) => this.list({ ...query, page }, req), hasMore(query), (p) => p.hooks.length, paging);
26
+ }
27
+ /** Every row of `list`, across pages (at most 1,000 without `chainId`). Each page is a metered request; `break` stops fetching. */
28
+ iterate(query, options) {
29
+ const [req, paging] = splitOptions(options);
30
+ const pages = this.pages(query, { ...req, ...(paging.maxPages === undefined ? {} : { maxPages: paging.maxPages }) });
31
+ return rowIterator(pages, (p) => p.hooks, paging);
32
+ }
33
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
34
+ exportCsv(query, options) {
35
+ return this.callCsv('hooks.list', toQuery(query), options);
36
+ }
37
+ /** 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. */
38
+ exportCsvPages(query, options) {
39
+ const [req, paging] = splitOptions(options);
40
+ return pageIterator(query, (page) => this.exportCsv({ ...query, page }, req), hasMore(query), (p) => (csvHasRows(p.csv) ? 1 : 0), paging);
41
+ }
42
+ }
@@ -0,0 +1,23 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import type { RequestOptions } from '../transport.js';
3
+ import type { Chain, PlanList, Protocol, Stats, UnitCostList } from '../types.js';
4
+ import { Resource } from './base.js';
5
+ /** The free, keyless routes. The key is never sent on them, even when the client has one. */
6
+ export declare class Meta extends Resource {
7
+ /** `GET /v1/chains`: the chains served right now, each with its protocols. The live list of valid `chainId`s. */
8
+ chains(options?: RequestOptions): APIPromise<Chain[]>;
9
+ /** `GET /v1/protocols`: the protocols served and the chains each is live on. */
10
+ protocols(options?: RequestOptions): APIPromise<Protocol[]>;
11
+ /** `GET /v1/plans`: the plans on sale, with monthly units, burst limit and prices. */
12
+ plans(options?: RequestOptions): APIPromise<PlanList>;
13
+ /** `GET /v1/stats`: headline counts of everything indexed. */
14
+ stats(options?: RequestOptions): APIPromise<Stats>;
15
+ }
16
+ /** `tw.pricing`: free, keyless. */
17
+ export declare class Pricing extends Resource {
18
+ /**
19
+ * `GET /v1/pricing/units`: what each metered route costs in units, live. Read prices from here; they can change,
20
+ * so the SDK never hard-codes them.
21
+ */
22
+ units(options?: RequestOptions): APIPromise<UnitCostList>;
23
+ }
@@ -0,0 +1,30 @@
1
+ import { Resource } from './base.js';
2
+ /** The free, keyless routes. The key is never sent on them, even when the client has one. */
3
+ export class Meta extends Resource {
4
+ /** `GET /v1/chains`: the chains served right now, each with its protocols. The live list of valid `chainId`s. */
5
+ chains(options) {
6
+ return this.call('chains', undefined, undefined, options);
7
+ }
8
+ /** `GET /v1/protocols`: the protocols served and the chains each is live on. */
9
+ protocols(options) {
10
+ return this.call('protocols', undefined, undefined, options);
11
+ }
12
+ /** `GET /v1/plans`: the plans on sale, with monthly units, burst limit and prices. */
13
+ plans(options) {
14
+ return this.call('plans', undefined, undefined, options);
15
+ }
16
+ /** `GET /v1/stats`: headline counts of everything indexed. */
17
+ stats(options) {
18
+ return this.call('stats', undefined, undefined, options);
19
+ }
20
+ }
21
+ /** `tw.pricing`: free, keyless. */
22
+ export class Pricing extends Resource {
23
+ /**
24
+ * `GET /v1/pricing/units`: what each metered route costs in units, live. Read prices from here; they can change,
25
+ * so the SDK never hard-codes them.
26
+ */
27
+ units(options) {
28
+ return this.call('pricing.units', undefined, undefined, options);
29
+ }
30
+ }
@@ -0,0 +1,21 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import { type CsvPage } from '../csv.js';
3
+ import type { RequestOptions } from '../transport.js';
4
+ import type { Charts, CsvPagingOptions, PagingOptions, Pool, PoolChartsQuery, PoolDetail, PoolDetailQuery, PoolList, PoolsListQuery, ProtocolKey, RowOf, Shaped, WithRows } from '../types.js';
5
+ import { Resource } from './base.js';
6
+ export declare class Pools extends Resource {
7
+ /** `GET /v1/pools`: a ranked, filtered page of pools. */
8
+ list<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PoolList, 'pools', Q>>;
9
+ /** Every page of `list`, fetched as you iterate. Starts at `query.page` (default 1). */
10
+ pages<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PoolList, 'pools', Q>, void, undefined>;
11
+ /** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
12
+ iterate<Q extends PoolsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
13
+ /** `GET /v1/pools/{chainId}/{protocol}/{poolId}`: one pool. */
14
+ get<Q extends PoolDetailQuery = {}>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<PoolDetail, Q>>;
15
+ /** `GET .../charts`: the pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
16
+ charts<Q extends PoolChartsQuery = {}>(chainId: number, protocol: ProtocolKey, poolId: string, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
17
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
18
+ exportCsv(query?: PoolsListQuery, options?: RequestOptions): APIPromise<CsvPage>;
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 & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
21
+ }
@@ -0,0 +1,36 @@
1
+ import { csvHasRows } from '../csv.js';
2
+ import { pageIterator, Resource, rowIterator, splitOptions, toQuery } from './base.js';
3
+ export class Pools extends Resource {
4
+ /** `GET /v1/pools`: a ranked, filtered page of pools. */
5
+ list(query, options) {
6
+ return this.call('pools.list', undefined, toQuery(query), options);
7
+ }
8
+ /** Every page of `list`, fetched as you iterate. Starts at `query.page` (default 1). */
9
+ pages(query, options) {
10
+ const [req, paging] = splitOptions(options);
11
+ return pageIterator(query, (page) => this.list({ ...query, page }, req), (p) => p.pagination.hasMore, (p) => p.pools.length, paging);
12
+ }
13
+ /** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
14
+ iterate(query, options) {
15
+ const [req, paging] = splitOptions(options);
16
+ const pages = this.pages(query, { ...req, ...(paging.maxPages === undefined ? {} : { maxPages: paging.maxPages }) });
17
+ return rowIterator(pages, (p) => p.pools, paging);
18
+ }
19
+ /** `GET /v1/pools/{chainId}/{protocol}/{poolId}`: one pool. */
20
+ get(chainId, protocol, poolId, query, options) {
21
+ return this.call('pools.detail', { chainId, protocol, poolId }, toQuery(query), options);
22
+ }
23
+ /** `GET .../charts`: the pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
24
+ charts(chainId, protocol, poolId, query, options) {
25
+ return this.call('pools.charts', { chainId, protocol, poolId }, toQuery(query), options);
26
+ }
27
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
28
+ exportCsv(query, options) {
29
+ return this.callCsv('pools.list', toQuery(query), options);
30
+ }
31
+ /** Every page of `list` as CSV, each with its own header row. Each page is a metered request. */
32
+ exportCsvPages(query, options) {
33
+ const [req, paging] = splitOptions(options);
34
+ return pageIterator(query, (page) => this.exportCsv({ ...query, page }, req), (p) => p.pagination.hasMore, (p) => (csvHasRows(p.csv) ? 1 : 0), paging);
35
+ }
36
+ }
@@ -0,0 +1,59 @@
1
+ import { APIPromise } from '../api-promise.js';
2
+ import { type CsvPage } from '../csv.js';
3
+ import type { RequestOptions } from '../transport.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
+ import { Resource } from './base.js';
6
+ /** Most ids one `GET /v1/positions/batch` call takes. */
7
+ export declare const POSITION_BATCH_MAX = 100;
8
+ export declare class Positions extends Resource {
9
+ /**
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
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.
15
+ */
16
+ list<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions): APIPromise<WithRows<PositionList, 'positions', Q>>;
17
+ /** Every page of `list`, one request per page, fetched as you iterate. Starts at `query.page` (default 1). */
18
+ pages<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<WithRows<PositionList, 'positions', Q>, void, undefined>;
19
+ /** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
20
+ iterate<Q extends PositionsListQuery = {}>(query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Position, Q>, void, undefined>;
21
+ /**
22
+ * `GET /v1/positions/batch`: up to 100 positions of one chain and protocol in one call, in the order of `ids`
23
+ * (duplicates dropped); ids not found are listed in `missing`. Priced per position returned
24
+ * (`.withMeta()` → `meta.unitsCharged`).
25
+ */
26
+ batch<Q extends PositionsBatchQuery>(query: Q, options?: RequestOptions): APIPromise<WithRows<PositionBatch, 'positions', Q>>;
27
+ /**
28
+ * Any number of ids: `batch` calls of 100, one after another, merged in order. Costs exactly what the separate
29
+ * calls cost (the batch is priced per position). `.withMeta()` gives the last call's metadata with
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.
35
+ */
36
+ batchAll<Q extends PositionsBatchQuery>(query: Q, options?: RequestOptions): APIPromise<WithRows<PositionBatch, 'positions', Q>>;
37
+ /** `GET /v1/positions/{chainId}/{protocol}/{positionId}`: one position, with its transactions. */
38
+ get<Q extends PositionDetailQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<PositionDetail, Q>>;
39
+ /**
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.
43
+ */
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>;
53
+ /** `GET .../charts`: the position's and its pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
54
+ charts<Q extends PositionChartsQuery = {}>(chainId: number, protocol: ProtocolKey, positionId: PositionId, query?: Q, options?: RequestOptions): APIPromise<Shaped<Charts, Q>>;
55
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
56
+ exportCsv(query?: PositionsListQuery, options?: RequestOptions): APIPromise<CsvPage>;
57
+ /** Every page of `list` as CSV, each with its own header row. Each page is a metered request. */
58
+ exportCsvPages(query?: PositionsListQuery, options?: RequestOptions & CsvPagingOptions): AsyncGenerator<CsvPage, void, undefined>;
59
+ }
@@ -0,0 +1,183 @@
1
+ import { APIPromise } from '../api-promise.js';
2
+ import { BatchAllIncompleteError, TransactionsIncompleteError } from '../errors.js';
3
+ import { csvHasRows } from '../csv.js';
4
+ import { pageIterator, Resource, rowIterator, splitOptions, toQuery } from './base.js';
5
+ const INCOMPLETE_FLAGS = ['transactionsPartial', 'transactionsTruncated', 'transactionsDegraded'];
6
+ /** Most ids one `GET /v1/positions/batch` call takes. */
7
+ export const POSITION_BATCH_MAX = 100;
8
+ function idList(ids) {
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
+ });
18
+ const seen = new Set();
19
+ const out = [];
20
+ for (const id of raw.map((s) => s.trim()).filter(Boolean)) {
21
+ if (!seen.has(id)) {
22
+ seen.add(id);
23
+ out.push(id);
24
+ }
25
+ }
26
+ return out;
27
+ }
28
+ export class Positions extends Resource {
29
+ /**
30
+ * `GET /v1/positions`: a ranked, filtered page of positions. The defaults hide closed, risky and small-pool
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.
35
+ */
36
+ list(query, options) {
37
+ return this.call('positions.list', undefined, toQuery(query), options);
38
+ }
39
+ /** Every page of `list`, one request per page, fetched as you iterate. Starts at `query.page` (default 1). */
40
+ pages(query, options) {
41
+ const [req, paging] = splitOptions(options);
42
+ return pageIterator(query, (page) => this.list({ ...query, page }, req), (p) => p.pagination.hasMore, (p) => p.positions.length, paging);
43
+ }
44
+ /** Every row of `list`, across pages. Each page is a metered request; `break` stops fetching. */
45
+ iterate(query, options) {
46
+ const [req, paging] = splitOptions(options);
47
+ const pages = this.pages(query, { ...req, ...(paging.maxPages === undefined ? {} : { maxPages: paging.maxPages }) });
48
+ return rowIterator(pages, (p) => p.positions, paging);
49
+ }
50
+ /**
51
+ * `GET /v1/positions/batch`: up to 100 positions of one chain and protocol in one call, in the order of `ids`
52
+ * (duplicates dropped); ids not found are listed in `missing`. Priced per position returned
53
+ * (`.withMeta()` → `meta.unitsCharged`).
54
+ */
55
+ batch(query, options) {
56
+ let ids;
57
+ try {
58
+ ids = idList(query.ids);
59
+ }
60
+ catch (e) {
61
+ return new APIPromise(Promise.reject(e));
62
+ }
63
+ if (ids.length === 0)
64
+ return new APIPromise(Promise.reject(new TypeError('positions.batch: `ids` is empty')));
65
+ return this.call('positions.batch', undefined, toQuery(query, { ids: ids.join(',') }), options);
66
+ }
67
+ /**
68
+ * Any number of ids: `batch` calls of 100, one after another, merged in order. Costs exactly what the separate
69
+ * calls cost (the batch is priced per position). `.withMeta()` gives the last call's metadata with
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.
75
+ */
76
+ batchAll(query, options) {
77
+ let ids;
78
+ try {
79
+ ids = idList(query.ids);
80
+ }
81
+ catch (e) {
82
+ return new APIPromise(Promise.reject(e));
83
+ }
84
+ if (ids.length === 0)
85
+ return new APIPromise(Promise.reject(new TypeError('positions.batchAll: `ids` is empty')));
86
+ const run = async () => {
87
+ let merged;
88
+ let meta;
89
+ let units = 0;
90
+ let unitsKnown = true;
91
+ let retries = 0;
92
+ for (let i = 0; i < ids.length; i += POSITION_BATCH_MAX) {
93
+ const chunk = ids.slice(i, i + POSITION_BATCH_MAX);
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
+ }
104
+ const data = r.data;
105
+ if (merged === undefined) {
106
+ merged = { ...data, positions: [...data.positions], missing: [...data.missing] };
107
+ }
108
+ else {
109
+ merged.positions.push(...data.positions);
110
+ merged.missing.push(...data.missing);
111
+ }
112
+ if (r.meta.unitsCharged === undefined)
113
+ unitsKnown = false;
114
+ else
115
+ units += r.meta.unitsCharged;
116
+ retries += r.meta.retries;
117
+ meta = r.meta;
118
+ }
119
+ return { data: merged, meta: { ...meta, unitsCharged: unitsKnown ? units : undefined, retries } };
120
+ };
121
+ return new APIPromise(run());
122
+ }
123
+ /** `GET /v1/positions/{chainId}/{protocol}/{positionId}`: one position, with its transactions. */
124
+ get(chainId, protocol, positionId, query, options) {
125
+ return this.call('positions.detail', { chainId, protocol, positionId }, toQuery(query), options);
126
+ }
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
+ */
132
+ transactions(chainId, protocol, positionId, query, options) {
133
+ return this.call('positions.transactions', { chainId, protocol, positionId }, toQuery(query), options);
134
+ }
135
+ /**
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.
141
+ */
142
+ async *iterateTransactions(chainId, protocol, positionId, query, options) {
143
+ const [req, paging] = splitOptions(options);
144
+ if (paging.maxItems !== undefined && paging.maxItems <= 0)
145
+ return;
146
+ let before = query?.before;
147
+ let items = 0;
148
+ for (let n = 0; paging.maxPages === undefined || n < paging.maxPages; n++) {
149
+ const page = (await this.transactions(chainId, protocol, positionId, { ...query, before }, req));
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)
155
+ return;
156
+ }
157
+ const next = page.transactionsNextCursor;
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
+ }
165
+ return;
166
+ }
167
+ before = next;
168
+ }
169
+ }
170
+ /** `GET .../charts`: the position's and its pool's time series (`range`: 30d, 60d, 90d, 180d, all). */
171
+ charts(chainId, protocol, positionId, query, options) {
172
+ return this.call('positions.charts', { chainId, protocol, positionId }, toQuery(query), options);
173
+ }
174
+ /** One page of `list` as CSV (`format=csv`): same filters, paging and unit cost as JSON. */
175
+ exportCsv(query, options) {
176
+ return this.callCsv('positions.list', toQuery(query), options);
177
+ }
178
+ /** Every page of `list` as CSV, each with its own header row. Each page is a metered request. */
179
+ exportCsvPages(query, options) {
180
+ const [req, paging] = splitOptions(options);
181
+ return pageIterator(query, (page) => this.exportCsv({ ...query, page }, req), (p) => p.pagination.hasMore, (p) => (csvHasRows(p.csv) ? 1 : 0), paging);
182
+ }
183
+ }
@@ -0,0 +1,19 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import type { RequestOptions } from '../transport.js';
3
+ import type { PagingOptions, Pool, RowOf, TokenLookup, TokenQuery, TokenSearch, TokenSearchQuery, WithRows } from '../types.js';
4
+ import { Resource } from './base.js';
5
+ export declare class Tokens extends Resource {
6
+ /**
7
+ * `GET /v1/tokens/{chainId}/{address}`: one token's USD price and where it came from, what the API knows about
8
+ * it, its risk flags, and a page of the pools holding it. The chain's native token is the zero address.
9
+ */
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>;
17
+ /** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
18
+ iteratePools<Q extends TokenQuery = {}>(chainId: number, address: string, query?: Q, options?: RequestOptions & PagingOptions): AsyncGenerator<RowOf<Pool, Q>, void, undefined>;
19
+ }
@@ -0,0 +1,24 @@
1
+ import { pageIterator, Resource, rowIterator, splitOptions, toQuery } from './base.js';
2
+ export class Tokens extends Resource {
3
+ /**
4
+ * `GET /v1/tokens/{chainId}/{address}`: one token's USD price and where it came from, what the API knows about
5
+ * it, its risk flags, and a page of the pools holding it. The chain's native token is the zero address.
6
+ */
7
+ get(chainId, address, query, options) {
8
+ return this.call('tokens.detail', { chainId, address }, toQuery(query), options);
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
+ }
18
+ /** Every pool holding the token, across pages. Each page is a metered request; `break` stops fetching. */
19
+ iteratePools(chainId, address, query, options) {
20
+ const [req, paging] = splitOptions(options);
21
+ const pages = pageIterator(query, (page) => this.get(chainId, address, { ...query, page }, req), (p) => p.pagination.hasMore, (p) => p.pools.length, paging.maxPages === undefined ? {} : { maxPages: paging.maxPages });
22
+ return rowIterator(pages, (p) => p.pools, paging);
23
+ }
24
+ }
@@ -0,0 +1,11 @@
1
+ import type { APIPromise } from '../api-promise.js';
2
+ import type { RequestOptions } from '../transport.js';
3
+ import type { WalletSummary, WalletSummaryQuery } from '../types.js';
4
+ import { Resource } from './base.js';
5
+ export declare class Wallets extends Resource {
6
+ /**
7
+ * `GET /v1/wallets/{address}`: one wallet's positions summed across every chain (or one `chainId`): value,
8
+ * uncollected fees, PnL and counts, in total and per chain. A wallet with no positions is zeros, not a 404.
9
+ */
10
+ summary(address: string, query?: WalletSummaryQuery, options?: RequestOptions): APIPromise<WalletSummary>;
11
+ }
@@ -0,0 +1,10 @@
1
+ import { Resource, toQuery } from './base.js';
2
+ export class Wallets extends Resource {
3
+ /**
4
+ * `GET /v1/wallets/{address}`: one wallet's positions summed across every chain (or one `chainId`): value,
5
+ * uncollected fees, PnL and counts, in total and per chain. A wallet with no positions is zeros, not a 404.
6
+ */
7
+ summary(address, query, options) {
8
+ return this.call('wallets.summary', { address }, toQuery(query), options);
9
+ }
10
+ }