@swarmvault/sdk 0.1.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.
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Swarm Vault SDK Types
3
+ */
4
+ interface User {
5
+ id: string;
6
+ walletAddress: string;
7
+ twitterId: string | null;
8
+ twitterUsername: string | null;
9
+ createdAt: string;
10
+ updatedAt: string;
11
+ }
12
+ interface Swarm {
13
+ id: string;
14
+ name: string;
15
+ description: string;
16
+ createdAt: string;
17
+ updatedAt: string;
18
+ manager?: {
19
+ id: string;
20
+ walletAddress: string;
21
+ twitterUsername: string | null;
22
+ };
23
+ memberCount?: number;
24
+ isManager?: boolean;
25
+ }
26
+ interface SwarmMember {
27
+ id: string;
28
+ swarmId: string;
29
+ userId: string;
30
+ agentWalletAddress: string;
31
+ status: "ACTIVE" | "LEFT";
32
+ joinedAt: string;
33
+ user?: {
34
+ id: string;
35
+ walletAddress: string;
36
+ };
37
+ }
38
+ type TransactionStatus = "PENDING" | "PROCESSING" | "COMPLETED" | "FAILED";
39
+ type TransactionTargetStatus = "PENDING" | "SUBMITTED" | "CONFIRMED" | "FAILED";
40
+ interface Transaction {
41
+ id: string;
42
+ swarmId: string;
43
+ status: TransactionStatus;
44
+ template: TransactionTemplate;
45
+ createdAt: string;
46
+ updatedAt: string;
47
+ targets?: TransactionTarget[];
48
+ }
49
+ interface TransactionTarget {
50
+ id: string;
51
+ transactionId: string;
52
+ membershipId: string;
53
+ userOpHash: string | null;
54
+ txHash: string | null;
55
+ status: TransactionTargetStatus;
56
+ error: string | null;
57
+ createdAt: string;
58
+ updatedAt: string;
59
+ membership?: {
60
+ agentWalletAddress: string;
61
+ user?: {
62
+ walletAddress: string;
63
+ };
64
+ };
65
+ }
66
+ interface ABITransactionTemplate {
67
+ mode: "abi";
68
+ contractAddress: string;
69
+ abi: unknown[];
70
+ functionName: string;
71
+ args: unknown[];
72
+ value: string;
73
+ }
74
+ interface RawTransactionTemplate {
75
+ mode: "raw";
76
+ contractAddress: string;
77
+ data: string;
78
+ value: string;
79
+ }
80
+ type TransactionTemplate = ABITransactionTemplate | RawTransactionTemplate;
81
+ interface SwapPreviewParams {
82
+ /** Token address to sell (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native ETH) */
83
+ sellToken: string;
84
+ /** Token address to buy */
85
+ buyToken: string;
86
+ /** Percentage of token balance to sell (1-100, default 100) */
87
+ sellPercentage?: number;
88
+ /** Slippage tolerance percentage (default 1) */
89
+ slippagePercentage?: number;
90
+ }
91
+ interface SwapExecuteParams extends SwapPreviewParams {
92
+ }
93
+ interface SwapMemberPreview {
94
+ membershipId: string;
95
+ userId: string;
96
+ userWalletAddress: string;
97
+ agentWalletAddress: string;
98
+ sellAmount: string;
99
+ buyAmount: string;
100
+ feeAmount?: string;
101
+ estimatedPriceImpact?: number;
102
+ sources?: string[];
103
+ error?: string;
104
+ }
105
+ interface SwapFeeInfo {
106
+ bps: number;
107
+ percentage: string;
108
+ recipientAddress: string;
109
+ }
110
+ interface SwapPreviewResult {
111
+ sellToken: string;
112
+ buyToken: string;
113
+ sellPercentage: number;
114
+ slippagePercentage: number;
115
+ members: SwapMemberPreview[];
116
+ totalSellAmount: string;
117
+ totalBuyAmount: string;
118
+ totalFeeAmount?: string;
119
+ successCount: number;
120
+ errorCount: number;
121
+ fee: SwapFeeInfo | null;
122
+ }
123
+ interface SwapExecuteResult {
124
+ transactionId: string;
125
+ status: "PENDING";
126
+ memberCount: number;
127
+ message: string;
128
+ fee: SwapFeeInfo | null;
129
+ }
130
+ interface TokenInfo {
131
+ address: string;
132
+ symbol: string;
133
+ name: string;
134
+ decimals: number;
135
+ logoUrl?: string;
136
+ }
137
+ interface TokenHolding extends TokenInfo {
138
+ totalBalance: string;
139
+ holderCount: number;
140
+ }
141
+ interface SwarmHoldings {
142
+ ethBalance: string;
143
+ tokens: TokenHolding[];
144
+ memberCount: number;
145
+ commonTokens: TokenInfo[];
146
+ }
147
+ interface ApiResponse<T> {
148
+ success: boolean;
149
+ data?: T;
150
+ error?: string;
151
+ errorCode?: string;
152
+ details?: unknown;
153
+ }
154
+ interface SwarmVaultClientOptions {
155
+ /** Base URL of the Swarm Vault API (default: https://api.swarmvault.xyz) */
156
+ baseUrl?: string;
157
+ /** API key for authentication (starts with 'svk_') */
158
+ apiKey?: string;
159
+ /** JWT token for authentication (alternative to API key) */
160
+ jwt?: string;
161
+ /** Custom fetch function (for testing or custom implementations) */
162
+ fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
163
+ }
164
+ interface WaitForTransactionOptions {
165
+ /** Maximum time to wait in milliseconds (default: 300000 = 5 minutes) */
166
+ timeoutMs?: number;
167
+ /** Polling interval in milliseconds (default: 3000 = 3 seconds) */
168
+ pollIntervalMs?: number;
169
+ /** Callback called on each poll with current status */
170
+ onPoll?: (transaction: Transaction) => void;
171
+ }
172
+ declare class SwarmVaultError extends Error {
173
+ readonly errorCode?: string;
174
+ readonly statusCode?: number;
175
+ readonly details?: unknown;
176
+ constructor(message: string, options?: {
177
+ errorCode?: string;
178
+ statusCode?: number;
179
+ details?: unknown;
180
+ });
181
+ }
182
+ /** Native ETH address used in swap APIs */
183
+ declare const NATIVE_ETH_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
184
+ /** Common token addresses on Base Mainnet */
185
+ declare const BASE_MAINNET_TOKENS: {
186
+ readonly ETH: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
187
+ readonly WETH: "0x4200000000000000000000000000000000000006";
188
+ readonly USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
189
+ readonly DAI: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb";
190
+ readonly USDbC: "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA";
191
+ readonly cbETH: "0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22";
192
+ };
193
+ /** Common token addresses on Base Sepolia (testnet) */
194
+ declare const BASE_SEPOLIA_TOKENS: {
195
+ readonly ETH: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
196
+ readonly WETH: "0x4200000000000000000000000000000000000006";
197
+ readonly USDC: "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
198
+ };
199
+
200
+ /**
201
+ * Swarm Vault SDK Client
202
+ *
203
+ * A TypeScript client for the Swarm Vault API, enabling managers to execute
204
+ * swaps and transactions on behalf of their swarm members.
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * import { SwarmVaultClient } from '@swarmvault/sdk';
209
+ *
210
+ * const client = new SwarmVaultClient({
211
+ * apiKey: 'svk_your_api_key_here',
212
+ * });
213
+ *
214
+ * // Get swarm holdings
215
+ * const holdings = await client.getSwarmHoldings('swarm-id');
216
+ *
217
+ * // Execute a swap
218
+ * const result = await client.executeSwap('swarm-id', {
219
+ * sellToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
220
+ * buyToken: '0x4200000000000000000000000000000000000006', // WETH
221
+ * sellPercentage: 50,
222
+ * });
223
+ *
224
+ * // Wait for completion
225
+ * const tx = await client.waitForTransaction(result.transactionId);
226
+ * ```
227
+ */
228
+
229
+ declare class SwarmVaultClient {
230
+ private baseUrl;
231
+ private apiKey?;
232
+ private jwt?;
233
+ private fetchFn;
234
+ /**
235
+ * Create a new Swarm Vault client.
236
+ *
237
+ * @param options - Client configuration options
238
+ * @param options.baseUrl - Base URL of the API (default: https://api.swarmvault.xyz)
239
+ * @param options.apiKey - API key for authentication (recommended)
240
+ * @param options.jwt - JWT token for authentication (alternative to API key)
241
+ */
242
+ constructor(options?: SwarmVaultClientOptions);
243
+ /**
244
+ * Set the API key for authentication.
245
+ * API keys start with 'svk_' and can be generated in the Swarm Vault settings.
246
+ *
247
+ * @param apiKey - The API key
248
+ */
249
+ setApiKey(apiKey: string): void;
250
+ /**
251
+ * Set the JWT token for authentication.
252
+ * JWTs are obtained through the SIWE login flow.
253
+ *
254
+ * @param jwt - The JWT token
255
+ */
256
+ setJwt(jwt: string): void;
257
+ /**
258
+ * Get the currently authenticated user.
259
+ *
260
+ * @returns The authenticated user
261
+ * @throws {SwarmVaultError} If not authenticated or request fails
262
+ */
263
+ getMe(): Promise<User>;
264
+ /**
265
+ * List all swarms. Returns public swarms for unauthenticated requests,
266
+ * or includes management status for authenticated requests.
267
+ *
268
+ * @returns Array of swarms
269
+ */
270
+ listSwarms(): Promise<Swarm[]>;
271
+ /**
272
+ * Get details of a specific swarm.
273
+ *
274
+ * @param swarmId - The swarm ID
275
+ * @returns Swarm details
276
+ * @throws {SwarmVaultError} If swarm not found
277
+ */
278
+ getSwarm(swarmId: string): Promise<Swarm>;
279
+ /**
280
+ * Get members of a swarm.
281
+ * **Manager only** - requires authentication as a swarm manager.
282
+ *
283
+ * @param swarmId - The swarm ID
284
+ * @returns Array of swarm members
285
+ * @throws {SwarmVaultError} If not authorized or swarm not found
286
+ */
287
+ getSwarmMembers(swarmId: string): Promise<SwarmMember[]>;
288
+ /**
289
+ * Get aggregate token holdings across all swarm members.
290
+ * **Manager only** - requires authentication as a swarm manager.
291
+ *
292
+ * @param swarmId - The swarm ID
293
+ * @returns Aggregated holdings with ETH balance, token balances, and common tokens
294
+ * @throws {SwarmVaultError} If not authorized or swarm not found
295
+ */
296
+ getSwarmHoldings(swarmId: string): Promise<SwarmHoldings>;
297
+ /**
298
+ * Preview a swap for all swarm members without executing it.
299
+ * **Manager only** - requires authentication as a swarm manager.
300
+ *
301
+ * Use this to see expected amounts before executing a swap.
302
+ *
303
+ * @param swarmId - The swarm ID
304
+ * @param params - Swap parameters
305
+ * @param params.sellToken - Token address to sell (use NATIVE_ETH_ADDRESS for ETH)
306
+ * @param params.buyToken - Token address to buy
307
+ * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
308
+ * @param params.slippagePercentage - Slippage tolerance (default 1%)
309
+ * @returns Preview with per-member amounts and totals
310
+ *
311
+ * @example
312
+ * ```typescript
313
+ * const preview = await client.previewSwap('swarm-id', {
314
+ * sellToken: BASE_MAINNET_TOKENS.USDC,
315
+ * buyToken: BASE_MAINNET_TOKENS.WETH,
316
+ * sellPercentage: 50,
317
+ * slippagePercentage: 1,
318
+ * });
319
+ *
320
+ * console.log(`Total sell: ${preview.totalSellAmount}`);
321
+ * console.log(`Expected buy: ${preview.totalBuyAmount}`);
322
+ * console.log(`Success: ${preview.successCount}, Errors: ${preview.errorCount}`);
323
+ * ```
324
+ */
325
+ previewSwap(swarmId: string, params: SwapPreviewParams): Promise<SwapPreviewResult>;
326
+ /**
327
+ * Execute a swap for all swarm members.
328
+ * **Manager only** - requires authentication as a swarm manager.
329
+ *
330
+ * The swap is executed asynchronously. Use `waitForTransaction` to wait for completion.
331
+ *
332
+ * A platform fee (default 0.5%) is deducted from the buy token amount.
333
+ *
334
+ * @param swarmId - The swarm ID
335
+ * @param params - Swap parameters
336
+ * @param params.sellToken - Token address to sell
337
+ * @param params.buyToken - Token address to buy
338
+ * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
339
+ * @param params.slippagePercentage - Slippage tolerance (default 1%)
340
+ * @returns Transaction ID and status
341
+ *
342
+ * @example
343
+ * ```typescript
344
+ * // Execute swap
345
+ * const result = await client.executeSwap('swarm-id', {
346
+ * sellToken: BASE_MAINNET_TOKENS.USDC,
347
+ * buyToken: BASE_MAINNET_TOKENS.WETH,
348
+ * sellPercentage: 50,
349
+ * });
350
+ *
351
+ * console.log(`Transaction started: ${result.transactionId}`);
352
+ *
353
+ * // Wait for completion
354
+ * const tx = await client.waitForTransaction(result.transactionId, {
355
+ * onPoll: (t) => console.log(`Status: ${t.status}`),
356
+ * });
357
+ *
358
+ * console.log(`Transaction ${tx.status}`);
359
+ * ```
360
+ */
361
+ executeSwap(swarmId: string, params: SwapExecuteParams): Promise<SwapExecuteResult>;
362
+ /**
363
+ * Execute a raw transaction template for all swarm members.
364
+ * **Manager only** - requires authentication as a swarm manager.
365
+ *
366
+ * This is an advanced method for custom transactions. For swaps, prefer `executeSwap`.
367
+ *
368
+ * @param swarmId - The swarm ID
369
+ * @param template - Transaction template (ABI mode or raw calldata mode)
370
+ * @returns Transaction ID and status
371
+ *
372
+ * @example
373
+ * ```typescript
374
+ * // ABI mode example - transfer tokens
375
+ * const result = await client.executeTransaction('swarm-id', {
376
+ * mode: 'abi',
377
+ * contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
378
+ * abi: [{
379
+ * name: 'transfer',
380
+ * type: 'function',
381
+ * inputs: [
382
+ * { name: 'to', type: 'address' },
383
+ * { name: 'amount', type: 'uint256' },
384
+ * ],
385
+ * outputs: [{ type: 'bool' }],
386
+ * }],
387
+ * functionName: 'transfer',
388
+ * args: ['0xRecipient', '{{percentage:tokenBalance:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913:50}}'],
389
+ * value: '0',
390
+ * });
391
+ * ```
392
+ */
393
+ executeTransaction(swarmId: string, template: TransactionTemplate): Promise<{
394
+ transactionId: string;
395
+ status: string;
396
+ }>;
397
+ /**
398
+ * List transactions for a swarm.
399
+ *
400
+ * @param swarmId - The swarm ID
401
+ * @returns Array of transactions
402
+ */
403
+ listTransactions(swarmId: string): Promise<Transaction[]>;
404
+ /**
405
+ * Get details of a specific transaction, including per-member status.
406
+ *
407
+ * @param transactionId - The transaction ID
408
+ * @returns Transaction details with targets
409
+ */
410
+ getTransaction(transactionId: string): Promise<Transaction>;
411
+ /**
412
+ * Wait for a transaction to complete.
413
+ *
414
+ * Polls the transaction status until it reaches COMPLETED or FAILED,
415
+ * or until the timeout is reached.
416
+ *
417
+ * @param transactionId - The transaction ID
418
+ * @param options - Wait options
419
+ * @param options.timeoutMs - Maximum wait time (default 5 minutes)
420
+ * @param options.pollIntervalMs - Polling interval (default 3 seconds)
421
+ * @param options.onPoll - Callback called on each poll
422
+ * @returns The completed transaction
423
+ * @throws {SwarmVaultError} If timeout is reached or transaction fails
424
+ *
425
+ * @example
426
+ * ```typescript
427
+ * const tx = await client.waitForTransaction(transactionId, {
428
+ * timeoutMs: 60000, // 1 minute
429
+ * pollIntervalMs: 2000, // 2 seconds
430
+ * onPoll: (t) => {
431
+ * const confirmed = t.targets?.filter(t => t.status === 'CONFIRMED').length ?? 0;
432
+ * const total = t.targets?.length ?? 0;
433
+ * console.log(`Progress: ${confirmed}/${total}`);
434
+ * },
435
+ * });
436
+ * ```
437
+ */
438
+ waitForTransaction(transactionId: string, options?: WaitForTransactionOptions): Promise<Transaction>;
439
+ private request;
440
+ private sleep;
441
+ }
442
+
443
+ export { type ABITransactionTemplate, type ApiResponse, BASE_MAINNET_TOKENS, BASE_SEPOLIA_TOKENS, NATIVE_ETH_ADDRESS, type RawTransactionTemplate, type SwapExecuteParams, type SwapExecuteResult, type SwapFeeInfo, type SwapMemberPreview, type SwapPreviewParams, type SwapPreviewResult, type Swarm, type SwarmHoldings, type SwarmMember, SwarmVaultClient, type SwarmVaultClientOptions, SwarmVaultError, type TokenHolding, type TokenInfo, type Transaction, type TransactionStatus, type TransactionTarget, type TransactionTargetStatus, type TransactionTemplate, type User, type WaitForTransactionOptions };