@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.
package/README.md ADDED
@@ -0,0 +1,393 @@
1
+ # @swarmvault/sdk
2
+
3
+ TypeScript SDK for the Swarm Vault API. Execute swaps and transactions on behalf of your swarm members with a simple, type-safe client.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @swarmvault/sdk
9
+ # or
10
+ pnpm add @swarmvault/sdk
11
+ # or
12
+ yarn add @swarmvault/sdk
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { SwarmVaultClient, BASE_MAINNET_TOKENS } from '@swarmvault/sdk';
19
+
20
+ // Initialize client with your API key
21
+ const client = new SwarmVaultClient({
22
+ apiKey: 'svk_your_api_key_here',
23
+ });
24
+
25
+ // Get your swarms
26
+ const swarms = await client.listSwarms();
27
+ const mySwarm = swarms.find(s => s.isManager);
28
+
29
+ // Check holdings
30
+ const holdings = await client.getSwarmHoldings(mySwarm.id);
31
+ console.log('ETH Balance:', holdings.ethBalance);
32
+ console.log('Tokens:', holdings.tokens);
33
+
34
+ // Preview a swap
35
+ const preview = await client.previewSwap(mySwarm.id, {
36
+ sellToken: BASE_MAINNET_TOKENS.USDC,
37
+ buyToken: BASE_MAINNET_TOKENS.WETH,
38
+ sellPercentage: 50, // Sell 50% of USDC
39
+ });
40
+
41
+ console.log('Expected output:', preview.totalBuyAmount, 'WETH');
42
+
43
+ // Execute the swap
44
+ const result = await client.executeSwap(mySwarm.id, {
45
+ sellToken: BASE_MAINNET_TOKENS.USDC,
46
+ buyToken: BASE_MAINNET_TOKENS.WETH,
47
+ sellPercentage: 50,
48
+ });
49
+
50
+ // Wait for completion
51
+ const tx = await client.waitForTransaction(result.transactionId, {
52
+ onPoll: (t) => console.log('Status:', t.status),
53
+ });
54
+
55
+ console.log('Swap completed!');
56
+ ```
57
+
58
+ ## Authentication
59
+
60
+ ### API Key (Recommended)
61
+
62
+ Generate an API key from the Swarm Vault settings page. API keys start with `svk_`.
63
+
64
+ ```typescript
65
+ const client = new SwarmVaultClient({
66
+ apiKey: 'svk_your_api_key_here',
67
+ });
68
+ ```
69
+
70
+ ### JWT Token
71
+
72
+ Alternatively, you can use a JWT token obtained through the SIWE login flow:
73
+
74
+ ```typescript
75
+ const client = new SwarmVaultClient({
76
+ jwt: 'eyJhbGciOiJIUzI1NiIs...',
77
+ });
78
+
79
+ // Or set it later
80
+ client.setJwt(token);
81
+ ```
82
+
83
+ ## API Reference
84
+
85
+ ### Client Options
86
+
87
+ ```typescript
88
+ const client = new SwarmVaultClient({
89
+ // API base URL (default: https://api.swarmvault.xyz)
90
+ baseUrl: 'https://api.swarmvault.xyz',
91
+
92
+ // API key for authentication
93
+ apiKey: 'svk_...',
94
+
95
+ // Or JWT token
96
+ jwt: 'eyJ...',
97
+
98
+ // Custom fetch function (optional, for testing)
99
+ fetch: customFetch,
100
+ });
101
+ ```
102
+
103
+ ### Authentication Methods
104
+
105
+ #### `getMe()`
106
+
107
+ Get the authenticated user.
108
+
109
+ ```typescript
110
+ const user = await client.getMe();
111
+ console.log(user.walletAddress);
112
+ console.log(user.twitterUsername);
113
+ ```
114
+
115
+ #### `setApiKey(key: string)`
116
+
117
+ Set or update the API key.
118
+
119
+ ```typescript
120
+ client.setApiKey('svk_new_key');
121
+ ```
122
+
123
+ #### `setJwt(token: string)`
124
+
125
+ Set or update the JWT token.
126
+
127
+ ```typescript
128
+ client.setJwt('eyJ...');
129
+ ```
130
+
131
+ ### Swarm Methods
132
+
133
+ #### `listSwarms()`
134
+
135
+ List all swarms. Returns your management status for authenticated requests.
136
+
137
+ ```typescript
138
+ const swarms = await client.listSwarms();
139
+ const managedSwarms = swarms.filter(s => s.isManager);
140
+ ```
141
+
142
+ #### `getSwarm(swarmId: string)`
143
+
144
+ Get details of a specific swarm.
145
+
146
+ ```typescript
147
+ const swarm = await client.getSwarm('swarm-id');
148
+ console.log(swarm.name, swarm.memberCount);
149
+ ```
150
+
151
+ #### `getSwarmMembers(swarmId: string)`
152
+
153
+ Get members of a swarm. **Manager only.**
154
+
155
+ ```typescript
156
+ const members = await client.getSwarmMembers('swarm-id');
157
+ for (const member of members) {
158
+ console.log(member.agentWalletAddress, member.status);
159
+ }
160
+ ```
161
+
162
+ #### `getSwarmHoldings(swarmId: string)`
163
+
164
+ Get aggregate token holdings across all swarm members. **Manager only.**
165
+
166
+ ```typescript
167
+ const holdings = await client.getSwarmHoldings('swarm-id');
168
+ console.log('ETH:', holdings.ethBalance);
169
+ console.log('Members:', holdings.memberCount);
170
+ for (const token of holdings.tokens) {
171
+ console.log(`${token.symbol}: ${token.totalBalance} (${token.holderCount} holders)`);
172
+ }
173
+ ```
174
+
175
+ ### Swap Methods
176
+
177
+ #### `previewSwap(swarmId: string, params: SwapPreviewParams)`
178
+
179
+ Preview a swap without executing it. **Manager only.**
180
+
181
+ ```typescript
182
+ const preview = await client.previewSwap('swarm-id', {
183
+ sellToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
184
+ buyToken: '0x4200000000000000000000000000000000000006', // WETH
185
+ sellPercentage: 50, // Sell 50% of balance (default: 100)
186
+ slippagePercentage: 1, // 1% slippage (default: 1)
187
+ });
188
+
189
+ console.log('Total sell:', preview.totalSellAmount);
190
+ console.log('Total buy:', preview.totalBuyAmount);
191
+ console.log('Success:', preview.successCount);
192
+ console.log('Errors:', preview.errorCount);
193
+
194
+ // Per-member breakdown
195
+ for (const member of preview.members) {
196
+ if (member.error) {
197
+ console.log(`${member.agentWalletAddress}: Error - ${member.error}`);
198
+ } else {
199
+ console.log(`${member.agentWalletAddress}: ${member.sellAmount} → ${member.buyAmount}`);
200
+ }
201
+ }
202
+ ```
203
+
204
+ #### `executeSwap(swarmId: string, params: SwapExecuteParams)`
205
+
206
+ Execute a swap for all swarm members. **Manager only.**
207
+
208
+ A platform fee (default 0.5%) is deducted from the buy token amount.
209
+
210
+ ```typescript
211
+ const result = await client.executeSwap('swarm-id', {
212
+ sellToken: BASE_MAINNET_TOKENS.USDC,
213
+ buyToken: BASE_MAINNET_TOKENS.WETH,
214
+ sellPercentage: 50,
215
+ slippagePercentage: 1,
216
+ });
217
+
218
+ console.log('Transaction ID:', result.transactionId);
219
+ console.log('Members:', result.memberCount);
220
+ console.log('Fee:', result.fee?.percentage);
221
+ ```
222
+
223
+ ### Transaction Methods
224
+
225
+ #### `executeTransaction(swarmId: string, template: TransactionTemplate)`
226
+
227
+ Execute a raw transaction template. **Manager only.** For swaps, prefer `executeSwap`.
228
+
229
+ ```typescript
230
+ // ABI mode
231
+ const result = await client.executeTransaction('swarm-id', {
232
+ mode: 'abi',
233
+ contractAddress: '0x...',
234
+ abi: [{ name: 'transfer', type: 'function', ... }],
235
+ functionName: 'transfer',
236
+ args: ['0xRecipient', '{{percentage:tokenBalance:0x...:50}}'],
237
+ value: '0',
238
+ });
239
+
240
+ // Raw calldata mode
241
+ const result = await client.executeTransaction('swarm-id', {
242
+ mode: 'raw',
243
+ contractAddress: '0x...',
244
+ data: '0xa9059cbb...',
245
+ value: '0',
246
+ });
247
+ ```
248
+
249
+ #### `listTransactions(swarmId: string)`
250
+
251
+ List all transactions for a swarm.
252
+
253
+ ```typescript
254
+ const transactions = await client.listTransactions('swarm-id');
255
+ for (const tx of transactions) {
256
+ console.log(tx.id, tx.status, tx.createdAt);
257
+ }
258
+ ```
259
+
260
+ #### `getTransaction(transactionId: string)`
261
+
262
+ Get transaction details including per-member status.
263
+
264
+ ```typescript
265
+ const tx = await client.getTransaction('tx-id');
266
+ console.log('Status:', tx.status);
267
+ for (const target of tx.targets || []) {
268
+ console.log(`${target.membership?.agentWalletAddress}: ${target.status}`);
269
+ }
270
+ ```
271
+
272
+ #### `waitForTransaction(transactionId: string, options?: WaitForTransactionOptions)`
273
+
274
+ Wait for a transaction to complete.
275
+
276
+ ```typescript
277
+ const tx = await client.waitForTransaction('tx-id', {
278
+ timeoutMs: 300000, // 5 minutes (default)
279
+ pollIntervalMs: 3000, // 3 seconds (default)
280
+ onPoll: (transaction) => {
281
+ const confirmed = transaction.targets?.filter(t => t.status === 'CONFIRMED').length ?? 0;
282
+ const total = transaction.targets?.length ?? 0;
283
+ console.log(`Progress: ${confirmed}/${total}`);
284
+ },
285
+ });
286
+
287
+ console.log('Final status:', tx.status);
288
+ ```
289
+
290
+ ## Token Constants
291
+
292
+ The SDK exports common token addresses for convenience:
293
+
294
+ ```typescript
295
+ import {
296
+ NATIVE_ETH_ADDRESS,
297
+ BASE_MAINNET_TOKENS,
298
+ BASE_SEPOLIA_TOKENS
299
+ } from '@swarmvault/sdk';
300
+
301
+ // Native ETH (for swaps)
302
+ const ethAddress = NATIVE_ETH_ADDRESS;
303
+ // => '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE'
304
+
305
+ // Base Mainnet tokens
306
+ BASE_MAINNET_TOKENS.USDC // => '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'
307
+ BASE_MAINNET_TOKENS.WETH // => '0x4200000000000000000000000000000000000006'
308
+ BASE_MAINNET_TOKENS.DAI // => '0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb'
309
+ BASE_MAINNET_TOKENS.USDbC // => '0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA'
310
+ BASE_MAINNET_TOKENS.cbETH // => '0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22'
311
+
312
+ // Base Sepolia tokens (testnet)
313
+ BASE_SEPOLIA_TOKENS.USDC // => '0x036CbD53842c5426634e7929541eC2318f3dCF7e'
314
+ BASE_SEPOLIA_TOKENS.WETH // => '0x4200000000000000000000000000000000000006'
315
+ ```
316
+
317
+ ## Error Handling
318
+
319
+ The SDK throws `SwarmVaultError` for API errors:
320
+
321
+ ```typescript
322
+ import { SwarmVaultClient, SwarmVaultError } from '@swarmvault/sdk';
323
+
324
+ try {
325
+ const holdings = await client.getSwarmHoldings('swarm-id');
326
+ } catch (error) {
327
+ if (error instanceof SwarmVaultError) {
328
+ console.error('Message:', error.message);
329
+ console.error('Error Code:', error.errorCode);
330
+ console.error('Status Code:', error.statusCode);
331
+ console.error('Details:', error.details);
332
+ }
333
+ }
334
+ ```
335
+
336
+ ### Common Error Codes
337
+
338
+ | Code | Description |
339
+ |------|-------------|
340
+ | `AUTH_001` | Unauthorized - missing or invalid authentication |
341
+ | `AUTH_002` | Invalid token |
342
+ | `RES_003` | Swarm not found |
343
+ | `PERM_002` | Not a manager of this swarm |
344
+ | `TX_001` | Transaction failed |
345
+ | `TX_003` | Insufficient balance |
346
+
347
+ ## Template Placeholders
348
+
349
+ When using `executeTransaction`, you can use placeholders that get resolved per-member:
350
+
351
+ | Placeholder | Description | Example |
352
+ |-------------|-------------|---------|
353
+ | `{{walletAddress}}` | Agent wallet address | `0x1234...` |
354
+ | `{{ethBalance}}` | ETH balance (wei) | `1000000000000000000` |
355
+ | `{{tokenBalance:0xAddr}}` | Token balance | `500000000` |
356
+ | `{{percentage:ethBalance:50}}` | 50% of ETH | `500000000000000000` |
357
+ | `{{percentage:tokenBalance:0xAddr:100}}` | 100% of token | `500000000` |
358
+ | `{{blockTimestamp}}` | Current timestamp | `1704567890` |
359
+ | `{{deadline:300}}` | Timestamp + 300s | `1704568190` |
360
+ | `{{slippage:amount:5}}` | Amount - 5% | `950000000` |
361
+
362
+ ## Examples
363
+
364
+ See the [examples directory](./examples) for complete working examples:
365
+
366
+ - `check-holdings.ts` - View holdings across all managed swarms
367
+ - `swap-usdc-to-weth.ts` - Preview and execute a swap
368
+
369
+ ## TypeScript
370
+
371
+ The SDK is fully typed. Import types as needed:
372
+
373
+ ```typescript
374
+ import type {
375
+ Swarm,
376
+ SwarmMember,
377
+ SwarmHoldings,
378
+ Transaction,
379
+ TransactionTarget,
380
+ SwapPreviewResult,
381
+ SwapExecuteResult,
382
+ SwarmVaultClientOptions,
383
+ } from '@swarmvault/sdk';
384
+ ```
385
+
386
+ ## Requirements
387
+
388
+ - Node.js 18+ (for native fetch) or provide a custom fetch implementation
389
+ - TypeScript 4.7+ (optional, for type checking)
390
+
391
+ ## License
392
+
393
+ MIT