@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 +393 -0
- package/dist/index.cjs +372 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +443 -0
- package/dist/index.d.ts +443 -0
- package/dist/index.js +366 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/types.ts
|
|
4
|
+
var SwarmVaultError = class extends Error {
|
|
5
|
+
errorCode;
|
|
6
|
+
statusCode;
|
|
7
|
+
details;
|
|
8
|
+
constructor(message, options) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.name = "SwarmVaultError";
|
|
11
|
+
this.errorCode = options?.errorCode;
|
|
12
|
+
this.statusCode = options?.statusCode;
|
|
13
|
+
this.details = options?.details;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var NATIVE_ETH_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
17
|
+
var BASE_MAINNET_TOKENS = {
|
|
18
|
+
ETH: NATIVE_ETH_ADDRESS,
|
|
19
|
+
WETH: "0x4200000000000000000000000000000000000006",
|
|
20
|
+
USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
|
|
21
|
+
DAI: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
|
|
22
|
+
USDbC: "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",
|
|
23
|
+
cbETH: "0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22"
|
|
24
|
+
};
|
|
25
|
+
var BASE_SEPOLIA_TOKENS = {
|
|
26
|
+
ETH: NATIVE_ETH_ADDRESS,
|
|
27
|
+
WETH: "0x4200000000000000000000000000000000000006",
|
|
28
|
+
USDC: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// src/client.ts
|
|
32
|
+
var DEFAULT_BASE_URL = "https://api.swarmvault.xyz";
|
|
33
|
+
var DEFAULT_TIMEOUT_MS = 3e5;
|
|
34
|
+
var DEFAULT_POLL_INTERVAL_MS = 3e3;
|
|
35
|
+
var SwarmVaultClient = class {
|
|
36
|
+
baseUrl;
|
|
37
|
+
apiKey;
|
|
38
|
+
jwt;
|
|
39
|
+
fetchFn;
|
|
40
|
+
/**
|
|
41
|
+
* Create a new Swarm Vault client.
|
|
42
|
+
*
|
|
43
|
+
* @param options - Client configuration options
|
|
44
|
+
* @param options.baseUrl - Base URL of the API (default: https://api.swarmvault.xyz)
|
|
45
|
+
* @param options.apiKey - API key for authentication (recommended)
|
|
46
|
+
* @param options.jwt - JWT token for authentication (alternative to API key)
|
|
47
|
+
*/
|
|
48
|
+
constructor(options = {}) {
|
|
49
|
+
this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
50
|
+
this.apiKey = options.apiKey;
|
|
51
|
+
this.jwt = options.jwt;
|
|
52
|
+
this.fetchFn = options.fetch || globalThis.fetch;
|
|
53
|
+
if (!this.fetchFn) {
|
|
54
|
+
throw new SwarmVaultError(
|
|
55
|
+
"fetch is not available. Please provide a fetch implementation or use Node.js 18+."
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// ===========================================================================
|
|
60
|
+
// Authentication
|
|
61
|
+
// ===========================================================================
|
|
62
|
+
/**
|
|
63
|
+
* Set the API key for authentication.
|
|
64
|
+
* API keys start with 'svk_' and can be generated in the Swarm Vault settings.
|
|
65
|
+
*
|
|
66
|
+
* @param apiKey - The API key
|
|
67
|
+
*/
|
|
68
|
+
setApiKey(apiKey) {
|
|
69
|
+
this.apiKey = apiKey;
|
|
70
|
+
this.jwt = void 0;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Set the JWT token for authentication.
|
|
74
|
+
* JWTs are obtained through the SIWE login flow.
|
|
75
|
+
*
|
|
76
|
+
* @param jwt - The JWT token
|
|
77
|
+
*/
|
|
78
|
+
setJwt(jwt) {
|
|
79
|
+
this.jwt = jwt;
|
|
80
|
+
this.apiKey = void 0;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Get the currently authenticated user.
|
|
84
|
+
*
|
|
85
|
+
* @returns The authenticated user
|
|
86
|
+
* @throws {SwarmVaultError} If not authenticated or request fails
|
|
87
|
+
*/
|
|
88
|
+
async getMe() {
|
|
89
|
+
return this.request("GET", "/api/auth/me");
|
|
90
|
+
}
|
|
91
|
+
// ===========================================================================
|
|
92
|
+
// Swarms
|
|
93
|
+
// ===========================================================================
|
|
94
|
+
/**
|
|
95
|
+
* List all swarms. Returns public swarms for unauthenticated requests,
|
|
96
|
+
* or includes management status for authenticated requests.
|
|
97
|
+
*
|
|
98
|
+
* @returns Array of swarms
|
|
99
|
+
*/
|
|
100
|
+
async listSwarms() {
|
|
101
|
+
return this.request("GET", "/api/swarms");
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Get details of a specific swarm.
|
|
105
|
+
*
|
|
106
|
+
* @param swarmId - The swarm ID
|
|
107
|
+
* @returns Swarm details
|
|
108
|
+
* @throws {SwarmVaultError} If swarm not found
|
|
109
|
+
*/
|
|
110
|
+
async getSwarm(swarmId) {
|
|
111
|
+
return this.request("GET", `/api/swarms/${swarmId}`);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Get members of a swarm.
|
|
115
|
+
* **Manager only** - requires authentication as a swarm manager.
|
|
116
|
+
*
|
|
117
|
+
* @param swarmId - The swarm ID
|
|
118
|
+
* @returns Array of swarm members
|
|
119
|
+
* @throws {SwarmVaultError} If not authorized or swarm not found
|
|
120
|
+
*/
|
|
121
|
+
async getSwarmMembers(swarmId) {
|
|
122
|
+
return this.request("GET", `/api/swarms/${swarmId}/members`);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Get aggregate token holdings across all swarm members.
|
|
126
|
+
* **Manager only** - requires authentication as a swarm manager.
|
|
127
|
+
*
|
|
128
|
+
* @param swarmId - The swarm ID
|
|
129
|
+
* @returns Aggregated holdings with ETH balance, token balances, and common tokens
|
|
130
|
+
* @throws {SwarmVaultError} If not authorized or swarm not found
|
|
131
|
+
*/
|
|
132
|
+
async getSwarmHoldings(swarmId) {
|
|
133
|
+
return this.request("GET", `/api/swarms/${swarmId}/holdings`);
|
|
134
|
+
}
|
|
135
|
+
// ===========================================================================
|
|
136
|
+
// Swaps
|
|
137
|
+
// ===========================================================================
|
|
138
|
+
/**
|
|
139
|
+
* Preview a swap for all swarm members without executing it.
|
|
140
|
+
* **Manager only** - requires authentication as a swarm manager.
|
|
141
|
+
*
|
|
142
|
+
* Use this to see expected amounts before executing a swap.
|
|
143
|
+
*
|
|
144
|
+
* @param swarmId - The swarm ID
|
|
145
|
+
* @param params - Swap parameters
|
|
146
|
+
* @param params.sellToken - Token address to sell (use NATIVE_ETH_ADDRESS for ETH)
|
|
147
|
+
* @param params.buyToken - Token address to buy
|
|
148
|
+
* @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
|
|
149
|
+
* @param params.slippagePercentage - Slippage tolerance (default 1%)
|
|
150
|
+
* @returns Preview with per-member amounts and totals
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* ```typescript
|
|
154
|
+
* const preview = await client.previewSwap('swarm-id', {
|
|
155
|
+
* sellToken: BASE_MAINNET_TOKENS.USDC,
|
|
156
|
+
* buyToken: BASE_MAINNET_TOKENS.WETH,
|
|
157
|
+
* sellPercentage: 50,
|
|
158
|
+
* slippagePercentage: 1,
|
|
159
|
+
* });
|
|
160
|
+
*
|
|
161
|
+
* console.log(`Total sell: ${preview.totalSellAmount}`);
|
|
162
|
+
* console.log(`Expected buy: ${preview.totalBuyAmount}`);
|
|
163
|
+
* console.log(`Success: ${preview.successCount}, Errors: ${preview.errorCount}`);
|
|
164
|
+
* ```
|
|
165
|
+
*/
|
|
166
|
+
async previewSwap(swarmId, params) {
|
|
167
|
+
return this.request("POST", `/api/swarms/${swarmId}/swap/preview`, {
|
|
168
|
+
sellToken: params.sellToken,
|
|
169
|
+
buyToken: params.buyToken,
|
|
170
|
+
sellPercentage: params.sellPercentage ?? 100,
|
|
171
|
+
slippagePercentage: params.slippagePercentage ?? 1
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Execute a swap for all swarm members.
|
|
176
|
+
* **Manager only** - requires authentication as a swarm manager.
|
|
177
|
+
*
|
|
178
|
+
* The swap is executed asynchronously. Use `waitForTransaction` to wait for completion.
|
|
179
|
+
*
|
|
180
|
+
* A platform fee (default 0.5%) is deducted from the buy token amount.
|
|
181
|
+
*
|
|
182
|
+
* @param swarmId - The swarm ID
|
|
183
|
+
* @param params - Swap parameters
|
|
184
|
+
* @param params.sellToken - Token address to sell
|
|
185
|
+
* @param params.buyToken - Token address to buy
|
|
186
|
+
* @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
|
|
187
|
+
* @param params.slippagePercentage - Slippage tolerance (default 1%)
|
|
188
|
+
* @returns Transaction ID and status
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```typescript
|
|
192
|
+
* // Execute swap
|
|
193
|
+
* const result = await client.executeSwap('swarm-id', {
|
|
194
|
+
* sellToken: BASE_MAINNET_TOKENS.USDC,
|
|
195
|
+
* buyToken: BASE_MAINNET_TOKENS.WETH,
|
|
196
|
+
* sellPercentage: 50,
|
|
197
|
+
* });
|
|
198
|
+
*
|
|
199
|
+
* console.log(`Transaction started: ${result.transactionId}`);
|
|
200
|
+
*
|
|
201
|
+
* // Wait for completion
|
|
202
|
+
* const tx = await client.waitForTransaction(result.transactionId, {
|
|
203
|
+
* onPoll: (t) => console.log(`Status: ${t.status}`),
|
|
204
|
+
* });
|
|
205
|
+
*
|
|
206
|
+
* console.log(`Transaction ${tx.status}`);
|
|
207
|
+
* ```
|
|
208
|
+
*/
|
|
209
|
+
async executeSwap(swarmId, params) {
|
|
210
|
+
return this.request("POST", `/api/swarms/${swarmId}/swap/execute`, {
|
|
211
|
+
sellToken: params.sellToken,
|
|
212
|
+
buyToken: params.buyToken,
|
|
213
|
+
sellPercentage: params.sellPercentage ?? 100,
|
|
214
|
+
slippagePercentage: params.slippagePercentage ?? 1
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
// ===========================================================================
|
|
218
|
+
// Transactions
|
|
219
|
+
// ===========================================================================
|
|
220
|
+
/**
|
|
221
|
+
* Execute a raw transaction template for all swarm members.
|
|
222
|
+
* **Manager only** - requires authentication as a swarm manager.
|
|
223
|
+
*
|
|
224
|
+
* This is an advanced method for custom transactions. For swaps, prefer `executeSwap`.
|
|
225
|
+
*
|
|
226
|
+
* @param swarmId - The swarm ID
|
|
227
|
+
* @param template - Transaction template (ABI mode or raw calldata mode)
|
|
228
|
+
* @returns Transaction ID and status
|
|
229
|
+
*
|
|
230
|
+
* @example
|
|
231
|
+
* ```typescript
|
|
232
|
+
* // ABI mode example - transfer tokens
|
|
233
|
+
* const result = await client.executeTransaction('swarm-id', {
|
|
234
|
+
* mode: 'abi',
|
|
235
|
+
* contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
|
|
236
|
+
* abi: [{
|
|
237
|
+
* name: 'transfer',
|
|
238
|
+
* type: 'function',
|
|
239
|
+
* inputs: [
|
|
240
|
+
* { name: 'to', type: 'address' },
|
|
241
|
+
* { name: 'amount', type: 'uint256' },
|
|
242
|
+
* ],
|
|
243
|
+
* outputs: [{ type: 'bool' }],
|
|
244
|
+
* }],
|
|
245
|
+
* functionName: 'transfer',
|
|
246
|
+
* args: ['0xRecipient', '{{percentage:tokenBalance:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913:50}}'],
|
|
247
|
+
* value: '0',
|
|
248
|
+
* });
|
|
249
|
+
* ```
|
|
250
|
+
*/
|
|
251
|
+
async executeTransaction(swarmId, template) {
|
|
252
|
+
return this.request(
|
|
253
|
+
"POST",
|
|
254
|
+
`/api/swarms/${swarmId}/transactions`,
|
|
255
|
+
template
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* List transactions for a swarm.
|
|
260
|
+
*
|
|
261
|
+
* @param swarmId - The swarm ID
|
|
262
|
+
* @returns Array of transactions
|
|
263
|
+
*/
|
|
264
|
+
async listTransactions(swarmId) {
|
|
265
|
+
return this.request("GET", `/api/swarms/${swarmId}/transactions`);
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Get details of a specific transaction, including per-member status.
|
|
269
|
+
*
|
|
270
|
+
* @param transactionId - The transaction ID
|
|
271
|
+
* @returns Transaction details with targets
|
|
272
|
+
*/
|
|
273
|
+
async getTransaction(transactionId) {
|
|
274
|
+
return this.request("GET", `/api/transactions/${transactionId}`);
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Wait for a transaction to complete.
|
|
278
|
+
*
|
|
279
|
+
* Polls the transaction status until it reaches COMPLETED or FAILED,
|
|
280
|
+
* or until the timeout is reached.
|
|
281
|
+
*
|
|
282
|
+
* @param transactionId - The transaction ID
|
|
283
|
+
* @param options - Wait options
|
|
284
|
+
* @param options.timeoutMs - Maximum wait time (default 5 minutes)
|
|
285
|
+
* @param options.pollIntervalMs - Polling interval (default 3 seconds)
|
|
286
|
+
* @param options.onPoll - Callback called on each poll
|
|
287
|
+
* @returns The completed transaction
|
|
288
|
+
* @throws {SwarmVaultError} If timeout is reached or transaction fails
|
|
289
|
+
*
|
|
290
|
+
* @example
|
|
291
|
+
* ```typescript
|
|
292
|
+
* const tx = await client.waitForTransaction(transactionId, {
|
|
293
|
+
* timeoutMs: 60000, // 1 minute
|
|
294
|
+
* pollIntervalMs: 2000, // 2 seconds
|
|
295
|
+
* onPoll: (t) => {
|
|
296
|
+
* const confirmed = t.targets?.filter(t => t.status === 'CONFIRMED').length ?? 0;
|
|
297
|
+
* const total = t.targets?.length ?? 0;
|
|
298
|
+
* console.log(`Progress: ${confirmed}/${total}`);
|
|
299
|
+
* },
|
|
300
|
+
* });
|
|
301
|
+
* ```
|
|
302
|
+
*/
|
|
303
|
+
async waitForTransaction(transactionId, options = {}) {
|
|
304
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
305
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
306
|
+
const startTime = Date.now();
|
|
307
|
+
while (true) {
|
|
308
|
+
const transaction = await this.getTransaction(transactionId);
|
|
309
|
+
if (options.onPoll) {
|
|
310
|
+
options.onPoll(transaction);
|
|
311
|
+
}
|
|
312
|
+
if (transaction.status === "COMPLETED") {
|
|
313
|
+
return transaction;
|
|
314
|
+
}
|
|
315
|
+
if (transaction.status === "FAILED") {
|
|
316
|
+
throw new SwarmVaultError(`Transaction failed: ${transactionId}`, {
|
|
317
|
+
errorCode: "TX_FAILED",
|
|
318
|
+
details: transaction.targets?.filter((t) => t.error)
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
if (Date.now() - startTime > timeoutMs) {
|
|
322
|
+
throw new SwarmVaultError(
|
|
323
|
+
`Transaction timeout: ${transactionId} did not complete within ${timeoutMs}ms`,
|
|
324
|
+
{
|
|
325
|
+
errorCode: "TX_TIMEOUT",
|
|
326
|
+
details: { lastStatus: transaction.status }
|
|
327
|
+
}
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
await this.sleep(pollIntervalMs);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
// ===========================================================================
|
|
334
|
+
// Private Methods
|
|
335
|
+
// ===========================================================================
|
|
336
|
+
async request(method, path, body) {
|
|
337
|
+
const url = `${this.baseUrl}${path}`;
|
|
338
|
+
const headers = {
|
|
339
|
+
"Content-Type": "application/json"
|
|
340
|
+
};
|
|
341
|
+
if (this.apiKey) {
|
|
342
|
+
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
|
343
|
+
} else if (this.jwt) {
|
|
344
|
+
headers["Authorization"] = `Bearer ${this.jwt}`;
|
|
345
|
+
}
|
|
346
|
+
const response = await this.fetchFn(url, {
|
|
347
|
+
method,
|
|
348
|
+
headers,
|
|
349
|
+
body: body ? JSON.stringify(body) : void 0
|
|
350
|
+
});
|
|
351
|
+
const data = await response.json();
|
|
352
|
+
if (!response.ok || !data.success) {
|
|
353
|
+
throw new SwarmVaultError(data.error || `Request failed with status ${response.status}`, {
|
|
354
|
+
errorCode: data.errorCode,
|
|
355
|
+
statusCode: response.status,
|
|
356
|
+
details: data.details
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return data.data;
|
|
360
|
+
}
|
|
361
|
+
sleep(ms) {
|
|
362
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
exports.BASE_MAINNET_TOKENS = BASE_MAINNET_TOKENS;
|
|
367
|
+
exports.BASE_SEPOLIA_TOKENS = BASE_SEPOLIA_TOKENS;
|
|
368
|
+
exports.NATIVE_ETH_ADDRESS = NATIVE_ETH_ADDRESS;
|
|
369
|
+
exports.SwarmVaultClient = SwarmVaultClient;
|
|
370
|
+
exports.SwarmVaultError = SwarmVaultError;
|
|
371
|
+
//# sourceMappingURL=index.cjs.map
|
|
372
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/client.ts"],"names":[],"mappings":";;;AA4NO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACzB,SAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EAEhB,WAAA,CACE,SACA,OAAA,EAKA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,YAAY,OAAA,E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AEA,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,OAAA,CAAQ,GAAA,EAAK;AAAA,MACvC,MAAA;AAAA,MACA,OAAA;AAAA,MACA,IAAA,EAAM,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA,GAAI;AAAA,KACrC,CAAA;AAED,IAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,EAAK;AAElC,IAAA,IAAI,CAAC,QAAA,CAAS,EAAA,IAAM,CAAC,KAAK,OAAA,EAAS;AACjC,MAAA,MAAM,IAAI,eAAA,CAAgB,IAAA,CAAK,SAAS,CAAA,2BAAA,EAA8B,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI;AAAA,QACvF,WAAW,IAAA,CAAK,SAAA;AAAA,QAChB,YAAY,QAAA,CAAS,MAAA;AAAA,QACrB,SAAS,IAAA,CAAK;AAAA,OACf,CAAA;AAAA,IACH;AAEA,IAAA,OAAO,IAAA,CAAK,IAAA;AAAA,EACd;AAAA,EAEQ,MAAM,EAAA,EAA2B;AACvC,IAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,OAAA,EAAS,EAAE,CAAC,CAAA;AAAA,EACzD;AACF","file":"index.cjs","sourcesContent":["/**\n * Swarm Vault SDK Types\n */\n\n// ============================================================================\n// Core Types\n// ============================================================================\n\nexport interface User {\n id: string;\n walletAddress: string;\n twitterId: string | null;\n twitterUsername: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface Swarm {\n id: string;\n name: string;\n description: string;\n createdAt: string;\n updatedAt: string;\n manager?: {\n id: string;\n walletAddress: string;\n twitterUsername: string | null;\n };\n memberCount?: number;\n isManager?: boolean;\n}\n\nexport interface SwarmMember {\n id: string;\n swarmId: string;\n userId: string;\n agentWalletAddress: string;\n status: \"ACTIVE\" | \"LEFT\";\n joinedAt: string;\n user?: {\n id: string;\n walletAddress: string;\n };\n}\n\n// ============================================================================\n// Transaction Types\n// ============================================================================\n\nexport type TransactionStatus = \"PENDING\" | \"PROCESSING\" | \"COMPLETED\" | \"FAILED\";\nexport type TransactionTargetStatus = \"PENDING\" | \"SUBMITTED\" | \"CONFIRMED\" | \"FAILED\";\n\nexport interface Transaction {\n id: string;\n swarmId: string;\n status: TransactionStatus;\n template: TransactionTemplate;\n createdAt: string;\n updatedAt: string;\n targets?: TransactionTarget[];\n}\n\nexport interface TransactionTarget {\n id: string;\n transactionId: string;\n membershipId: string;\n userOpHash: string | null;\n txHash: string | null;\n status: TransactionTargetStatus;\n error: string | null;\n createdAt: string;\n updatedAt: string;\n membership?: {\n agentWalletAddress: string;\n user?: {\n walletAddress: string;\n };\n };\n}\n\nexport interface ABITransactionTemplate {\n mode: \"abi\";\n contractAddress: string;\n abi: unknown[];\n functionName: string;\n args: unknown[];\n value: string;\n}\n\nexport interface RawTransactionTemplate {\n mode: \"raw\";\n contractAddress: string;\n data: string;\n value: string;\n}\n\nexport type TransactionTemplate = ABITransactionTemplate | RawTransactionTemplate;\n\n// ============================================================================\n// Swap Types\n// ============================================================================\n\nexport interface SwapPreviewParams {\n /** Token address to sell (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native ETH) */\n sellToken: string;\n /** Token address to buy */\n buyToken: string;\n /** Percentage of token balance to sell (1-100, default 100) */\n sellPercentage?: number;\n /** Slippage tolerance percentage (default 1) */\n slippagePercentage?: number;\n}\n\nexport interface SwapExecuteParams extends SwapPreviewParams {}\n\nexport interface SwapMemberPreview {\n membershipId: string;\n userId: string;\n userWalletAddress: string;\n agentWalletAddress: string;\n sellAmount: string;\n buyAmount: string;\n feeAmount?: string;\n estimatedPriceImpact?: number;\n sources?: string[];\n error?: string;\n}\n\nexport interface SwapFeeInfo {\n bps: number;\n percentage: string;\n recipientAddress: string;\n}\n\nexport interface SwapPreviewResult {\n sellToken: string;\n buyToken: string;\n sellPercentage: number;\n slippagePercentage: number;\n members: SwapMemberPreview[];\n totalSellAmount: string;\n totalBuyAmount: string;\n totalFeeAmount?: string;\n successCount: number;\n errorCount: number;\n fee: SwapFeeInfo | null;\n}\n\nexport interface SwapExecuteResult {\n transactionId: string;\n status: \"PENDING\";\n memberCount: number;\n message: string;\n fee: SwapFeeInfo | null;\n}\n\n// ============================================================================\n// Holdings Types\n// ============================================================================\n\nexport interface TokenInfo {\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n logoUrl?: string;\n}\n\nexport interface TokenHolding extends TokenInfo {\n totalBalance: string;\n holderCount: number;\n}\n\nexport interface SwarmHoldings {\n ethBalance: string;\n tokens: TokenHolding[];\n memberCount: number;\n commonTokens: TokenInfo[];\n}\n\n// ============================================================================\n// API Response Types\n// ============================================================================\n\nexport interface ApiResponse<T> {\n success: boolean;\n data?: T;\n error?: string;\n errorCode?: string;\n details?: unknown;\n}\n\n// ============================================================================\n// Client Options\n// ============================================================================\n\nexport interface SwarmVaultClientOptions {\n /** Base URL of the Swarm Vault API (default: https://api.swarmvault.xyz) */\n baseUrl?: string;\n /** API key for authentication (starts with 'svk_') */\n apiKey?: string;\n /** JWT token for authentication (alternative to API key) */\n jwt?: string;\n /** Custom fetch function (for testing or custom implementations) */\n fetch?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n}\n\nexport interface WaitForTransactionOptions {\n /** Maximum time to wait in milliseconds (default: 300000 = 5 minutes) */\n timeoutMs?: number;\n /** Polling interval in milliseconds (default: 3000 = 3 seconds) */\n pollIntervalMs?: number;\n /** Callback called on each poll with current status */\n onPoll?: (transaction: Transaction) => void;\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\nexport class SwarmVaultError extends Error {\n public readonly errorCode?: string;\n public readonly statusCode?: number;\n public readonly details?: unknown;\n\n constructor(\n message: string,\n options?: {\n errorCode?: string;\n statusCode?: number;\n details?: unknown;\n }\n ) {\n super(message);\n this.name = \"SwarmVaultError\";\n this.errorCode = options?.errorCode;\n this.statusCode = options?.statusCode;\n this.details = options?.details;\n }\n}\n\n// ============================================================================\n// Common Token Addresses\n// ============================================================================\n\n/** Native ETH address used in swap APIs */\nexport const NATIVE_ETH_ADDRESS = \"0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\";\n\n/** Common token addresses on Base Mainnet */\nexport const BASE_MAINNET_TOKENS = {\n ETH: NATIVE_ETH_ADDRESS,\n WETH: \"0x4200000000000000000000000000000000000006\",\n USDC: \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n DAI: \"0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb\",\n USDbC: \"0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA\",\n cbETH: \"0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22\",\n} as const;\n\n/** Common token addresses on Base Sepolia (testnet) */\nexport const BASE_SEPOLIA_TOKENS = {\n ETH: NATIVE_ETH_ADDRESS,\n WETH: \"0x4200000000000000000000000000000000000006\",\n USDC: \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\",\n} as const;\n","/**\n * Swarm Vault SDK Client\n *\n * A TypeScript client for the Swarm Vault API, enabling managers to execute\n * swaps and transactions on behalf of their swarm members.\n *\n * @example\n * ```typescript\n * import { SwarmVaultClient } from '@swarmvault/sdk';\n *\n * const client = new SwarmVaultClient({\n * apiKey: 'svk_your_api_key_here',\n * });\n *\n * // Get swarm holdings\n * const holdings = await client.getSwarmHoldings('swarm-id');\n *\n * // Execute a swap\n * const result = await client.executeSwap('swarm-id', {\n * sellToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC\n * buyToken: '0x4200000000000000000000000000000000000006', // WETH\n * sellPercentage: 50,\n * });\n *\n * // Wait for completion\n * const tx = await client.waitForTransaction(result.transactionId);\n * ```\n */\n\nimport type {\n ApiResponse,\n Swarm,\n SwarmMember,\n SwarmHoldings,\n SwapPreviewParams,\n SwapPreviewResult,\n SwapExecuteParams,\n SwapExecuteResult,\n Transaction,\n TransactionTemplate,\n User,\n SwarmVaultClientOptions,\n WaitForTransactionOptions,\n} from \"./types.js\";\nimport { SwarmVaultError } from \"./types.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.swarmvault.xyz\";\nconst DEFAULT_TIMEOUT_MS = 300000; // 5 minutes\nconst DEFAULT_POLL_INTERVAL_MS = 3000; // 3 seconds\n\ntype FetchFn = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;\n\nexport class SwarmVaultClient {\n private baseUrl: string;\n private apiKey?: string;\n private jwt?: string;\n private fetchFn: FetchFn;\n\n /**\n * Create a new Swarm Vault client.\n *\n * @param options - Client configuration options\n * @param options.baseUrl - Base URL of the API (default: https://api.swarmvault.xyz)\n * @param options.apiKey - API key for authentication (recommended)\n * @param options.jwt - JWT token for authentication (alternative to API key)\n */\n constructor(options: SwarmVaultClientOptions = {}) {\n this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.apiKey = options.apiKey;\n this.jwt = options.jwt;\n this.fetchFn = options.fetch || (globalThis.fetch as FetchFn);\n\n if (!this.fetchFn) {\n throw new SwarmVaultError(\n \"fetch is not available. Please provide a fetch implementation or use Node.js 18+.\"\n );\n }\n }\n\n // ===========================================================================\n // Authentication\n // ===========================================================================\n\n /**\n * Set the API key for authentication.\n * API keys start with 'svk_' and can be generated in the Swarm Vault settings.\n *\n * @param apiKey - The API key\n */\n setApiKey(apiKey: string): void {\n this.apiKey = apiKey;\n this.jwt = undefined;\n }\n\n /**\n * Set the JWT token for authentication.\n * JWTs are obtained through the SIWE login flow.\n *\n * @param jwt - The JWT token\n */\n setJwt(jwt: string): void {\n this.jwt = jwt;\n this.apiKey = undefined;\n }\n\n /**\n * Get the currently authenticated user.\n *\n * @returns The authenticated user\n * @throws {SwarmVaultError} If not authenticated or request fails\n */\n async getMe(): Promise<User> {\n return this.request<User>(\"GET\", \"/api/auth/me\");\n }\n\n // ===========================================================================\n // Swarms\n // ===========================================================================\n\n /**\n * List all swarms. Returns public swarms for unauthenticated requests,\n * or includes management status for authenticated requests.\n *\n * @returns Array of swarms\n */\n async listSwarms(): Promise<Swarm[]> {\n return this.request<Swarm[]>(\"GET\", \"/api/swarms\");\n }\n\n /**\n * Get details of a specific swarm.\n *\n * @param swarmId - The swarm ID\n * @returns Swarm details\n * @throws {SwarmVaultError} If swarm not found\n */\n async getSwarm(swarmId: string): Promise<Swarm> {\n return this.request<Swarm>(\"GET\", `/api/swarms/${swarmId}`);\n }\n\n /**\n * Get members of a swarm.\n * **Manager only** - requires authentication as a swarm manager.\n *\n * @param swarmId - The swarm ID\n * @returns Array of swarm members\n * @throws {SwarmVaultError} If not authorized or swarm not found\n */\n async getSwarmMembers(swarmId: string): Promise<SwarmMember[]> {\n return this.request<SwarmMember[]>(\"GET\", `/api/swarms/${swarmId}/members`);\n }\n\n /**\n * Get aggregate token holdings across all swarm members.\n * **Manager only** - requires authentication as a swarm manager.\n *\n * @param swarmId - The swarm ID\n * @returns Aggregated holdings with ETH balance, token balances, and common tokens\n * @throws {SwarmVaultError} If not authorized or swarm not found\n */\n async getSwarmHoldings(swarmId: string): Promise<SwarmHoldings> {\n return this.request<SwarmHoldings>(\"GET\", `/api/swarms/${swarmId}/holdings`);\n }\n\n // ===========================================================================\n // Swaps\n // ===========================================================================\n\n /**\n * Preview a swap for all swarm members without executing it.\n * **Manager only** - requires authentication as a swarm manager.\n *\n * Use this to see expected amounts before executing a swap.\n *\n * @param swarmId - The swarm ID\n * @param params - Swap parameters\n * @param params.sellToken - Token address to sell (use NATIVE_ETH_ADDRESS for ETH)\n * @param params.buyToken - Token address to buy\n * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)\n * @param params.slippagePercentage - Slippage tolerance (default 1%)\n * @returns Preview with per-member amounts and totals\n *\n * @example\n * ```typescript\n * const preview = await client.previewSwap('swarm-id', {\n * sellToken: BASE_MAINNET_TOKENS.USDC,\n * buyToken: BASE_MAINNET_TOKENS.WETH,\n * sellPercentage: 50,\n * slippagePercentage: 1,\n * });\n *\n * console.log(`Total sell: ${preview.totalSellAmount}`);\n * console.log(`Expected buy: ${preview.totalBuyAmount}`);\n * console.log(`Success: ${preview.successCount}, Errors: ${preview.errorCount}`);\n * ```\n */\n async previewSwap(swarmId: string, params: SwapPreviewParams): Promise<SwapPreviewResult> {\n return this.request<SwapPreviewResult>(\"POST\", `/api/swarms/${swarmId}/swap/preview`, {\n sellToken: params.sellToken,\n buyToken: params.buyToken,\n sellPercentage: params.sellPercentage ?? 100,\n slippagePercentage: params.slippagePercentage ?? 1,\n });\n }\n\n /**\n * Execute a swap for all swarm members.\n * **Manager only** - requires authentication as a swarm manager.\n *\n * The swap is executed asynchronously. Use `waitForTransaction` to wait for completion.\n *\n * A platform fee (default 0.5%) is deducted from the buy token amount.\n *\n * @param swarmId - The swarm ID\n * @param params - Swap parameters\n * @param params.sellToken - Token address to sell\n * @param params.buyToken - Token address to buy\n * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)\n * @param params.slippagePercentage - Slippage tolerance (default 1%)\n * @returns Transaction ID and status\n *\n * @example\n * ```typescript\n * // Execute swap\n * const result = await client.executeSwap('swarm-id', {\n * sellToken: BASE_MAINNET_TOKENS.USDC,\n * buyToken: BASE_MAINNET_TOKENS.WETH,\n * sellPercentage: 50,\n * });\n *\n * console.log(`Transaction started: ${result.transactionId}`);\n *\n * // Wait for completion\n * const tx = await client.waitForTransaction(result.transactionId, {\n * onPoll: (t) => console.log(`Status: ${t.status}`),\n * });\n *\n * console.log(`Transaction ${tx.status}`);\n * ```\n */\n async executeSwap(swarmId: string, params: SwapExecuteParams): Promise<SwapExecuteResult> {\n return this.request<SwapExecuteResult>(\"POST\", `/api/swarms/${swarmId}/swap/execute`, {\n sellToken: params.sellToken,\n buyToken: params.buyToken,\n sellPercentage: params.sellPercentage ?? 100,\n slippagePercentage: params.slippagePercentage ?? 1,\n });\n }\n\n // ===========================================================================\n // Transactions\n // ===========================================================================\n\n /**\n * Execute a raw transaction template for all swarm members.\n * **Manager only** - requires authentication as a swarm manager.\n *\n * This is an advanced method for custom transactions. For swaps, prefer `executeSwap`.\n *\n * @param swarmId - The swarm ID\n * @param template - Transaction template (ABI mode or raw calldata mode)\n * @returns Transaction ID and status\n *\n * @example\n * ```typescript\n * // ABI mode example - transfer tokens\n * const result = await client.executeTransaction('swarm-id', {\n * mode: 'abi',\n * contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n * abi: [{\n * name: 'transfer',\n * type: 'function',\n * inputs: [\n * { name: 'to', type: 'address' },\n * { name: 'amount', type: 'uint256' },\n * ],\n * outputs: [{ type: 'bool' }],\n * }],\n * functionName: 'transfer',\n * args: ['0xRecipient', '{{percentage:tokenBalance:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913:50}}'],\n * value: '0',\n * });\n * ```\n */\n async executeTransaction(\n swarmId: string,\n template: TransactionTemplate\n ): Promise<{ transactionId: string; status: string }> {\n return this.request<{ transactionId: string; status: string }>(\n \"POST\",\n `/api/swarms/${swarmId}/transactions`,\n template\n );\n }\n\n /**\n * List transactions for a swarm.\n *\n * @param swarmId - The swarm ID\n * @returns Array of transactions\n */\n async listTransactions(swarmId: string): Promise<Transaction[]> {\n return this.request<Transaction[]>(\"GET\", `/api/swarms/${swarmId}/transactions`);\n }\n\n /**\n * Get details of a specific transaction, including per-member status.\n *\n * @param transactionId - The transaction ID\n * @returns Transaction details with targets\n */\n async getTransaction(transactionId: string): Promise<Transaction> {\n return this.request<Transaction>(\"GET\", `/api/transactions/${transactionId}`);\n }\n\n /**\n * Wait for a transaction to complete.\n *\n * Polls the transaction status until it reaches COMPLETED or FAILED,\n * or until the timeout is reached.\n *\n * @param transactionId - The transaction ID\n * @param options - Wait options\n * @param options.timeoutMs - Maximum wait time (default 5 minutes)\n * @param options.pollIntervalMs - Polling interval (default 3 seconds)\n * @param options.onPoll - Callback called on each poll\n * @returns The completed transaction\n * @throws {SwarmVaultError} If timeout is reached or transaction fails\n *\n * @example\n * ```typescript\n * const tx = await client.waitForTransaction(transactionId, {\n * timeoutMs: 60000, // 1 minute\n * pollIntervalMs: 2000, // 2 seconds\n * onPoll: (t) => {\n * const confirmed = t.targets?.filter(t => t.status === 'CONFIRMED').length ?? 0;\n * const total = t.targets?.length ?? 0;\n * console.log(`Progress: ${confirmed}/${total}`);\n * },\n * });\n * ```\n */\n async waitForTransaction(\n transactionId: string,\n options: WaitForTransactionOptions = {}\n ): Promise<Transaction> {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const startTime = Date.now();\n\n while (true) {\n const transaction = await this.getTransaction(transactionId);\n\n if (options.onPoll) {\n options.onPoll(transaction);\n }\n\n if (transaction.status === \"COMPLETED\") {\n return transaction;\n }\n\n if (transaction.status === \"FAILED\") {\n throw new SwarmVaultError(`Transaction failed: ${transactionId}`, {\n errorCode: \"TX_FAILED\",\n details: transaction.targets?.filter((t) => t.error),\n });\n }\n\n if (Date.now() - startTime > timeoutMs) {\n throw new SwarmVaultError(\n `Transaction timeout: ${transactionId} did not complete within ${timeoutMs}ms`,\n {\n errorCode: \"TX_TIMEOUT\",\n details: { lastStatus: transaction.status },\n }\n );\n }\n\n await this.sleep(pollIntervalMs);\n }\n }\n\n // ===========================================================================\n // Private Methods\n // ===========================================================================\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n // Add authorization header\n if (this.apiKey) {\n headers[\"Authorization\"] = `Bearer ${this.apiKey}`;\n } else if (this.jwt) {\n headers[\"Authorization\"] = `Bearer ${this.jwt}`;\n }\n\n const response = await this.fetchFn(url, {\n method,\n headers,\n body: body ? JSON.stringify(body) : undefined,\n });\n\n const data = (await response.json()) as ApiResponse<T>;\n\n if (!response.ok || !data.success) {\n throw new SwarmVaultError(data.error || `Request failed with status ${response.status}`, {\n errorCode: data.errorCode,\n statusCode: response.status,\n details: data.details,\n });\n }\n\n return data.data as T;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n"]}
|