@gauntlet-xyz/sdk 2.0.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -1
- package/dist/api/activity.d.ts +70 -0
- package/dist/api/activity.d.ts.map +1 -0
- package/dist/api/activity.js +154 -0
- package/dist/api/activity.js.map +1 -0
- package/dist/api/caip.d.ts +29 -0
- package/dist/api/caip.d.ts.map +1 -0
- package/dist/api/caip.js +38 -0
- package/dist/api/caip.js.map +1 -0
- package/dist/api/client.d.ts +114 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +109 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/decimal.d.ts +21 -0
- package/dist/api/decimal.d.ts.map +1 -0
- package/dist/api/decimal.js +44 -0
- package/dist/api/decimal.js.map +1 -0
- package/dist/api/errors.d.ts +32 -0
- package/dist/api/errors.d.ts.map +1 -0
- package/dist/api/errors.js +41 -0
- package/dist/api/errors.js.map +1 -0
- package/dist/api/generated.d.ts +1461 -0
- package/dist/api/generated.d.ts.map +1 -0
- package/dist/api/generated.js +6 -0
- package/dist/api/generated.js.map +1 -0
- package/dist/api/http.d.ts +16 -0
- package/dist/api/http.d.ts.map +1 -0
- package/dist/api/http.js +39 -0
- package/dist/api/http.js.map +1 -0
- package/dist/api/index.d.ts +14 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +8 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/positionHistory.d.ts +44 -0
- package/dist/api/positionHistory.d.ts.map +1 -0
- package/dist/api/positionHistory.js +126 -0
- package/dist/api/positionHistory.js.map +1 -0
- package/dist/client.d.ts +6 -0
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +2 -0
- package/dist/client.js.map +1 -1
- package/dist/evm/abis/provisionerV2.d.ts +224 -0
- package/dist/evm/abis/provisionerV2.d.ts.map +1 -1
- package/dist/evm/abis/provisionerV2.js +59 -0
- package/dist/evm/abis/provisionerV2.js.map +1 -1
- package/dist/evm/aeraContracts/v2.d.ts +1369 -25
- package/dist/evm/aeraContracts/v2.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/privy/index.d.ts +52 -0
- package/dist/privy/index.d.ts.map +1 -0
- package/dist/privy/index.js +51 -0
- package/dist/privy/index.js.map +1 -0
- package/manifest/vaults.json +299 -5
- package/package.json +2 -2
- package/src/api/activity.ts +219 -0
- package/src/api/caip.ts +61 -0
- package/src/api/client.ts +201 -0
- package/src/api/decimal.ts +49 -0
- package/src/api/errors.ts +64 -0
- package/src/api/generated.ts +1461 -0
- package/src/api/http.ts +62 -0
- package/src/api/index.ts +65 -0
- package/src/api/positionHistory.ts +167 -0
- package/src/client.ts +7 -1
- package/src/evm/abis/provisionerV2.ts +59 -0
- package/src/index.ts +2 -0
- package/src/privy/index.ts +95 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { GauntletSDKError } from '../errors';
|
|
2
|
+
import type { ActivityOptions, GauntletApi, TokenRef, UserActivity } from './client';
|
|
3
|
+
import { decimalToBigInt, sharesToBigInt } from './decimal';
|
|
4
|
+
import { SettlementTimeoutError } from './errors';
|
|
5
|
+
|
|
6
|
+
export type ActivityFlowKind = 'deposit' | 'withdraw' | 'transfer_in' | 'transfer_out';
|
|
7
|
+
export type ActivityFlowStatus = 'settled' | 'pending' | 'refunded';
|
|
8
|
+
|
|
9
|
+
/** A signed token amount as reported by the API, with base-unit conversion when possible. */
|
|
10
|
+
export interface AssetAmount {
|
|
11
|
+
/** Human-unit decimal string exactly as the API emits it, e.g. `"1250.5"`. */
|
|
12
|
+
decimal: string;
|
|
13
|
+
/** Base-unit integer (`decimal × 10^token.decimals`); null when the token's decimals are unknown. */
|
|
14
|
+
raw: bigint | null;
|
|
15
|
+
token: TokenRef | null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* One user action against a vault, stitched from the activity log's immutable
|
|
20
|
+
* rows. Sync flows (Morpho, secondary-market transfers) come from a single
|
|
21
|
+
* row; Aera async flows pair a `*_pending` request row with its terminal
|
|
22
|
+
* settle/refund row via `request_hash`.
|
|
23
|
+
*/
|
|
24
|
+
export interface ActivityFlow {
|
|
25
|
+
kind: ActivityFlowKind;
|
|
26
|
+
status: ActivityFlowStatus;
|
|
27
|
+
/** CAIP-10 vault id (`"{chainId}:{address}"`). */
|
|
28
|
+
vaultId: string;
|
|
29
|
+
/** Aera async correlation hash; null for sync flows and transfers. */
|
|
30
|
+
requestHash: string | null;
|
|
31
|
+
/** When the request row landed. Null when the flow's pending row is outside the fetched window. */
|
|
32
|
+
requestedAt: Date | null;
|
|
33
|
+
/** When the terminal (settle/refund) row landed. Null while pending. */
|
|
34
|
+
settledAt: Date | null;
|
|
35
|
+
/** Magnitude of the flow's asset movement (requested amount for refunded flows). */
|
|
36
|
+
assets: AssetAmount;
|
|
37
|
+
/** Magnitude of the flow's share movement in 18-decimal base units. */
|
|
38
|
+
shares: bigint;
|
|
39
|
+
/** Transaction hashes in row order (request first, then settlement, when both are known). */
|
|
40
|
+
txHashes: string[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const PENDING_TYPES = new Set(['deposit_pending', 'withdraw_pending']);
|
|
44
|
+
const REFUNDED_TYPES = new Set(['deposit_refunded', 'withdraw_refunded']);
|
|
45
|
+
|
|
46
|
+
function flowKind(rowType: string): ActivityFlowKind {
|
|
47
|
+
if (rowType.startsWith('deposit')) return 'deposit';
|
|
48
|
+
if (rowType.startsWith('withdraw')) return 'withdraw';
|
|
49
|
+
if (rowType === 'transfer_in' || rowType === 'transfer_out') return rowType;
|
|
50
|
+
throw new GauntletSDKError(`Unknown activity row type "${rowType}"`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function abs(value: bigint): bigint {
|
|
54
|
+
return value < 0n ? -value : value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Comparison scale for asset amounts. The API emits human-unit decimal strings
|
|
59
|
+
* with at most `token.decimals` fractional digits, so 18 digits is exact for
|
|
60
|
+
* every supported asset.
|
|
61
|
+
*/
|
|
62
|
+
const ASSET_SCALE = 18;
|
|
63
|
+
|
|
64
|
+
function toAssetAmount(rows: UserActivity[]): AssetAmount {
|
|
65
|
+
// Per the API contract, at most one row of an async lifecycle carries the
|
|
66
|
+
// asset movement (the other legs are "0"), so the max magnitude is the
|
|
67
|
+
// flow's amount. For refunded flows this surfaces the requested amount
|
|
68
|
+
// instead of the useless net of zero.
|
|
69
|
+
let best = rows[0];
|
|
70
|
+
let bestMagnitude = abs(decimalToBigInt(best.assets_delta.native, ASSET_SCALE));
|
|
71
|
+
for (const row of rows.slice(1)) {
|
|
72
|
+
const magnitude = abs(decimalToBigInt(row.assets_delta.native, ASSET_SCALE));
|
|
73
|
+
if (magnitude > bestMagnitude) {
|
|
74
|
+
best = row;
|
|
75
|
+
bestMagnitude = magnitude;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const token =
|
|
79
|
+
best.assets_delta.token ?? rows.find((r) => r.assets_delta.token)?.assets_delta.token ?? null;
|
|
80
|
+
const decimal = best.assets_delta.native.replace(/^-/, '');
|
|
81
|
+
const raw = token?.decimals != null ? decimalToBigInt(decimal, token.decimals) : null;
|
|
82
|
+
return { decimal, raw, token };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Pure stitcher: folds raw activity rows into `ActivityFlow`s. Rows may be in
|
|
87
|
+
* any order and may span multiple vaults; async lifecycles are paired by
|
|
88
|
+
* `request_hash`. Flows are returned newest-first (by the flow's latest row).
|
|
89
|
+
*/
|
|
90
|
+
export function stitchActivityFlows(rows: UserActivity[]): ActivityFlow[] {
|
|
91
|
+
const groups = new Map<string, UserActivity[]>();
|
|
92
|
+
for (const [index, row] of rows.entries()) {
|
|
93
|
+
// Rows without a request_hash are standalone sync flows: each one is its
|
|
94
|
+
// own group, so two same-type events in one transaction (e.g. a multicall
|
|
95
|
+
// doing two deposits) stay two flows.
|
|
96
|
+
const key = row.request_hash ?? `row:${index}`;
|
|
97
|
+
const group = groups.get(key);
|
|
98
|
+
if (group) group.push(row);
|
|
99
|
+
else groups.set(key, [row]);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const flows: ActivityFlow[] = [];
|
|
103
|
+
for (const group of groups.values()) {
|
|
104
|
+
group.sort((a, b) => a.block_timestamp - b.block_timestamp);
|
|
105
|
+
const pendingRow = group.find((r) => PENDING_TYPES.has(r.type)) ?? null;
|
|
106
|
+
const terminalRow = group.find((r) => !PENDING_TYPES.has(r.type)) ?? null;
|
|
107
|
+
const isAsync = group.some((r) => r.request_hash != null);
|
|
108
|
+
|
|
109
|
+
let status: ActivityFlowStatus;
|
|
110
|
+
if (!terminalRow) status = 'pending';
|
|
111
|
+
else if (REFUNDED_TYPES.has(terminalRow.type)) status = 'refunded';
|
|
112
|
+
else status = 'settled';
|
|
113
|
+
|
|
114
|
+
let sharesMagnitude = 0n;
|
|
115
|
+
for (const row of group) {
|
|
116
|
+
const shares = abs(sharesToBigInt(row.shares_delta));
|
|
117
|
+
if (shares > sharesMagnitude) sharesMagnitude = shares;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
flows.push({
|
|
121
|
+
kind: flowKind((terminalRow ?? pendingRow ?? group[0]).type),
|
|
122
|
+
status,
|
|
123
|
+
vaultId: group[0].vault_id,
|
|
124
|
+
requestHash: group[0].request_hash ?? null,
|
|
125
|
+
requestedAt: pendingRow
|
|
126
|
+
? new Date(pendingRow.block_timestamp * 1000)
|
|
127
|
+
: isAsync
|
|
128
|
+
? null
|
|
129
|
+
: new Date(group[0].block_timestamp * 1000),
|
|
130
|
+
settledAt: terminalRow ? new Date(terminalRow.block_timestamp * 1000) : null,
|
|
131
|
+
assets: toAssetAmount(group),
|
|
132
|
+
shares: sharesMagnitude,
|
|
133
|
+
txHashes: [...new Set(group.map((r) => r.tx_hash))],
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return flows.sort((a, b) => {
|
|
138
|
+
const aAt = (a.settledAt ?? a.requestedAt)?.getTime() ?? 0;
|
|
139
|
+
const bAt = (b.settledAt ?? b.requestedAt)?.getTime() ?? 0;
|
|
140
|
+
return bAt - aAt;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface ActivityFlowsOptions extends Pick<ActivityOptions, 'vaultId' | 'limit'> {
|
|
145
|
+
/** Stop paginating once this many rows have been fetched. Defaults to 1000. */
|
|
146
|
+
maxRows?: number;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Fetches the wallet's activity log and stitches it into lifecycle-aware
|
|
151
|
+
* flows — the replacement for scanning vault event logs over RPC.
|
|
152
|
+
*
|
|
153
|
+
* ```ts
|
|
154
|
+
* const flows = await getActivityFlows(client.api, wallet);
|
|
155
|
+
* const open = flows.filter((f) => f.status === 'pending');
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export async function getActivityFlows(
|
|
159
|
+
api: GauntletApi,
|
|
160
|
+
walletAddress: string,
|
|
161
|
+
options: ActivityFlowsOptions = {}
|
|
162
|
+
): Promise<ActivityFlow[]> {
|
|
163
|
+
const maxRows = options.maxRows ?? 1000;
|
|
164
|
+
const rows: UserActivity[] = [];
|
|
165
|
+
for await (const row of api.activityRows(walletAddress, {
|
|
166
|
+
vaultId: options.vaultId,
|
|
167
|
+
// The API caps page size at 1000; request maxRows per page so the common
|
|
168
|
+
// case is a single round trip instead of ten default-100 pages.
|
|
169
|
+
limit: options.limit ?? Math.min(maxRows, 1000),
|
|
170
|
+
order: 'desc',
|
|
171
|
+
})) {
|
|
172
|
+
rows.push(row);
|
|
173
|
+
if (rows.length >= maxRows) break;
|
|
174
|
+
}
|
|
175
|
+
const flows = stitchActivityFlows(rows);
|
|
176
|
+
if (rows.length >= maxRows) {
|
|
177
|
+
// The window cut may have split an async lifecycle, keeping a terminal
|
|
178
|
+
// row whose request leg (the one carrying the amount) fell outside the
|
|
179
|
+
// window. Drop those flows rather than reporting zeroed amounts.
|
|
180
|
+
return flows.filter((f) => f.requestHash === null || f.requestedAt !== null);
|
|
181
|
+
}
|
|
182
|
+
return flows;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface WaitForSettlementOptions {
|
|
186
|
+
/** CAIP-10 vault id — narrows polling to one vault's activity. */
|
|
187
|
+
vaultId?: string;
|
|
188
|
+
/** Polling interval. Defaults to 5s. */
|
|
189
|
+
pollIntervalMs?: number;
|
|
190
|
+
/** Overall deadline. Defaults to 10 minutes. Throws `SettlementTimeoutError` on expiry. */
|
|
191
|
+
timeoutMs?: number;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Polls the activity log until the Aera async request identified by
|
|
196
|
+
* `requestHash` reaches a terminal state, and returns the settled or refunded
|
|
197
|
+
* flow. Use after submitting a `requestDeposit` / `requestRedeem` transaction.
|
|
198
|
+
*/
|
|
199
|
+
export async function waitForRequestSettlement(
|
|
200
|
+
api: GauntletApi,
|
|
201
|
+
walletAddress: string,
|
|
202
|
+
requestHash: string,
|
|
203
|
+
options: WaitForSettlementOptions = {}
|
|
204
|
+
): Promise<ActivityFlow> {
|
|
205
|
+
const pollIntervalMs = options.pollIntervalMs ?? 5_000;
|
|
206
|
+
const timeoutMs = options.timeoutMs ?? 600_000;
|
|
207
|
+
const deadline = Date.now() + timeoutMs;
|
|
208
|
+
|
|
209
|
+
for (;;) {
|
|
210
|
+
const flows = await getActivityFlows(api, walletAddress, { vaultId: options.vaultId });
|
|
211
|
+
const flow = flows.find((f) => f.requestHash === requestHash);
|
|
212
|
+
if (flow && flow.status !== 'pending') return flow;
|
|
213
|
+
|
|
214
|
+
if (Date.now() + pollIntervalMs > deadline) {
|
|
215
|
+
throw new SettlementTimeoutError(requestHash, timeoutMs);
|
|
216
|
+
}
|
|
217
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
218
|
+
}
|
|
219
|
+
}
|
package/src/api/caip.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { GauntletClient } from '../client';
|
|
2
|
+
import { VaultNotFoundError } from '../errors';
|
|
3
|
+
import { resolveVault } from '../evm/vaults';
|
|
4
|
+
import { InvalidCaipIdError } from './errors';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The Gaia API identifies vaults as `"{chainId}:{address}"` with a lowercase
|
|
8
|
+
* address (a CAIP-10-style account id without the `eip155` namespace prefix).
|
|
9
|
+
*/
|
|
10
|
+
export interface ApiVaultId {
|
|
11
|
+
chainId: number;
|
|
12
|
+
/** Lowercase EVM address. */
|
|
13
|
+
address: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function parseApiVaultId(id: string): ApiVaultId {
|
|
17
|
+
const match = /^(?:eip155:)?(\d+):(0x[0-9a-fA-F]{40})$/.exec(id);
|
|
18
|
+
if (!match) throw new InvalidCaipIdError(id);
|
|
19
|
+
return { chainId: Number(match[1]), address: match[2].toLowerCase() };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function formatApiVaultId(chainId: number, address: string): string {
|
|
23
|
+
return `${chainId}:${address.toLowerCase()}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Resolves a manifest vault id (e.g. `VaultId.AeraUsdAlpha` / `'gtusda'`) to
|
|
28
|
+
* the Gaia API's CAIP-10 id for the vault's deployment on `chainId`.
|
|
29
|
+
*
|
|
30
|
+
* Deployment resolution is `resolveVault` — the same rules tx-building uses:
|
|
31
|
+
* single-deployment vaults resolve directly (a mismatched explicit `chainId`
|
|
32
|
+
* throws `ChainMismatchError`), multi-chain vaults default to Base when
|
|
33
|
+
* `chainId` is omitted.
|
|
34
|
+
*/
|
|
35
|
+
export async function apiVaultIdFromVaultId(
|
|
36
|
+
client: GauntletClient,
|
|
37
|
+
vaultId: string,
|
|
38
|
+
chainId?: number
|
|
39
|
+
): Promise<string> {
|
|
40
|
+
const resolved = await resolveVault(client, vaultId, chainId);
|
|
41
|
+
if (!resolved) throw new VaultNotFoundError(vaultId, chainId);
|
|
42
|
+
return formatApiVaultId(resolved.vault.chainId, resolved.vault.vaultAddress);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolves a Gaia API CAIP-10 vault id back to the manifest vault id, or
|
|
47
|
+
* `undefined` when the vault is not in the bundled manifest (the API indexes
|
|
48
|
+
* more vaults than the manifest lists).
|
|
49
|
+
*/
|
|
50
|
+
export async function vaultIdFromApiVaultId(
|
|
51
|
+
client: GauntletClient,
|
|
52
|
+
apiVaultId: string
|
|
53
|
+
): Promise<string | undefined> {
|
|
54
|
+
const { chainId, address } = parseApiVaultId(apiVaultId);
|
|
55
|
+
const manifest = await client.manifest;
|
|
56
|
+
return manifest.vaults.find((v) =>
|
|
57
|
+
v.deployments.some(
|
|
58
|
+
(d) => d.chain === 'evm' && d.chainId === chainId && d.vaultAddress.toLowerCase() === address
|
|
59
|
+
)
|
|
60
|
+
)?.vaultId;
|
|
61
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import type { components } from './generated';
|
|
2
|
+
import { apiGet, type GauntletApiConfig, type QueryParams } from './http';
|
|
3
|
+
|
|
4
|
+
type Schemas = components['schemas'];
|
|
5
|
+
|
|
6
|
+
export type UserActivity = Schemas['UserActivity'];
|
|
7
|
+
export type UserActivityResponse = Schemas['UserActivityResponse'];
|
|
8
|
+
export type UserPosition = Schemas['UserPosition'];
|
|
9
|
+
export type UserAllPositionsResponse = Schemas['UserAllPositionsResponse'];
|
|
10
|
+
export type UserPositionLatestResponse = Schemas['UserPositionLatestResponse'];
|
|
11
|
+
export type UserPositionsTimeseriesResponse = Schemas['UserPositionsTimeseriesResponse'];
|
|
12
|
+
export type PositionTimeseriesPoint = Schemas['PositionTimeseriesPoint'];
|
|
13
|
+
export type VaultDetail = Schemas['VaultDetail'];
|
|
14
|
+
export type VaultDetailResponse = Schemas['VaultDetailResponse'];
|
|
15
|
+
export type VaultTimeseriesResponse = Schemas['VaultTimeseriesResponse'];
|
|
16
|
+
export type VaultTimeseriesPoint = Schemas['VaultTimeseriesPoint'];
|
|
17
|
+
export type VaultMetrics = Schemas['VaultMetrics'];
|
|
18
|
+
export type TvlResponse = Schemas['TvlResponse'];
|
|
19
|
+
export type LatestPriceResponse = Schemas['LatestPriceResponse'];
|
|
20
|
+
export type PriceTimeseriesResponse = Schemas['TimeseriesResponse'];
|
|
21
|
+
export type TokenRef = Schemas['TokenRef'];
|
|
22
|
+
export type PartialResponseError = Schemas['PartialResponseError'];
|
|
23
|
+
export type AmountPair = Schemas['AmountPair'];
|
|
24
|
+
export type TimeseriesMeta = Schemas['TimeseriesMeta'];
|
|
25
|
+
export type HealthResponse = Schemas['HealthResponse'];
|
|
26
|
+
export type ChainSyncStatus = Schemas['ChainSyncStatus'];
|
|
27
|
+
|
|
28
|
+
export interface PageOptions {
|
|
29
|
+
/** Opaque cursor from a previous response's `meta.next_cursor`. */
|
|
30
|
+
next?: string;
|
|
31
|
+
limit?: number;
|
|
32
|
+
order?: 'asc' | 'desc';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface TimeWindowOptions extends PageOptions {
|
|
36
|
+
/** ISO 8601 date (`2026-01-01`) or RFC 3339 timestamp. */
|
|
37
|
+
start?: string;
|
|
38
|
+
end?: string;
|
|
39
|
+
granularity?: 'hour' | 'day' | 'week' | 'month';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ActivityOptions extends PageOptions {
|
|
43
|
+
/** CAIP-10 vault id (`"{chainId}:{address}"`). Omit for wallet-wide activity. */
|
|
44
|
+
vaultId?: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface LatestPriceOptions {
|
|
48
|
+
address: string;
|
|
49
|
+
chainId: number;
|
|
50
|
+
/** Optional ISO 8601 timestamp for a point-in-time price. */
|
|
51
|
+
at?: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface PriceTimeseriesOptions {
|
|
55
|
+
address: string;
|
|
56
|
+
chainId: number;
|
|
57
|
+
start: string;
|
|
58
|
+
end: string;
|
|
59
|
+
granularity?: 'raw' | 'hour' | 'day' | 'week' | 'month';
|
|
60
|
+
limit?: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Typed client for the Gaia REST API (api.gauntlet.xyz).
|
|
65
|
+
*
|
|
66
|
+
* All response types are generated from the service's OpenAPI spec
|
|
67
|
+
* (`src/api/generated.ts`, regenerated via `yarn generate:api-types`) so they
|
|
68
|
+
* cannot drift from the server models. Values are returned exactly as the API
|
|
69
|
+
* emits them — human-unit decimal strings and CAIP-10 vault ids; use
|
|
70
|
+
* `decimalToBigInt` / `sharesToBigInt` and `apiVaultIdFromVaultId` /
|
|
71
|
+
* `vaultIdFromApiVaultId` to convert, or the higher-level `activityFlows` /
|
|
72
|
+
* `positionHistory` helpers for pre-normalized values.
|
|
73
|
+
*
|
|
74
|
+
* Available on a configured client as `client.api`, or standalone:
|
|
75
|
+
* ```ts
|
|
76
|
+
* const api = new GauntletApi({ apiKey: process.env.GAUNTLET_API_KEY });
|
|
77
|
+
* const { data } = await api.vaults();
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export class GauntletApi {
|
|
81
|
+
private readonly config: GauntletApiConfig;
|
|
82
|
+
|
|
83
|
+
constructor(config: GauntletApiConfig = {}) {
|
|
84
|
+
this.config = config;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
private get<T>(path: string, query?: QueryParams): Promise<T> {
|
|
88
|
+
return apiGet<T>(this.config, path, query);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** GET /health — service liveness (version + uptime). */
|
|
92
|
+
health(): Promise<HealthResponse> {
|
|
93
|
+
return this.get('/health');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** GET /health/chains — per-chain indexer sync freshness. */
|
|
97
|
+
chainSyncStatus(): Promise<ChainSyncStatus[]> {
|
|
98
|
+
return this.get('/health/chains');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** GET /v1/vaults — all indexed vaults with live metrics (TVL, APY, unit price). */
|
|
102
|
+
vaults(options: PageOptions = {}): Promise<{ data: VaultDetail[]; meta: TimeseriesMeta }> {
|
|
103
|
+
return this.get('/v1/vaults', { next: options.next, limit: options.limit });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** GET /v1/vaults/{vault_id} — one vault with live metrics. `vaultId` is CAIP-10. */
|
|
107
|
+
vault(vaultId: string): Promise<VaultDetailResponse> {
|
|
108
|
+
return this.get(`/v1/vaults/${encodeURIComponent(vaultId)}`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** GET /v1/vaults/{vault_id}/definition — raw indexed vault definition. */
|
|
112
|
+
vaultDefinition(vaultId: string): Promise<unknown> {
|
|
113
|
+
return this.get(`/v1/vaults/${encodeURIComponent(vaultId)}/definition`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** GET /v1/vaults/{vault_id}/timeseries — TVL / unit-price / APY history. */
|
|
117
|
+
vaultTimeseries(
|
|
118
|
+
vaultId: string,
|
|
119
|
+
options: TimeWindowOptions = {}
|
|
120
|
+
): Promise<VaultTimeseriesResponse> {
|
|
121
|
+
return this.get(`/v1/vaults/${encodeURIComponent(vaultId)}/timeseries`, { ...options });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** GET /v1/users/{wallet}/positions — all of a wallet's indexed positions with PnL. */
|
|
125
|
+
positions(walletAddress: string, options: PageOptions = {}): Promise<UserAllPositionsResponse> {
|
|
126
|
+
return this.get(`/v1/users/${encodeURIComponent(walletAddress)}/positions`, {
|
|
127
|
+
next: options.next,
|
|
128
|
+
limit: options.limit,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** GET /v1/users/{wallet}/positions/{vault_id} — one position with PnL breakdown. */
|
|
133
|
+
position(walletAddress: string, vaultId: string): Promise<UserPositionLatestResponse> {
|
|
134
|
+
return this.get(
|
|
135
|
+
`/v1/users/${encodeURIComponent(walletAddress)}/positions/${encodeURIComponent(vaultId)}`
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** GET /v1/users/{wallet}/positions/{vault_id}/timeseries — value / cost-basis / PnL / ROI history. */
|
|
140
|
+
positionTimeseries(
|
|
141
|
+
walletAddress: string,
|
|
142
|
+
vaultId: string,
|
|
143
|
+
options: TimeWindowOptions = {}
|
|
144
|
+
): Promise<UserPositionsTimeseriesResponse> {
|
|
145
|
+
return this.get(
|
|
146
|
+
`/v1/users/${encodeURIComponent(walletAddress)}/positions/${encodeURIComponent(vaultId)}/timeseries`,
|
|
147
|
+
{ ...options }
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** GET /v1/users/{wallet}/activity — one page of the wallet's immutable event log. */
|
|
152
|
+
activity(walletAddress: string, options: ActivityOptions = {}): Promise<UserActivityResponse> {
|
|
153
|
+
const { vaultId, ...page } = options;
|
|
154
|
+
return this.get(`/v1/users/${encodeURIComponent(walletAddress)}/activity`, {
|
|
155
|
+
vault_id: vaultId,
|
|
156
|
+
...page,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Iterates the wallet's full activity log, following `meta.next_cursor`
|
|
162
|
+
* across pages so callers never handle cursors.
|
|
163
|
+
*/
|
|
164
|
+
async *activityRows(
|
|
165
|
+
walletAddress: string,
|
|
166
|
+
options: Omit<ActivityOptions, 'next'> = {}
|
|
167
|
+
): AsyncGenerator<UserActivity> {
|
|
168
|
+
let next: string | undefined;
|
|
169
|
+
do {
|
|
170
|
+
const page = await this.activity(walletAddress, { ...options, next });
|
|
171
|
+
yield* page.data;
|
|
172
|
+
next = page.meta.next_cursor ?? undefined;
|
|
173
|
+
} while (next);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** GET /v1/tvl — aggregate Gauntlet TVL, optionally with per-source breakdown. */
|
|
177
|
+
tvl(options: { includeBreakdown?: boolean } = {}): Promise<TvlResponse> {
|
|
178
|
+
return this.get('/v1/tvl', { include_breakdown: options.includeBreakdown });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** GET /v1/prices — latest USD price for a token. */
|
|
182
|
+
latestPrice(options: LatestPriceOptions): Promise<LatestPriceResponse> {
|
|
183
|
+
return this.get('/v1/prices', {
|
|
184
|
+
address: options.address,
|
|
185
|
+
chain_id: options.chainId,
|
|
186
|
+
at: options.at,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** GET /v1/prices/timeseries — USD price history for a token. */
|
|
191
|
+
priceTimeseries(options: PriceTimeseriesOptions): Promise<PriceTimeseriesResponse> {
|
|
192
|
+
return this.get('/v1/prices/timeseries', {
|
|
193
|
+
address: options.address,
|
|
194
|
+
chain_id: options.chainId,
|
|
195
|
+
start: options.start,
|
|
196
|
+
end: options.end,
|
|
197
|
+
granularity: options.granularity,
|
|
198
|
+
limit: options.limit,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { formatUnits } from 'viem';
|
|
2
|
+
import { DecimalPrecisionError, InvalidDecimalError } from './errors';
|
|
3
|
+
|
|
4
|
+
const DECIMAL_RE = /^(-?)(\d+)(?:\.(\d+))?$/;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Converts an API decimal string (human units, e.g. `"1250.5"`) into base-unit
|
|
8
|
+
* bigint at the given token decimals (e.g. `1250500000n` for 6 decimals).
|
|
9
|
+
*
|
|
10
|
+
* The conversion is exact: a value with more significant fractional digits
|
|
11
|
+
* than `decimals` throws `DecimalPrecisionError` rather than rounding.
|
|
12
|
+
* Hand-rolled instead of viem's `parseUnits`, which silently rounds excess
|
|
13
|
+
* precision (`parseUnits('1.0000005', 6)` → `1000001n`) — unacceptable for
|
|
14
|
+
* financial amounts.
|
|
15
|
+
*/
|
|
16
|
+
export function decimalToBigInt(value: string, decimals: number): bigint {
|
|
17
|
+
if (!Number.isInteger(decimals) || decimals < 0) {
|
|
18
|
+
throw new InvalidDecimalError(`decimals=${decimals}`);
|
|
19
|
+
}
|
|
20
|
+
const match = DECIMAL_RE.exec(value);
|
|
21
|
+
if (!match) throw new InvalidDecimalError(value);
|
|
22
|
+
|
|
23
|
+
const [, sign, whole, frac = ''] = match;
|
|
24
|
+
if (frac.length > decimals && !/^0*$/.test(frac.slice(decimals))) {
|
|
25
|
+
throw new DecimalPrecisionError(value, decimals);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const scaled = BigInt(whole + frac.slice(0, decimals).padEnd(decimals, '0'));
|
|
29
|
+
return sign === '-' ? -scaled : scaled;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Formats a base-unit bigint back into the API's human decimal-string
|
|
34
|
+
* representation (no trailing fractional zeros, no exponent notation).
|
|
35
|
+
*/
|
|
36
|
+
export function bigIntToDecimal(value: bigint, decimals: number): string {
|
|
37
|
+
if (!Number.isInteger(decimals) || decimals < 0) {
|
|
38
|
+
throw new InvalidDecimalError(`decimals=${decimals}`);
|
|
39
|
+
}
|
|
40
|
+
return formatUnits(value, decimals);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Vault shares are always reported in 18-decimal units by the Gaia API. */
|
|
44
|
+
export const SHARE_DECIMALS = 18;
|
|
45
|
+
|
|
46
|
+
/** Parses an API share amount (decimal string) into base-unit bigint (1e18). */
|
|
47
|
+
export function sharesToBigInt(value: string): bigint {
|
|
48
|
+
return decimalToBigInt(value, SHARE_DECIMALS);
|
|
49
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { GauntletSDKError } from '../errors';
|
|
2
|
+
|
|
3
|
+
export class GauntletApiError extends GauntletSDKError {
|
|
4
|
+
readonly status: number;
|
|
5
|
+
readonly path: string;
|
|
6
|
+
/** Machine-readable code from the API error envelope (e.g. `NOT_FOUND`), when present. */
|
|
7
|
+
readonly code?: string;
|
|
8
|
+
|
|
9
|
+
constructor(params: { status: number; path: string; message: string; code?: string }) {
|
|
10
|
+
super(
|
|
11
|
+
`Gauntlet API request to "${params.path}" failed with ${params.status}: ${params.message}`
|
|
12
|
+
);
|
|
13
|
+
this.name = 'GauntletApiError';
|
|
14
|
+
this.status = params.status;
|
|
15
|
+
this.path = params.path;
|
|
16
|
+
this.code = params.code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class InvalidDecimalError extends GauntletSDKError {
|
|
21
|
+
readonly value: string;
|
|
22
|
+
|
|
23
|
+
constructor(value: string) {
|
|
24
|
+
super(`Value "${value}" is not a valid decimal string`);
|
|
25
|
+
this.name = 'InvalidDecimalError';
|
|
26
|
+
this.value = value;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class DecimalPrecisionError extends GauntletSDKError {
|
|
31
|
+
readonly value: string;
|
|
32
|
+
readonly decimals: number;
|
|
33
|
+
|
|
34
|
+
constructor(value: string, decimals: number) {
|
|
35
|
+
super(
|
|
36
|
+
`Decimal "${value}" has more fractional digits than the token's ${decimals} decimals; converting would lose precision`
|
|
37
|
+
);
|
|
38
|
+
this.name = 'DecimalPrecisionError';
|
|
39
|
+
this.value = value;
|
|
40
|
+
this.decimals = decimals;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class InvalidCaipIdError extends GauntletSDKError {
|
|
45
|
+
readonly id: string;
|
|
46
|
+
|
|
47
|
+
constructor(id: string) {
|
|
48
|
+
super(`"${id}" is not a valid CAIP-10 vault id (expected "{chainId}:{address}")`);
|
|
49
|
+
this.name = 'InvalidCaipIdError';
|
|
50
|
+
this.id = id;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class SettlementTimeoutError extends GauntletSDKError {
|
|
55
|
+
readonly requestHash: string;
|
|
56
|
+
readonly timeoutMs: number;
|
|
57
|
+
|
|
58
|
+
constructor(requestHash: string, timeoutMs: number) {
|
|
59
|
+
super(`Request "${requestHash}" did not settle within ${timeoutMs}ms`);
|
|
60
|
+
this.name = 'SettlementTimeoutError';
|
|
61
|
+
this.requestHash = requestHash;
|
|
62
|
+
this.timeoutMs = timeoutMs;
|
|
63
|
+
}
|
|
64
|
+
}
|