@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/dist/index.js ADDED
@@ -0,0 +1,366 @@
1
+ // src/types.ts
2
+ var SwarmVaultError = class extends Error {
3
+ errorCode;
4
+ statusCode;
5
+ details;
6
+ constructor(message, options) {
7
+ super(message);
8
+ this.name = "SwarmVaultError";
9
+ this.errorCode = options?.errorCode;
10
+ this.statusCode = options?.statusCode;
11
+ this.details = options?.details;
12
+ }
13
+ };
14
+ var NATIVE_ETH_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
15
+ var BASE_MAINNET_TOKENS = {
16
+ ETH: NATIVE_ETH_ADDRESS,
17
+ WETH: "0x4200000000000000000000000000000000000006",
18
+ USDC: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
19
+ DAI: "0x50c5725949A6F0c72E6C4a641F24049A917DB0Cb",
20
+ USDbC: "0xd9aAEc86B65D86f6A7B5B1b0c42FFA531710b6CA",
21
+ cbETH: "0x2Ae3F1Ec7F1F5012CFEab0185bfc7aa3cf0DEc22"
22
+ };
23
+ var BASE_SEPOLIA_TOKENS = {
24
+ ETH: NATIVE_ETH_ADDRESS,
25
+ WETH: "0x4200000000000000000000000000000000000006",
26
+ USDC: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
27
+ };
28
+
29
+ // src/client.ts
30
+ var DEFAULT_BASE_URL = "https://api.swarmvault.xyz";
31
+ var DEFAULT_TIMEOUT_MS = 3e5;
32
+ var DEFAULT_POLL_INTERVAL_MS = 3e3;
33
+ var SwarmVaultClient = class {
34
+ baseUrl;
35
+ apiKey;
36
+ jwt;
37
+ fetchFn;
38
+ /**
39
+ * Create a new Swarm Vault client.
40
+ *
41
+ * @param options - Client configuration options
42
+ * @param options.baseUrl - Base URL of the API (default: https://api.swarmvault.xyz)
43
+ * @param options.apiKey - API key for authentication (recommended)
44
+ * @param options.jwt - JWT token for authentication (alternative to API key)
45
+ */
46
+ constructor(options = {}) {
47
+ this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\/$/, "");
48
+ this.apiKey = options.apiKey;
49
+ this.jwt = options.jwt;
50
+ this.fetchFn = options.fetch || globalThis.fetch;
51
+ if (!this.fetchFn) {
52
+ throw new SwarmVaultError(
53
+ "fetch is not available. Please provide a fetch implementation or use Node.js 18+."
54
+ );
55
+ }
56
+ }
57
+ // ===========================================================================
58
+ // Authentication
59
+ // ===========================================================================
60
+ /**
61
+ * Set the API key for authentication.
62
+ * API keys start with 'svk_' and can be generated in the Swarm Vault settings.
63
+ *
64
+ * @param apiKey - The API key
65
+ */
66
+ setApiKey(apiKey) {
67
+ this.apiKey = apiKey;
68
+ this.jwt = void 0;
69
+ }
70
+ /**
71
+ * Set the JWT token for authentication.
72
+ * JWTs are obtained through the SIWE login flow.
73
+ *
74
+ * @param jwt - The JWT token
75
+ */
76
+ setJwt(jwt) {
77
+ this.jwt = jwt;
78
+ this.apiKey = void 0;
79
+ }
80
+ /**
81
+ * Get the currently authenticated user.
82
+ *
83
+ * @returns The authenticated user
84
+ * @throws {SwarmVaultError} If not authenticated or request fails
85
+ */
86
+ async getMe() {
87
+ return this.request("GET", "/api/auth/me");
88
+ }
89
+ // ===========================================================================
90
+ // Swarms
91
+ // ===========================================================================
92
+ /**
93
+ * List all swarms. Returns public swarms for unauthenticated requests,
94
+ * or includes management status for authenticated requests.
95
+ *
96
+ * @returns Array of swarms
97
+ */
98
+ async listSwarms() {
99
+ return this.request("GET", "/api/swarms");
100
+ }
101
+ /**
102
+ * Get details of a specific swarm.
103
+ *
104
+ * @param swarmId - The swarm ID
105
+ * @returns Swarm details
106
+ * @throws {SwarmVaultError} If swarm not found
107
+ */
108
+ async getSwarm(swarmId) {
109
+ return this.request("GET", `/api/swarms/${swarmId}`);
110
+ }
111
+ /**
112
+ * Get members of a swarm.
113
+ * **Manager only** - requires authentication as a swarm manager.
114
+ *
115
+ * @param swarmId - The swarm ID
116
+ * @returns Array of swarm members
117
+ * @throws {SwarmVaultError} If not authorized or swarm not found
118
+ */
119
+ async getSwarmMembers(swarmId) {
120
+ return this.request("GET", `/api/swarms/${swarmId}/members`);
121
+ }
122
+ /**
123
+ * Get aggregate token holdings across all swarm members.
124
+ * **Manager only** - requires authentication as a swarm manager.
125
+ *
126
+ * @param swarmId - The swarm ID
127
+ * @returns Aggregated holdings with ETH balance, token balances, and common tokens
128
+ * @throws {SwarmVaultError} If not authorized or swarm not found
129
+ */
130
+ async getSwarmHoldings(swarmId) {
131
+ return this.request("GET", `/api/swarms/${swarmId}/holdings`);
132
+ }
133
+ // ===========================================================================
134
+ // Swaps
135
+ // ===========================================================================
136
+ /**
137
+ * Preview a swap for all swarm members without executing it.
138
+ * **Manager only** - requires authentication as a swarm manager.
139
+ *
140
+ * Use this to see expected amounts before executing a swap.
141
+ *
142
+ * @param swarmId - The swarm ID
143
+ * @param params - Swap parameters
144
+ * @param params.sellToken - Token address to sell (use NATIVE_ETH_ADDRESS for ETH)
145
+ * @param params.buyToken - Token address to buy
146
+ * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
147
+ * @param params.slippagePercentage - Slippage tolerance (default 1%)
148
+ * @returns Preview with per-member amounts and totals
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * const preview = await client.previewSwap('swarm-id', {
153
+ * sellToken: BASE_MAINNET_TOKENS.USDC,
154
+ * buyToken: BASE_MAINNET_TOKENS.WETH,
155
+ * sellPercentage: 50,
156
+ * slippagePercentage: 1,
157
+ * });
158
+ *
159
+ * console.log(`Total sell: ${preview.totalSellAmount}`);
160
+ * console.log(`Expected buy: ${preview.totalBuyAmount}`);
161
+ * console.log(`Success: ${preview.successCount}, Errors: ${preview.errorCount}`);
162
+ * ```
163
+ */
164
+ async previewSwap(swarmId, params) {
165
+ return this.request("POST", `/api/swarms/${swarmId}/swap/preview`, {
166
+ sellToken: params.sellToken,
167
+ buyToken: params.buyToken,
168
+ sellPercentage: params.sellPercentage ?? 100,
169
+ slippagePercentage: params.slippagePercentage ?? 1
170
+ });
171
+ }
172
+ /**
173
+ * Execute a swap for all swarm members.
174
+ * **Manager only** - requires authentication as a swarm manager.
175
+ *
176
+ * The swap is executed asynchronously. Use `waitForTransaction` to wait for completion.
177
+ *
178
+ * A platform fee (default 0.5%) is deducted from the buy token amount.
179
+ *
180
+ * @param swarmId - The swarm ID
181
+ * @param params - Swap parameters
182
+ * @param params.sellToken - Token address to sell
183
+ * @param params.buyToken - Token address to buy
184
+ * @param params.sellPercentage - Percentage of balance to sell (1-100, default 100)
185
+ * @param params.slippagePercentage - Slippage tolerance (default 1%)
186
+ * @returns Transaction ID and status
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * // Execute swap
191
+ * const result = await client.executeSwap('swarm-id', {
192
+ * sellToken: BASE_MAINNET_TOKENS.USDC,
193
+ * buyToken: BASE_MAINNET_TOKENS.WETH,
194
+ * sellPercentage: 50,
195
+ * });
196
+ *
197
+ * console.log(`Transaction started: ${result.transactionId}`);
198
+ *
199
+ * // Wait for completion
200
+ * const tx = await client.waitForTransaction(result.transactionId, {
201
+ * onPoll: (t) => console.log(`Status: ${t.status}`),
202
+ * });
203
+ *
204
+ * console.log(`Transaction ${tx.status}`);
205
+ * ```
206
+ */
207
+ async executeSwap(swarmId, params) {
208
+ return this.request("POST", `/api/swarms/${swarmId}/swap/execute`, {
209
+ sellToken: params.sellToken,
210
+ buyToken: params.buyToken,
211
+ sellPercentage: params.sellPercentage ?? 100,
212
+ slippagePercentage: params.slippagePercentage ?? 1
213
+ });
214
+ }
215
+ // ===========================================================================
216
+ // Transactions
217
+ // ===========================================================================
218
+ /**
219
+ * Execute a raw transaction template for all swarm members.
220
+ * **Manager only** - requires authentication as a swarm manager.
221
+ *
222
+ * This is an advanced method for custom transactions. For swaps, prefer `executeSwap`.
223
+ *
224
+ * @param swarmId - The swarm ID
225
+ * @param template - Transaction template (ABI mode or raw calldata mode)
226
+ * @returns Transaction ID and status
227
+ *
228
+ * @example
229
+ * ```typescript
230
+ * // ABI mode example - transfer tokens
231
+ * const result = await client.executeTransaction('swarm-id', {
232
+ * mode: 'abi',
233
+ * contractAddress: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
234
+ * abi: [{
235
+ * name: 'transfer',
236
+ * type: 'function',
237
+ * inputs: [
238
+ * { name: 'to', type: 'address' },
239
+ * { name: 'amount', type: 'uint256' },
240
+ * ],
241
+ * outputs: [{ type: 'bool' }],
242
+ * }],
243
+ * functionName: 'transfer',
244
+ * args: ['0xRecipient', '{{percentage:tokenBalance:0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913:50}}'],
245
+ * value: '0',
246
+ * });
247
+ * ```
248
+ */
249
+ async executeTransaction(swarmId, template) {
250
+ return this.request(
251
+ "POST",
252
+ `/api/swarms/${swarmId}/transactions`,
253
+ template
254
+ );
255
+ }
256
+ /**
257
+ * List transactions for a swarm.
258
+ *
259
+ * @param swarmId - The swarm ID
260
+ * @returns Array of transactions
261
+ */
262
+ async listTransactions(swarmId) {
263
+ return this.request("GET", `/api/swarms/${swarmId}/transactions`);
264
+ }
265
+ /**
266
+ * Get details of a specific transaction, including per-member status.
267
+ *
268
+ * @param transactionId - The transaction ID
269
+ * @returns Transaction details with targets
270
+ */
271
+ async getTransaction(transactionId) {
272
+ return this.request("GET", `/api/transactions/${transactionId}`);
273
+ }
274
+ /**
275
+ * Wait for a transaction to complete.
276
+ *
277
+ * Polls the transaction status until it reaches COMPLETED or FAILED,
278
+ * or until the timeout is reached.
279
+ *
280
+ * @param transactionId - The transaction ID
281
+ * @param options - Wait options
282
+ * @param options.timeoutMs - Maximum wait time (default 5 minutes)
283
+ * @param options.pollIntervalMs - Polling interval (default 3 seconds)
284
+ * @param options.onPoll - Callback called on each poll
285
+ * @returns The completed transaction
286
+ * @throws {SwarmVaultError} If timeout is reached or transaction fails
287
+ *
288
+ * @example
289
+ * ```typescript
290
+ * const tx = await client.waitForTransaction(transactionId, {
291
+ * timeoutMs: 60000, // 1 minute
292
+ * pollIntervalMs: 2000, // 2 seconds
293
+ * onPoll: (t) => {
294
+ * const confirmed = t.targets?.filter(t => t.status === 'CONFIRMED').length ?? 0;
295
+ * const total = t.targets?.length ?? 0;
296
+ * console.log(`Progress: ${confirmed}/${total}`);
297
+ * },
298
+ * });
299
+ * ```
300
+ */
301
+ async waitForTransaction(transactionId, options = {}) {
302
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
303
+ const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
304
+ const startTime = Date.now();
305
+ while (true) {
306
+ const transaction = await this.getTransaction(transactionId);
307
+ if (options.onPoll) {
308
+ options.onPoll(transaction);
309
+ }
310
+ if (transaction.status === "COMPLETED") {
311
+ return transaction;
312
+ }
313
+ if (transaction.status === "FAILED") {
314
+ throw new SwarmVaultError(`Transaction failed: ${transactionId}`, {
315
+ errorCode: "TX_FAILED",
316
+ details: transaction.targets?.filter((t) => t.error)
317
+ });
318
+ }
319
+ if (Date.now() - startTime > timeoutMs) {
320
+ throw new SwarmVaultError(
321
+ `Transaction timeout: ${transactionId} did not complete within ${timeoutMs}ms`,
322
+ {
323
+ errorCode: "TX_TIMEOUT",
324
+ details: { lastStatus: transaction.status }
325
+ }
326
+ );
327
+ }
328
+ await this.sleep(pollIntervalMs);
329
+ }
330
+ }
331
+ // ===========================================================================
332
+ // Private Methods
333
+ // ===========================================================================
334
+ async request(method, path, body) {
335
+ const url = `${this.baseUrl}${path}`;
336
+ const headers = {
337
+ "Content-Type": "application/json"
338
+ };
339
+ if (this.apiKey) {
340
+ headers["Authorization"] = `Bearer ${this.apiKey}`;
341
+ } else if (this.jwt) {
342
+ headers["Authorization"] = `Bearer ${this.jwt}`;
343
+ }
344
+ const response = await this.fetchFn(url, {
345
+ method,
346
+ headers,
347
+ body: body ? JSON.stringify(body) : void 0
348
+ });
349
+ const data = await response.json();
350
+ if (!response.ok || !data.success) {
351
+ throw new SwarmVaultError(data.error || `Request failed with status ${response.status}`, {
352
+ errorCode: data.errorCode,
353
+ statusCode: response.status,
354
+ details: data.details
355
+ });
356
+ }
357
+ return data.data;
358
+ }
359
+ sleep(ms) {
360
+ return new Promise((resolve) => setTimeout(resolve, ms));
361
+ }
362
+ };
363
+
364
+ export { BASE_MAINNET_TOKENS, BASE_SEPOLIA_TOKENS, NATIVE_ETH_ADDRESS, SwarmVaultClient, SwarmVaultError };
365
+ //# sourceMappingURL=index.js.map
366
+ //# sourceMappingURL=index.js.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,EAAS,SAAA;AAC1B,IAAA,IAAA,CAAK,aAAa,OAAA,EAAS,UAAA;AAC3B,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AAAA,EAC1B;AACF;AAOO,IAAM,kBAAA,GAAqB;AAG3B,IAAM,mBAAA,GAAsB;AAAA,EACjC,GAAA,EAAK,kBAAA;AAAA,EACL,IAAA,EAAM,4CAAA;AAAA,EACN,IAAA,EAAM,4CAAA;AAAA,EACN,GAAA,EAAK,4CAAA;AAAA,EACL,KAAA,EAAO,4CAAA;AAAA,EACP,KAAA,EAAO;AACT;AAGO,IAAM,mBAAA,GAAsB;AAAA,EACjC,GAAA,EAAK,kBAAA;AAAA,EACL,IAAA,EAAM,4CAAA;AAAA,EACN,IAAA,EAAM;AACR;;;ACzNA,IAAM,gBAAA,GAAmB,4BAAA;AACzB,IAAM,kBAAA,GAAqB,GAAA;AAC3B,IAAM,wBA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A;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.js","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"]}
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@swarmvault/sdk",
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for Swarm Vault API - execute swaps and transactions on behalf of swarm members",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md"
24
+ ],
25
+ "keywords": [
26
+ "swarmvault",
27
+ "web3",
28
+ "defi",
29
+ "smart-wallet",
30
+ "swap",
31
+ "sdk",
32
+ "api-client"
33
+ ],
34
+ "author": "Swarm Vault",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/swarmvault/swarm-vault"
39
+ },
40
+ "devDependencies": {
41
+ "tsup": "^8.0.1",
42
+ "tsx": "^4.7.0",
43
+ "typescript": "^5.3.3"
44
+ },
45
+ "peerDependencies": {
46
+ "typescript": ">=4.7.0"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "typescript": {
50
+ "optional": true
51
+ }
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "scripts": {
57
+ "build": "tsup",
58
+ "dev": "tsup --watch",
59
+ "typecheck": "tsc --noEmit",
60
+ "clean": "rm -rf dist",
61
+ "example:holdings": "tsx examples/check-holdings.ts",
62
+ "example:swap": "tsx examples/swap-usdc-to-weth.ts"
63
+ }
64
+ }