@circuitorg/agent-sdk 1.3.10 → 1.4.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.
Files changed (3) hide show
  1. package/index.d.ts +35 -129
  2. package/index.js +1 -1
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -23,6 +23,13 @@ type SignAndSendRequest = {
23
23
  * If not provided, the suggestion never expires.
24
24
  */
25
25
  expiresAt?: string | null;
26
+ /**
27
+ * If true, the SDK polls for the transaction receipt after broadcast and
28
+ * only resolves once confirmed onchain. Returns `success: false` if the
29
+ * transaction reverts. Useful when a subsequent operation depends on this
30
+ * transaction's state change (e.g. approve before supply). Defaults to true.
31
+ */
32
+ waitForConfirmation?: boolean;
26
33
  } & ({
27
34
  network: `ethereum:${number}`;
28
35
  request: {
@@ -51,13 +58,6 @@ declare const SignAndSendResponseSchema: z$1.ZodObject<{
51
58
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
52
59
  }, z$1.core.$strip>]>>;
53
60
  error: z$1.ZodOptional<z$1.ZodString>;
54
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
55
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
56
- message: z$1.ZodOptional<z$1.ZodString>;
57
- error: z$1.ZodOptional<z$1.ZodString>;
58
- status: z$1.ZodOptional<z$1.ZodNumber>;
59
- statusText: z$1.ZodOptional<z$1.ZodString>;
60
- }, z$1.core.$strip>>;
61
61
  }, z$1.core.$strip>;
62
62
  /**
63
63
  * Standard response from signAndSend operations (TypeScript type)
@@ -132,15 +132,6 @@ type SignMessageResponse = {
132
132
  data?: SignMessageData;
133
133
  /** Error category from API (only present on failure) */
134
134
  error?: string;
135
- /** Detailed error message from API (only present on failure) */
136
- errorMessage?: string;
137
- /** Detailed error information (only present on failure) */
138
- errorDetails?: {
139
- message?: string;
140
- error?: string;
141
- status?: number;
142
- statusText?: string;
143
- };
144
135
  };
145
136
  /**
146
137
  * Asset change representing a token transfer in a confirmed transaction
@@ -177,13 +168,6 @@ type TransactionsResponse = {
177
168
  data?: AssetChange[];
178
169
  /** Error message (only present on failure) */
179
170
  error?: string;
180
- /** Detailed error message (only present on failure) */
181
- errorMessage?: string;
182
- /** Detailed error information (only present on failure) */
183
- errorDetails?: {
184
- message?: string;
185
- status?: number;
186
- };
187
171
  };
188
172
  /**
189
173
  * Current position with optional Polymarket metadata enrichment
@@ -265,13 +249,6 @@ type CurrentPositionsResponse = {
265
249
  data?: CurrentPositionsData;
266
250
  /** Error message (only present on failure) */
267
251
  error?: string;
268
- /** Detailed error message (only present on failure) */
269
- errorMessage?: string;
270
- /** Detailed error information (only present on failure) */
271
- errorDetails?: {
272
- message?: string;
273
- status?: number;
274
- };
275
252
  };
276
253
 
277
254
  /**
@@ -301,8 +278,6 @@ type AgentLog = z$1.infer<typeof AgentLogSchema>;
301
278
  interface LogResponse {
302
279
  success: boolean;
303
280
  error?: string;
304
- errorMessage?: string;
305
- errorDetails?: object;
306
281
  }
307
282
 
308
283
  /**
@@ -399,9 +374,9 @@ declare const SwidgeQuoteDataSchema: z$1.ZodObject<{
399
374
  chainId: z$1.ZodNumber;
400
375
  value: z$1.ZodString;
401
376
  data: z$1.ZodString;
402
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
403
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
404
- maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
377
+ gas: z$1.ZodOptional<z$1.ZodNumber>;
378
+ maxFeePerGas: z$1.ZodOptional<z$1.ZodString>;
379
+ maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodString>;
405
380
  }, z$1.core.$strip>, z$1.ZodObject<{
406
381
  type: z$1.ZodLiteral<"solana">;
407
382
  serializedTransaction: z$1.ZodString;
@@ -462,9 +437,9 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
462
437
  chainId: z$1.ZodNumber;
463
438
  value: z$1.ZodString;
464
439
  data: z$1.ZodString;
465
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
466
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
467
- maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
440
+ gas: z$1.ZodOptional<z$1.ZodNumber>;
441
+ maxFeePerGas: z$1.ZodOptional<z$1.ZodString>;
442
+ maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodString>;
468
443
  }, z$1.core.$strip>, z$1.ZodObject<{
469
444
  type: z$1.ZodLiteral<"solana">;
470
445
  serializedTransaction: z$1.ZodString;
@@ -475,6 +450,7 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
475
450
  signatureData: z$1.ZodString;
476
451
  }, z$1.core.$strip>], "type">>;
477
452
  expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
453
+ waitForConfirmation: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
478
454
  }, z$1.core.$strip>;
479
455
  /**
480
456
  * Quote result constants - type QUOTE_RESULT. to see available options
@@ -544,9 +520,9 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
544
520
  chainId: z$1.ZodNumber;
545
521
  value: z$1.ZodString;
546
522
  data: z$1.ZodString;
547
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
548
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
549
- maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
523
+ gas: z$1.ZodOptional<z$1.ZodNumber>;
524
+ maxFeePerGas: z$1.ZodOptional<z$1.ZodString>;
525
+ maxPriorityFeePerGas: z$1.ZodOptional<z$1.ZodString>;
550
526
  }, z$1.core.$strip>, z$1.ZodObject<{
551
527
  type: z$1.ZodLiteral<"solana">;
552
528
  serializedTransaction: z$1.ZodString;
@@ -558,13 +534,6 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
558
534
  }, z$1.core.$strip>], "type">>;
559
535
  }, z$1.core.$strip>>;
560
536
  error: z$1.ZodOptional<z$1.ZodString>;
561
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
562
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
563
- message: z$1.ZodOptional<z$1.ZodString>;
564
- error: z$1.ZodOptional<z$1.ZodString>;
565
- status: z$1.ZodOptional<z$1.ZodNumber>;
566
- statusText: z$1.ZodOptional<z$1.ZodString>;
567
- }, z$1.core.$strip>>;
568
537
  }, z$1.core.$loose>;
569
538
  /**
570
539
  * Swidge execute response wrapper with union type for manual mode support
@@ -589,13 +558,6 @@ declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
589
558
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
590
559
  }, z$1.core.$strip>]>>;
591
560
  error: z$1.ZodOptional<z$1.ZodString>;
592
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
593
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
594
- message: z$1.ZodOptional<z$1.ZodString>;
595
- error: z$1.ZodOptional<z$1.ZodString>;
596
- status: z$1.ZodOptional<z$1.ZodNumber>;
597
- statusText: z$1.ZodOptional<z$1.ZodString>;
598
- }, z$1.core.$strip>>;
599
561
  }, z$1.core.$loose>;
600
562
  type SwidgeQuoteData = z$1.infer<typeof SwidgeQuoteDataSchema>;
601
563
  type SwidgeQuoteResponse = z$1.infer<typeof SwidgeQuoteResponseWrapperSchema>;
@@ -610,9 +572,11 @@ declare const PolymarketMarketOrderRequestSchema: z$1.ZodObject<{
610
572
  SELL: "SELL";
611
573
  }>;
612
574
  expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
575
+ waitForConfirmation: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
613
576
  }, z$1.core.$strip>;
614
577
  declare const PolymarketRedeemPositionsRequestSchema: z$1.ZodObject<{
615
578
  tokenIds: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>>;
579
+ waitForConfirmation: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
616
580
  }, z$1.core.$strip>;
617
581
  /**
618
582
  * Polymarket market order response with union type for manual mode support
@@ -635,13 +599,6 @@ declare const PolymarketMarketOrderResponseSchema: z$1.ZodObject<{
635
599
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
636
600
  }, z$1.core.$strip>]>>;
637
601
  error: z$1.ZodOptional<z$1.ZodString>;
638
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
639
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
640
- message: z$1.ZodOptional<z$1.ZodString>;
641
- error: z$1.ZodOptional<z$1.ZodString>;
642
- status: z$1.ZodOptional<z$1.ZodNumber>;
643
- statusText: z$1.ZodOptional<z$1.ZodString>;
644
- }, z$1.core.$strip>>;
645
602
  }, z$1.core.$loose>;
646
603
  declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
647
604
  success: z$1.ZodBoolean;
@@ -672,13 +629,6 @@ declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
672
629
  transactionHash: z$1.ZodNullable<z$1.ZodString>;
673
630
  }, z$1.core.$strip>>>;
674
631
  error: z$1.ZodOptional<z$1.ZodString>;
675
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
676
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
677
- message: z$1.ZodOptional<z$1.ZodString>;
678
- error: z$1.ZodOptional<z$1.ZodString>;
679
- status: z$1.ZodOptional<z$1.ZodNumber>;
680
- statusText: z$1.ZodOptional<z$1.ZodString>;
681
- }, z$1.core.$strip>>;
682
632
  }, z$1.core.$loose>;
683
633
  type PolymarketMarketOrderRequest = z$1.input<typeof PolymarketMarketOrderRequestSchema>;
684
634
  type PolymarketRedeemPositionsRequest = z$1.infer<typeof PolymarketRedeemPositionsRequestSchema>;
@@ -710,6 +660,7 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
710
660
  reduceOnly: z$1.ZodOptional<z$1.ZodBoolean>;
711
661
  postOnly: z$1.ZodOptional<z$1.ZodBoolean>;
712
662
  expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
663
+ waitForConfirmation: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
713
664
  }, z$1.core.$strip>;
714
665
  /**
715
666
  * Request to transfer between spot and perp accounts on Hyperliquid
@@ -718,6 +669,7 @@ declare const HyperliquidTransferRequestSchema: z$1.ZodObject<{
718
669
  amount: z$1.ZodNumber;
719
670
  toPerp: z$1.ZodBoolean;
720
671
  expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
672
+ waitForConfirmation: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
721
673
  }, z$1.core.$strip>;
722
674
  /**
723
675
  * Hyperliquid place order response with union type for manual mode support
@@ -889,13 +841,6 @@ declare const MemorySetResponseSchema: z$1.ZodObject<{
889
841
  key: z$1.ZodString;
890
842
  }, z$1.core.$strip>>;
891
843
  error: z$1.ZodOptional<z$1.ZodString>;
892
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
893
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
894
- message: z$1.ZodOptional<z$1.ZodString>;
895
- error: z$1.ZodOptional<z$1.ZodString>;
896
- status: z$1.ZodOptional<z$1.ZodNumber>;
897
- statusText: z$1.ZodOptional<z$1.ZodString>;
898
- }, z$1.core.$strip>>;
899
844
  }, z$1.core.$loose>;
900
845
  /**
901
846
  * Memory get response wrapper
@@ -907,13 +852,6 @@ declare const MemoryGetResponseSchema: z$1.ZodObject<{
907
852
  value: z$1.ZodString;
908
853
  }, z$1.core.$strip>>;
909
854
  error: z$1.ZodOptional<z$1.ZodString>;
910
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
911
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
912
- message: z$1.ZodOptional<z$1.ZodString>;
913
- error: z$1.ZodOptional<z$1.ZodString>;
914
- status: z$1.ZodOptional<z$1.ZodNumber>;
915
- statusText: z$1.ZodOptional<z$1.ZodString>;
916
- }, z$1.core.$strip>>;
917
855
  }, z$1.core.$loose>;
918
856
  /**
919
857
  * Memory delete response wrapper
@@ -924,13 +862,6 @@ declare const MemoryDeleteResponseSchema: z$1.ZodObject<{
924
862
  key: z$1.ZodString;
925
863
  }, z$1.core.$strip>>;
926
864
  error: z$1.ZodOptional<z$1.ZodString>;
927
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
928
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
929
- message: z$1.ZodOptional<z$1.ZodString>;
930
- error: z$1.ZodOptional<z$1.ZodString>;
931
- status: z$1.ZodOptional<z$1.ZodNumber>;
932
- statusText: z$1.ZodOptional<z$1.ZodString>;
933
- }, z$1.core.$strip>>;
934
865
  }, z$1.core.$loose>;
935
866
  /**
936
867
  * Memory list response wrapper
@@ -942,13 +873,6 @@ declare const MemoryListResponseSchema: z$1.ZodObject<{
942
873
  count: z$1.ZodNumber;
943
874
  }, z$1.core.$strip>>;
944
875
  error: z$1.ZodOptional<z$1.ZodString>;
945
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
946
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
947
- message: z$1.ZodOptional<z$1.ZodString>;
948
- error: z$1.ZodOptional<z$1.ZodString>;
949
- status: z$1.ZodOptional<z$1.ZodNumber>;
950
- statusText: z$1.ZodOptional<z$1.ZodString>;
951
- }, z$1.core.$strip>>;
952
876
  }, z$1.core.$loose>;
953
877
  type MemorySetResponse = z$1.infer<typeof MemorySetResponseSchema>;
954
878
  type MemoryGetResponse = z$1.infer<typeof MemoryGetResponseSchema>;
@@ -1043,7 +967,6 @@ declare function isSuccessResponse<T>(response: {
1043
967
  success: boolean;
1044
968
  data?: T;
1045
969
  error?: string;
1046
- errorMessage?: string;
1047
970
  }): response is {
1048
971
  success: true;
1049
972
  data: T;
@@ -1133,7 +1056,6 @@ declare function isTransactionExecuted(data: unknown): data is {
1133
1056
  interface ClearSuggestionsResponse {
1134
1057
  success: boolean;
1135
1058
  error?: string;
1136
- errorMessage?: string;
1137
1059
  }
1138
1060
 
1139
1061
  /**
@@ -1221,7 +1143,7 @@ declare class AgentSdk {
1221
1143
  * - `enforceTransactionSuccess`: Enforce transaction success (optional)
1222
1144
  * - For Solana: `{ hexTransaction }`
1223
1145
  * - `hexTransaction`: Serialized `VersionedTransaction` as hex string
1224
- * @returns Promise resolving to SignAndSendResponse with success status and transaction hash or error details
1146
+ * @returns Promise resolving to SignAndSendResponse with success status and transaction hash or error
1225
1147
  * @example
1226
1148
  * ```ts
1227
1149
  * // Ethereum (Arbitrum) native transfer
@@ -1352,7 +1274,6 @@ declare class AgentSdk {
1352
1274
  * - `steps`: Transaction steps required to complete the swap
1353
1275
  * - `priceImpact`: Calculated price impact percentage
1354
1276
  * - `error` (string | undefined): Error message if quote failed
1355
- * - `errorDetails` (object | undefined): Detailed error information
1356
1277
  *
1357
1278
  * @example
1358
1279
  * ```ts
@@ -1413,7 +1334,6 @@ declare class AgentSdk {
1413
1334
  * - `out`: Destination transaction details with txs array (transaction hashes)
1414
1335
  * - Additional metadata about the swap/bridge operation
1415
1336
  * - `error` (string | undefined): Error message if execution failed
1416
- * - `errorDetails` (object | undefined): Detailed error information
1417
1337
  *
1418
1338
  * @example
1419
1339
  * ```ts
@@ -1498,7 +1418,6 @@ declare class AgentSdk {
1498
1418
  * - `data` (object | undefined): Present on success
1499
1419
  * - `key` (string): The key that was set
1500
1420
  * - `error` (string | undefined): Error message on failure
1501
- * - `errorDetails` (object | undefined): Detailed error info on failure
1502
1421
  */
1503
1422
  set: (key: string, value: string) => Promise<MemorySetResponse>;
1504
1423
  /**
@@ -1507,7 +1426,7 @@ declare class AgentSdk {
1507
1426
  * Retrieve a previously stored value. Returns an error if the key doesn't exist.
1508
1427
  *
1509
1428
  * @param key The key to retrieve
1510
- * @returns Promise with the key and its value, or error details
1429
+ * @returns Promise with the key and its value, or error
1511
1430
  *
1512
1431
  * @example
1513
1432
  * ```ts
@@ -1529,7 +1448,6 @@ declare class AgentSdk {
1529
1448
  * - `key` (string): The requested key
1530
1449
  * - `value` (string): The stored value
1531
1450
  * - `error` (string | undefined): Error message (e.g., "Key not found")
1532
- * - `errorDetails` (object | undefined): Detailed error info on failure
1533
1451
  */
1534
1452
  get: (key: string) => Promise<MemoryGetResponse>;
1535
1453
  /**
@@ -1557,7 +1475,6 @@ declare class AgentSdk {
1557
1475
  * - `data` (object | undefined): Present on success
1558
1476
  * - `key` (string): The key that was deleted
1559
1477
  * - `error` (string | undefined): Error message on failure
1560
- * - `errorDetails` (object | undefined): Detailed error info on failure
1561
1478
  */
1562
1479
  delete: (key: string) => Promise<MemoryDeleteResponse>;
1563
1480
  /**
@@ -1587,7 +1504,6 @@ declare class AgentSdk {
1587
1504
  * - `keys` (string[]): Array of all stored keys
1588
1505
  * - `count` (number): Number of keys
1589
1506
  * - `error` (string | undefined): Error message on failure
1590
- * - `errorDetails` (object | undefined): Detailed error info on failure
1591
1507
  */
1592
1508
  list: () => Promise<MemoryListResponse>;
1593
1509
  };
@@ -1631,7 +1547,6 @@ declare class AgentSdk {
1631
1547
  * - `totalPriceUsd` (string): Total order value in USD
1632
1548
  * - `txHashes` (string[]): List of transaction hashes
1633
1549
  * - `error` (string | undefined): Error message (only present on failure)
1634
- * - `errorDetails` (object | undefined): Detailed error info
1635
1550
  *
1636
1551
  * **Key Functionality**:
1637
1552
  * - Automatic approval handling for token spending
@@ -1684,8 +1599,7 @@ declare class AgentSdk {
1684
1599
  * ```json
1685
1600
  * {
1686
1601
  * "success": false,
1687
- * "error": "Could not get order",
1688
- * "errorDetails": { "message": "Invalid request", "status": 400 }
1602
+ * "error": "Could not get order"
1689
1603
  * }
1690
1604
  * ```
1691
1605
  */
@@ -1706,7 +1620,6 @@ declare class AgentSdk {
1706
1620
  * - `position` (PolymarketPosition | null): Position that was redeemed (full position details, null for unwrap collateral)
1707
1621
  * - `transactionHash` (string | null): Transaction hash (null if redemption failed)
1708
1622
  * - `error` (string | undefined): Error message (only present on failure)
1709
- * - `errorDetails` (object | undefined): Detailed error info
1710
1623
  *
1711
1624
  * **Key Functionality**:
1712
1625
  * - Automatic detection of redeemable positions
@@ -1781,8 +1694,7 @@ declare class AgentSdk {
1781
1694
  * {
1782
1695
  * "success": false,
1783
1696
  * "data": undefined,
1784
- * "error": "Could not get positions",
1785
- * "errorDetails": { "message": "No redeemable positions", "status": 404 }
1697
+ * "error": "Could not get positions"
1786
1698
  * }
1787
1699
  * ```
1788
1700
  */
@@ -2183,6 +2095,12 @@ declare class AgentSdk {
2183
2095
  liquidations: (startTime?: number) => Promise<HyperliquidLiquidationsResponse>;
2184
2096
  };
2185
2097
  };
2098
+ private static readonly EVM_PUBLIC_RPCS;
2099
+ /**
2100
+ * Poll a public RPC for a transaction receipt until confirmed.
2101
+ * Returns the receipt status: "success", "reverted", or "unknown" (timeout).
2102
+ */
2103
+ private waitForReceipt;
2186
2104
  /**
2187
2105
  * Handle EVM transaction signing and broadcasting
2188
2106
  */
@@ -2290,7 +2208,6 @@ declare class AgentSdk {
2290
2208
  * - `tokenUsdPrice` (string | null): Token price in USD at time of transaction
2291
2209
  * - `timestamp` (string): Transaction timestamp
2292
2210
  * - `error` (string | undefined): Error message on failure
2293
- * - `errorMessage` (string | undefined): Detailed error message on failure
2294
2211
  *
2295
2212
  * @returns Promise resolving to TransactionsResponse with array of asset changes
2296
2213
  *
@@ -2343,7 +2260,6 @@ declare class AgentSdk {
2343
2260
  * - Plus additional market details
2344
2261
  * - `hasPendingTxs` (boolean): Whether there are pending transactions
2345
2262
  * - `error` (string | undefined): Error message on failure
2346
- * - `errorMessage` (string | undefined): Detailed error message on failure
2347
2263
  *
2348
2264
  * @returns Promise resolving to CurrentPositionsResponse with enriched positions
2349
2265
  *
@@ -2732,8 +2648,6 @@ declare class AgentContext {
2732
2648
  * - In auto mode: SignAndSendData with txHash, transactionUrl, etc.
2733
2649
  * - In manual mode: SuggestedTransactionData with suggestionId and details
2734
2650
  * - `error` (string | undefined): Error message on failure
2735
- * - `errorMessage` (string | undefined): Detailed error message on failure
2736
- * - `errorDetails` (object | undefined): Detailed error info
2737
2651
  *
2738
2652
  * @param request - Transaction request with network and transaction details
2739
2653
  * @returns Promise resolving to SignAndSendResponse
@@ -2985,7 +2899,6 @@ declare class AgentContext {
2985
2899
  * - In auto mode: PolymarketMarketOrderData with orderInfo (orderId, side, priceUsd, txHashes)
2986
2900
  * - In manual mode: SuggestedTransactionData with suggestionId and details
2987
2901
  * - `error` (string | undefined): Error message on failure
2988
- * - `errorMessage` (string | undefined): Detailed error message on failure
2989
2902
  *
2990
2903
  * @param request - Order parameters (tokenId, size, side)
2991
2904
  * @returns Promise resolving to PolymarketMarketOrderResponse with order details or suggestion
@@ -3009,7 +2922,7 @@ declare class AgentContext {
3009
2922
  * await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
3010
2923
  * }
3011
2924
  * } else {
3012
- * await agent.log(`Order failed: ${buyResult.errorMessage}`, { error: true });
2925
+ * await agent.log(`Order failed: ${buyResult.error}`, { error: true });
3013
2926
  * }
3014
2927
  *
3015
2928
  * // SELL order - size is number of shares
@@ -3087,7 +3000,6 @@ declare class AgentContext {
3087
3000
  * - In auto mode: HyperliquidOrderInfo with orderId, symbol, side, price, size, filled, status, market, clientOrderId
3088
3001
  * - In manual mode: SuggestedTransactionData with suggestionId and details
3089
3002
  * - `error` (string | undefined): Error message (only present on failure)
3090
- * - `errorMessage` (string | undefined): Detailed error message (only present on failure)
3091
3003
  *
3092
3004
  * @param request - Order parameters
3093
3005
  * @returns Promise resolving to HyperliquidPlaceOrderResponse
@@ -3114,7 +3026,7 @@ declare class AgentContext {
3114
3026
  * await agent.log(`Status: ${result.data.status}`);
3115
3027
  * }
3116
3028
  * } else {
3117
- * await agent.log(`Order failed: ${result.errorMessage}`, { error: true });
3029
+ * await agent.log(`Order failed: ${result.error}`, { error: true });
3118
3030
  * }
3119
3031
  *
3120
3032
  * // Limit order
@@ -3520,7 +3432,6 @@ declare class AgentContext {
3520
3432
  * - In auto mode: SwidgeExecuteData with status ("success", "failure", "refund", "delayed") and transaction hashes
3521
3433
  * - In manual mode: SuggestedTransactionData with suggestionId and details
3522
3434
  * - `error` (string | undefined): Error message if execution failed
3523
- * - `errorMessage` (string | undefined): Detailed error message if execution failed
3524
3435
  *
3525
3436
  * @param quoteData - Complete quote object(s) from agent.swidge.quote()
3526
3437
  * @returns Promise resolving to SwidgeExecuteResponse with transaction status
@@ -3545,7 +3456,7 @@ declare class AgentContext {
3545
3456
  * }
3546
3457
  * }
3547
3458
  * } else {
3548
- * await agent.log(`Swap failed: ${result.errorMessage}`, { error: true });
3459
+ * await agent.log(`Swap failed: ${result.error}`, { error: true });
3549
3460
  * }
3550
3461
  * }
3551
3462
  *
@@ -3584,7 +3495,6 @@ declare class AgentContext {
3584
3495
  * - `tokenUsdPrice` (string | null): Token price in USD at time of transaction
3585
3496
  * - `timestamp` (string): Transaction timestamp
3586
3497
  * - `error` (string | undefined): Error message on failure
3587
- * - `errorMessage` (string | undefined): Detailed error message on failure
3588
3498
  *
3589
3499
  * @returns Promise resolving to TransactionsResponse with asset changes
3590
3500
  *
@@ -3625,7 +3535,6 @@ declare class AgentContext {
3625
3535
  * **Output**: `ClearSuggestionsResponse`
3626
3536
  * - `success` (boolean): Whether the operation succeeded
3627
3537
  * - `error` (string | undefined): Error message on failure
3628
- * - `errorMessage` (string | undefined): Detailed error message on failure
3629
3538
  *
3630
3539
  * @returns Promise resolving to ClearSuggestionsResponse
3631
3540
  *
@@ -3677,7 +3586,6 @@ declare class AgentContext {
3677
3586
  * - `endDate` (string): Market end date
3678
3587
  * - Plus additional market details
3679
3588
  * - `error` (string | undefined): Error message on failure
3680
- * - `errorMessage` (string | undefined): Detailed error message on failure
3681
3589
  *
3682
3590
  * @returns Promise resolving to CurrentPositionsResponse with enriched positions
3683
3591
  *
@@ -3791,7 +3699,6 @@ interface AgentConfig {
3791
3699
  *
3792
3700
  * Exposes the following endpoints:
3793
3701
  * - `POST /run` — required, calls your execution function
3794
- * - `POST /execute` — backward compatibility, maps to run function
3795
3702
  * - `POST /unwind` — optional, uses provided or default unwind function
3796
3703
  * - `GET /health` — always available, uses default health check
3797
3704
  */
@@ -3836,14 +3743,13 @@ declare class Agent {
3836
3743
  */
3837
3744
  private updateJobStatus;
3838
3745
  private setupRoutes;
3839
- private getPortFromPackageJson;
3840
3746
  /**
3841
3747
  * Start a local HTTP server for development and testing.
3842
3748
  *
3843
3749
  * This method is used for local development and testing with the Circuit CLI.
3844
3750
  * For Lambda deployment, use `getExport()` instead.
3845
3751
  *
3846
- * @param port - Optional port number (defaults to 3000 or AGENT_PORT env var)
3752
+ * @param port - Optional port number (defaults to AGENT_PORT env var or 3000)
3847
3753
  */
3848
3754
  run(port?: number): Promise<void>;
3849
3755
  /** Get the handler export for Lambda environments. */
package/index.js CHANGED
@@ -1 +1 @@
1
- import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCircuitEnvironment(){return!("undefined"==typeof process||!process.env||"circuit"!==process.env.CIRCUIT_ENVIRONMENT&&void 0===process.env.AWS_LAMBDA_FUNCTION_NAME&&void 0===process.env.LAMBDA_TASK_ROOT&&void 0===process.env.AWS_EXECUTION_ENV)}getCircuitDevMode(){if("undefined"!=typeof process&&process.env)return process.env.CIRCUIT_DEV_MODE}constructor(r){this.config=r;const e=this.getCircuitDevMode(),t=this.isCircuitEnvironment();let s,o;"local"===e?(s="http://localhost:4001",o="Dev Local"):t?(s="http://transaction-service.agent.internal",o="Circuit (internal)"):(s="https://agents.circuit.org",o="Local (public)"),this.baseUrl=r.baseUrl||s,this.authorizationHeader=r.authorizationHeader}getAgentSlug(){if("undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG)return process.env.CIRCUIT_AGENT_SLUG}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCircuitEnvironment())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return"undefined"!=typeof process&&process.env?.CIRCUIT_DEV_API_KEY&&(r["X-API-Key"]=process.env.CIRCUIT_DEV_API_KEY),r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json","User-Agent":"circuit-agent-sdk/1.0",Accept:"*/*",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${r}`,o=9e5,n=new AbortController,a=setTimeout(()=>n.abort(),o),i={...e,headers:t,signal:n.signal};try{const r=await fetch(s,i);if(clearTimeout(a),!r.ok){const e=await r.text();let t={};try{t=JSON.parse(e)}catch{t={error:e}}const s=t.error||`HTTP ${r.status}: ${r.statusText}`,o=new Error(s);throw o.error=t.error,o.errorMessage=t.error,o.errorDetails=t,o.statusCode=r.status,o}return await r.json()}catch(e){if(clearTimeout(a),e instanceof Error){if("AbortError"===e.name||e.message.includes("aborted")){const e=new Error(`Request timeout after 900s to ${s}`);throw e.error="Request Timeout",e.errorMessage=`Request to ${s} timed out after 900 seconds`,e.errorDetails={url:s,endpoint:r,timeout:o,baseUrl:this.baseUrl},e}if(e.message.includes("fetch failed")||e.message.includes("ECONNREFUSED")||e.message.includes("ENOTFOUND")||e.message.includes("getaddrinfo")||e.message.includes("network")){const t=new Error(`Network error: ${e.message}. URL: ${s}`);throw t.error="Network Error",t.errorMessage=`Failed to connect to ${s}: ${e.message}`,t.errorDetails={url:s,endpoint:r,baseUrl:this.baseUrl,originalError:e.message,isCircuitEnvironment:this.isCircuitEnvironment()},t}}throw e}}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var n=class{client;config;constructor(r){this.config=r,this.client=new e(r)}setBaseUrl(r){this.config.baseUrl=r,this.client=new e(this.config)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message,expiresAt:r.expiresAt??null})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message,expiresAt:r.expiresAt??null});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=(await this.client.post("/v1/transactions/evm",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/evm/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=(await this.client.post("/v1/transactions/solana",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/solana/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return await this.client.post("/v1/swap/quote",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{return await this.client.post("/v1/swap/execute",r)}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},n=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{const e=await this.client.post("/v1/platforms/polymarket/market-order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{const e=await this.client.post("/v1/platforms/hyperliquid/order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return await this.client.post(`/v1/memory/${r}`,{value:e})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return await this.client.get(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return await this.client.delete(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async clearSuggestedTransactions(){try{return await this.client.delete("/v1/sessions/suggestions")}catch(r){const e=r.error,t=r.errorMessage,s=r instanceof Error?r.message:"Failed to clear suggested transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||s}}}};import{existsSync as a,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;executionMode;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.executionMode=r.executionMode??"auto",this.t=new n({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}setBaseUrl(r){this.t.setBaseUrl(r)}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,n;const a=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,a,2),n=JSON.stringify(r,a)):(o=String(r),n=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{return await this.t._sendLog([{type:i,message:n}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async clearSuggestedTransactions(){return this.t.clearSuggestedTransactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),g=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p),unwindPositions:h.array(p).optional(),executionMode:h.enum(["auto","manual"]).default("auto")}),m=(h.object({status:h.string()}),class{app;runFunction;unwindFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.unwindFunction=r.unwindFunction,this.app.use("*",d()),this.setupRoutes()}defaultUnwindFunction=async(r,e)=>{await r.log(`Unwind requested for session ${r.sessionId} (positions=${e.length}), but no unwindFunction was provided`)};async executeWithJobTracking(r,e,t,s){let o,n=!1;try{const o=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,executionMode:r.executionMode,authorizationHeader:s});if("unwind"===e){const e=r.unwindPositions??r.currentPositions;await t(o,e)}else await t(o);n=!0}catch(r){o=this.getErrorMessage(r),n=!1,console.error(`Agent ${e} function error:`,o)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,n?"success":"failed",o,s)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const a=new n({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await a._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await a._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/unwind",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.unwindFunction||this.defaultUnwindFunction;return await this.executeWithJobTracking(e,"unwind",s,t),r.json({success:!0,message:"Unwind completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(a(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /unwind"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:this.app.fetch.bind(this.app)}}});import{z as f}from"zod";f.enum(["auto","manual"]);var w="0x",E=f.object({suggested:f.literal(!0),suggestionId:f.number(),details:f.record(f.string(),f.unknown())});function v(r){return!0===r.success&&"data"in r&&"object"==typeof r.data&&null!==r.data&&"suggested"in r.data&&!0===r.data.suggested}function D(r){return r.success&&void 0!==r.data}function k(r){return"object"==typeof r&&null!==r&&"out"in r&&!("suggested"in r)}function F(r){return"object"==typeof r&&null!==r&&"orderInfo"in r&&!("suggested"in r)}function b(r){return"object"==typeof r&&null!==r&&"orderId"in r&&!("suggested"in r)}function T(r){return"object"==typeof r&&null!==r&&"txHash"in r&&!("suggested"in r)}f.object({success:f.boolean(),error:f.string().optional(),errorMessage:f.string().optional()});import{z as S}from"zod";var O=S.templateLiteral(["ethereum:",S.coerce.number().int().nonnegative()]),M=S.union([S.literal("solana"),O]),A=S.object({address:S.string(),network:M}),$=S.object({from:A,to:A,fromToken:S.string().optional(),toToken:S.string().optional(),amount:S.string(),slippage:S.string().optional()}),U=S.object({network:M,address:S.string(),token:S.string().nullable(),name:S.string().optional(),symbol:S.string().optional(),decimals:S.number().optional(),amount:S.string().optional(),minimumAmount:S.string().optional(),amountFormatted:S.string().optional(),amountUsd:S.string().optional()}),q=S.object({usd:S.string().optional(),percentage:S.string().optional()}),x=S.object({name:S.string(),amount:S.string().optional(),amountFormatted:S.string().optional(),amountUsd:S.string().optional()}),I=(S.object({programId:S.string(),keys:S.array(S.object({pubkey:S.string(),isSigner:S.boolean(),isWritable:S.boolean()})),data:S.union([S.string(),S.instanceof(Buffer)])}),S.object({type:S.literal("evm"),from:S.string().regex(/^0x[a-fA-F0-9]{40}$/),to:S.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:S.number(),value:S.string(),data:S.string().regex(/^0x[a-fA-F0-9]*$/),gas:S.number().nullish(),maxFeePerGas:S.number().nullish(),maxPriorityFeePerGas:S.number().nullish()})),P=S.object({type:S.literal("solana"),serializedTransaction:S.string()}),j=S.object({type:S.literal("transaction"),description:S.string(),transactionDetails:S.union([I,P])}),N=S.object({type:S.literal("signature"),description:S.string(),signatureData:S.string()}),H=S.discriminatedUnion("type",[j,N]),C=S.object({engine:S.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:U,assetReceive:U,priceImpact:q,fees:S.array(x),steps:S.array(H)}),_=C.extend({expiresAt:S.string().datetime().optional().nullable().default(null)}),K=S.object({network:S.string(),txs:S.array(S.string())}),L=S.object({status:S.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:K.optional(),out:K.optional(),lastUpdated:S.number(),error:S.string().optional()}),R={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},G=r=>S.object({success:S.boolean(),data:r.optional(),error:S.string().optional(),errorMessage:S.string().optional(),errorDetails:S.object({message:S.string().optional(),error:S.string().optional(),status:S.number().optional(),statusText:S.string().optional()}).optional()}).passthrough(),z=G(C),W=G(S.union([L,E]));export{e as APIClient,m as Agent,y as AgentContext,n as AgentSdk,w as EMPTY_DATA,R as QUOTE_RESULT,_ as SwidgeExecuteRequestSchema,W as SwidgeExecuteResponseWrapperSchema,$ as SwidgeQuoteRequestSchema,z as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,b as isHyperliquidExecuted,F as isPolymarketExecuted,s as isSolanaNetwork,D as isSuccessResponse,v as isSuggestedTransaction,k as isSwidgeExecuted,T as isTransactionExecuted};
1
+ import{loadAuthFromFileSystem as t}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCircuitEnvironment(){return!("undefined"==typeof process||!process.env||"circuit"!==process.env.CIRCUIT_BACKEND&&void 0===process.env.AWS_LAMBDA_FUNCTION_NAME&&void 0===process.env.LAMBDA_TASK_ROOT&&void 0===process.env.AWS_EXECUTION_ENV)}getCircuitDevMode(){if("undefined"!=typeof process&&process.env)return process.env.CIRCUIT_DEV_MODE}constructor(t){this.config=t;const e=this.getCircuitDevMode(),r=this.isCircuitEnvironment();let s,n;"local"===e?(s="http://localhost:4001",n="Dev Local"):r?(s="http://transaction-service.agent.internal",n="Circuit (internal)"):(s="https://agents.circuit.org",n="Local (public)"),this.baseUrl=t.baseUrl||s,this.authorizationHeader=t.authorizationHeader}getAgentSlug(){if("undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG)return process.env.CIRCUIT_AGENT_SLUG}getAuthHeaders(){const t={};t["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();e&&(t["X-Agent-Slug"]=e);const r=this.getCircuitDevMode();if(this.isCircuitEnvironment()&&"local"!==r)return t;if(this.authorizationHeader)return t.Authorization=this.authorizationHeader,t;try{const e=this.loadAuthConfig();e?.sessionToken&&(t.Authorization=`Bearer ${e.sessionToken}`)}catch{}return"undefined"!=typeof process&&process.env?.CIRCUIT_DEV_API_KEY&&(t["X-API-Key"]=process.env.CIRCUIT_DEV_API_KEY),t}loadAuthConfig(){try{return t()}catch{}}async makeRequest(t,e={}){const r={...{"Content-Type":"application/json","User-Agent":"circuit-agent-sdk/1.3",Accept:"*/*",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${t}`,n=new AbortController,o=setTimeout(()=>n.abort(),9e5),a={...e,headers:r,signal:n.signal};try{const t=await fetch(s,a);if(clearTimeout(o),!t.ok){const e=await t.text();let r={};try{r=JSON.parse(e)}catch{r={error:e}}const s=r.error||`HTTP ${t.status}: ${t.statusText}`,n=new Error(s);throw n.error=r.error,n.statusCode=t.status,n}return await t.json()}catch(t){if(clearTimeout(o),t instanceof Error){if("AbortError"===t.name||t.message.includes("aborted")){const t=new Error(`Request timeout after 900s to ${s}`);throw t.error="Request Timeout",t}if(t.message.includes("fetch failed")||t.message.includes("ECONNREFUSED")||t.message.includes("ENOTFOUND")||t.message.includes("getaddrinfo")||t.message.includes("network")){const e=new Error(`Network error: ${t.message}. URL: ${s}`);throw e.error="Network Error",e}}throw t}}async get(t){return this.makeRequest(t,{method:"GET"})}async post(t,e){return this.makeRequest(t,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(t){return this.makeRequest(t,{method:"DELETE"})}};function r(t){return t.startsWith("ethereum:")}function s(t){return"solana"===t}function n(t){return Number(t.split(":")[1])}var o={1:"https://etherscan.io",8453:"https://basescan.org",42161:"https://arbiscan.io",10:"https://optimistic.etherscan.io",137:"https://polygonscan.com",56:"https://bscscan.com",43114:"https://snowscan.xyz",100:"https://gnosisscan.io",534352:"https://scrollscan.com",324:"https://explorer.zksync.io",59144:"https://lineascan.build",81457:"https://blastscan.io"};function a(t,e){const r=o[t];return r?`${r}/tx/${e}`:void 0}var i=class t{client;config;constructor(t){this.config=t,this.client=new e(t)}setBaseUrl(t){this.config.baseUrl=t,this.client=new e(this.config)}async _sendLog(t){await this.client.post("/v1/logs",t)}async signAndSend(t){try{if(r(t.network)){const e=n(t.network);if("toAddress"in t.request)return await this.handleEvmTransaction({chainId:e,toAddress:t.request.toAddress,data:t.request.data,valueWei:t.request.value,message:t.message,expiresAt:t.expiresAt??null},{waitForConfirmation:t.waitForConfirmation??!0})}return s(t.network)&&"hexTransaction"in t.request?await this.handleSolanaTransaction({hexTransaction:t.request.hexTransaction,message:t.message,expiresAt:t.expiresAt??null}):{success:!1,error:`Unsupported network: ${t.network}`}}catch(t){const e=t.error;return e?{success:!1,error:e}:{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async signMessage(t){try{return r(t.network)?await this.handleEvmSignMessage(t):{success:!1,error:`Unsupported network: ${t.network}`}}catch(t){const e=t.error;return e?{success:!1,error:e}:{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}swidge={quote:async t=>this.handleSwidgeQuote(t),execute:function(t){return this.handleSwidgeExecute(t)}.bind(this)};memory={set:async(t,e)=>this.handleMemorySet(t,e),get:async t=>this.handleMemoryGet(t),delete:async t=>this.handleMemoryDelete(t),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async t=>this.handlePolymarketMarketOrder(t),redeemPositions:async t=>this.handlePolymarketRedeemPositions(t||{tokenIds:[],waitForConfirmation:!0})},hyperliquid:{placeOrder:async t=>this.handleHyperliquidPlaceOrder(t),order:async t=>this.handleHyperliquidGetOrder(t),deleteOrder:async(t,e)=>this.handleHyperliquidDeleteOrder(t,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async t=>this.handleHyperliquidTransfer(t),liquidations:async t=>this.handleHyperliquidGetLiquidations(t)}};static EVM_PUBLIC_RPCS={1:"https://eth.llamarpc.com",8453:"https://mainnet.base.org",42161:"https://arb1.arbitrum.io/rpc",137:"https://polygon-rpc.com",10:"https://mainnet.optimism.io",43114:"https://api.avax.network/ext/bc/C/rpc",56:"https://bsc-dataseed.binance.org",100:"https://rpc.gnosischain.com",146:"https://rpc.soniclabs.com",17e3:"https://ethereum-holesky-rpc.publicnode.com"};async waitForReceipt(e,r,s=3e4,n=1e3){const o=t.EVM_PUBLIC_RPCS[e];if(!o)return console.warn(`waitForConfirmation: no public RPC for chainId ${e}, skipping`),"unknown";const a=Date.now()+s;for(;Date.now()<a;){try{const t=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[r]}),signal:AbortSignal.timeout(5e3)}),e=await t.json();if(e.result)return"0x1"===e.result.status?"success":"0x0"===e.result.status?"reverted":"unknown"}catch{}await new Promise(t=>setTimeout(t,n))}return console.warn(`waitForConfirmation: timed out after ${s}ms for tx ${r}`),"unknown"}async handleEvmTransaction(t,e){try{const r=(await this.client.post("/v1/transactions/evm",t)).data;if("suggested"in r&&!0===r.suggested)return{success:!0,data:{suggested:!0,suggestionId:r.suggestionId,details:r.details}};const s=r,n=(await this.client.post(`/v1/transactions/evm/${s.id}/broadcast`)).data;return e?.waitForConfirmation&&"reverted"===await this.waitForReceipt(t.chainId,n.transactionHash)?{success:!1,error:`Transaction reverted onchain (tx: ${n.transactionHash})`}:{success:!0,data:{internalTransactionId:s.id,txHash:n.transactionHash,transactionUrl:a(t.chainId,n.transactionHash)}}}catch(t){const e=t.error;return e?{success:!1,error:e}:{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async handleSolanaTransaction(t){try{const r=(await this.client.post("/v1/transactions/solana",t)).data;if("suggested"in r&&!0===r.suggested)return{success:!0,data:{suggested:!0,suggestionId:r.suggestionId,details:r.details}};const s=r,n=(await this.client.post(`/v1/transactions/solana/${s.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:s.id,txHash:n.transactionHash,transactionUrl:(e=n.transactionHash,`https://solscan.io/tx/${e}`)}}}catch(t){const e=t.error;return e?{success:!1,error:e}:{success:!1,error:t instanceof Error?t.message:"Unknown error"}}var e}async handleEvmSignMessage(t){try{return await this.client.post("/v1/messages/evm",{messageType:t.request.messageType,data:t.request.data,chainId:t.request.chainId})}catch(t){const e=t.error;return e?{success:!1,error:e}:{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async _updateJobStatus(t){try{return await this.client.post(`/v1/jobs/${t.jobId}/status`,t)}catch(t){return{status:400,message:`Failed to update job status: ${t instanceof Error?t.message:"Unknown error"}`}}}async handleSwidgeQuote(t){try{return await this.client.post("/v1/swap/quote",t)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get swidge quote";return{success:!1,error:e||r}}}async handleSwidgeExecute(t){try{const e=await this.client.post("/v1/swap/execute",t),r=async t=>{if(!t.success||!t.data||"suggested"in t.data&&!0===t.data.suggested)return null;const e=t.data;for(const t of[e.in,e.out])if(t?.network?.startsWith("ethereum:")){const e=n(t.network);for(const r of t.txs)if("reverted"===await this.waitForReceipt(e,r))return{success:!1,error:`Swidge transaction reverted onchain (tx: ${r})`}}return null};if(Array.isArray(t)){const s=e;for(let e=0;e<s.length;e++)if(!1!==t[e]?.waitForConfirmation){const t=await r(s[e]);t&&(s[e]=t)}}else if(!1!==t.waitForConfirmation){const t=await r(e);if(t)return t}return e}catch(e){const r=e.error,s=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(t)?[{success:!1,error:r||s}]:{success:!1,error:r||s}}}async handlePolymarketMarketOrder(t){try{const e=await this.client.post("/v1/platforms/polymarket/market-order",t);if(e.success&&e.data&&"suggested"in e.data&&!0===e.data.suggested)return e;if(!1!==t.waitForConfirmation&&e.success&&e.data&&"orderInfo"in e.data&&e.data.orderInfo?.txHashes)for(const t of e.data.orderInfo.txHashes)if("reverted"===await this.waitForReceipt(137,t))return{success:!1,error:`Transaction reverted onchain (tx: ${t})`};return e}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to execute polymarket market order";return{success:!1,error:e||r}}}async handlePolymarketRedeemPositions(t){try{const e=await this.client.post("/v1/platforms/polymarket/redeem-positions",t);if(!1!==t.waitForConfirmation&&e.success&&Array.isArray(e.data))for(const t of e.data)if(t.transactionHash&&"reverted"===await this.waitForReceipt(137,t.transactionHash))return{success:!1,error:`Redeem transaction reverted onchain (tx: ${t.transactionHash})`};return e}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to redeem polymarket positions";return{success:!1,error:e||r}}}async handleHyperliquidPlaceOrder(t){try{const e=await this.client.post("/v1/platforms/hyperliquid/order",t);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to place order";return{success:!1,error:e||r}}}async handleHyperliquidGetOrder(t){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${t}`)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get order";return{success:!1,error:e||r}}}async handleHyperliquidDeleteOrder(t,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${t}/${e}`)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to delete order";return{success:!1,error:e||r}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get balances";return{success:!1,error:e||r}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get positions";return{success:!1,error:e||r}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get open orders";return{success:!1,error:e||r}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get order fills";return{success:!1,error:e||r}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get historical orders";return{success:!1,error:e||r}}}async handleHyperliquidTransfer(t){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",t)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to transfer";return{success:!1,error:e||r}}}async handleHyperliquidGetLiquidations(t){try{const e=t?`?startTime=${t}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get liquidations";return{success:!1,error:e||r}}}async handleMemorySet(t,e){try{return await this.client.post(`/v1/memory/${t}`,{value:e})}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to set memory";return{success:!1,error:e||r}}}async handleMemoryGet(t){try{return await this.client.get(`/v1/memory/${t}`)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to get memory";return{success:!1,error:e||r}}}async handleMemoryDelete(t){try{return await this.client.delete(`/v1/memory/${t}`)}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to delete memory";return{success:!1,error:e||r}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to list memory keys";return{success:!1,error:e||r}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to fetch transactions";return{success:!1,error:e||r}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to fetch current positions";return{success:!1,error:e||r}}}async clearSuggestedTransactions(){try{return await this.client.delete("/v1/sessions/suggestions")}catch(t){const e=t.error,r=t instanceof Error?t.message:"Failed to clear suggested transactions";return{success:!1,error:e||r}}}};import{zValidator as c}from"@hono/zod-validator";import{Hono as u}from"hono";import{cors as d}from"hono/cors";import*as l from"zod";var h=class{sessionId;sessionWalletAddress;currentPositions;executionMode;t;constructor(t){this.sessionId=t.sessionId,this.sessionWalletAddress=t.sessionWalletAddress,this.currentPositions=t.currentPositions,this.executionMode=t.executionMode??"auto",this.t=new i({sessionId:t.sessionId,baseUrl:t.baseUrl,authorizationHeader:t.authorizationHeader})}setBaseUrl(t){this.t.setBaseUrl(t)}async log(t,e){const{error:r=!1,debug:s=!1}=e||{};let n,o;const a=(t,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const t=e.toString();if("[object Object]"!==t)return t}catch(t){}return e};if("object"==typeof t&&null!==t?(n=JSON.stringify(t,a,2),o=JSON.stringify(t,a)):(n=String(t),o=String(t)),r?console.error(n):console.log(n),s)return{success:!0};const i=r?"error":"observe";try{return await this.t._sendLog([{type:i,message:o}]),{success:!0}}catch(t){const e=t instanceof Error?t.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:e}}}async signAndSend(t){return this.t.signAndSend(t)}async signMessage(t){return this.t.signMessage(t)}memory={set:async(t,e)=>this.t.memory.set(t,e),get:async t=>this.t.memory.get(t),delete:async t=>this.t.memory.delete(t),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async t=>this.t.platforms.polymarket.marketOrder(t),redeemPositions:async t=>this.t.platforms.polymarket.redeemPositions(t)},hyperliquid:{placeOrder:async t=>this.t.platforms.hyperliquid.placeOrder(t),order:async t=>this.t.platforms.hyperliquid.order(t),deleteOrder:async(t,e)=>this.t.platforms.hyperliquid.deleteOrder(t,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async t=>this.t.platforms.hyperliquid.transfer(t),liquidations:async t=>this.t.platforms.hyperliquid.liquidations(t)}};swidge={quote:async t=>this.t.swidge.quote(t),execute:function(t){return this.t.swidge.execute(t)}.bind(this)};async transactions(){return this.t.transactions()}async clearSuggestedTransactions(){return this.t.clearSuggestedTransactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},y=l.object({network:l.string(),assetAddress:l.string(),tokenId:l.string().nullable(),avgUnitCost:l.string(),currentQty:l.string()}),p=l.object({sessionId:l.number(),sessionWalletAddress:l.string(),jobId:l.string().optional(),currentPositions:l.array(y),unwindPositions:l.array(y).optional(),executionMode:l.enum(["auto","manual"]).default("auto")}),f=(l.object({status:l.string()}),class{app;runFunction;unwindFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(t){this.app=new u,this.runFunction=t.runFunction,this.unwindFunction=t.unwindFunction,this.app.use("*",d()),this.setupRoutes()}defaultUnwindFunction=async(t,e)=>{await t.log(`Unwind requested for session ${t.sessionId} (positions=${e.length}), but no unwindFunction was provided`)};async executeWithJobTracking(t,e,r,s){let n,o=!1;try{const n=new h({sessionId:t.sessionId,sessionWalletAddress:t.sessionWalletAddress,currentPositions:t.currentPositions,executionMode:t.executionMode,authorizationHeader:s});if("unwind"===e){const e=t.unwindPositions??t.currentPositions;await r(n,e)}else await r(n);o=!0}catch(t){n=this.getErrorMessage(t),o=!1,console.error(`Agent ${e} function error:`,n)}finally{t.jobId&&await this.updateJobStatus(t.sessionId,t.jobId,o?"success":"failed",n,s)}return o?{success:!0}:{success:!1,error:n}}getErrorMessage(t){if(null==t)return"Unknown error";try{const e=t?.constructor?.name||"Error";let r="";r=t instanceof Error&&t.message||String(t),r=r.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${r}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(t,e,r,s,n){const o=new i({sessionId:t,authorizationHeader:n});for(let t=1;t<=3;t++)try{return void await o._updateJobStatus({jobId:e,status:r,errorMessage:s})}catch(e){console.error(`Status update attempt ${t}/3 failed:`,e),t<3&&await new Promise(e=>setTimeout(e,100*2**(t-1)))}if("failed"===r)try{return console.warn(`Issue updating job status to '${r}' with error message, attempting to update status without error message`),void await o._updateJobStatus({jobId:e,status:r,errorMessage:void 0})}catch(t){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,t)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",c("json",p),async t=>{const e=t.req.valid("json"),r=t.req.header("Authorization"),s=await this.executeWithJobTracking(e,"run",this.runFunction,r);return t.json(s.success?{success:!0,message:"Execution completed"}:{success:!1,error:s.error},s.success?200:500)}),this.app.post("/unwind",c("json",p),async t=>{const e=t.req.valid("json"),r=t.req.header("Authorization"),s=this.unwindFunction||this.defaultUnwindFunction,n=await this.executeWithJobTracking(e,"unwind",s,r);return t.json(n.success?{success:!0,message:"Unwind completed"}:{success:!1,error:n.error},n.success?200:500)}),this.app.get("/health",async t=>{try{const e=await this.healthCheckFunction();return t.json(e)}catch(e){return console.error("Agent health check error:",e),t.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}async run(t){const e=process.env.AGENT_PORT||globalThis.Bun?.env?.AGENT_PORT,r=t||(e?Number.parseInt(e,10):3e3);try{const{serve:t}=await import("@hono/node-server");console.log(`Server is running on port ${r}`),t({fetch:this.app.fetch,port:r})}catch(t){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:this.app.fetch.bind(this.app)}}});import{z as m}from"zod";m.enum(["auto","manual"]);var g="0x",w=m.object({suggested:m.literal(!0),suggestionId:m.number(),details:m.record(m.string(),m.unknown())});function v(t){return!0===t.success&&"data"in t&&"object"==typeof t.data&&null!==t.data&&"suggested"in t.data&&!0===t.data.suggested}function E(t){return t.success&&void 0!==t.data}function b(t){return"object"==typeof t&&null!==t&&"out"in t&&!("suggested"in t)}function F(t){return"object"==typeof t&&null!==t&&"orderInfo"in t&&!("suggested"in t)}function k(t){return"object"==typeof t&&null!==t&&"orderId"in t&&!("suggested"in t)}function $(t){return"object"==typeof t&&null!==t&&"txHash"in t&&!("suggested"in t)}m.object({success:m.boolean(),error:m.string().optional()});import{z as x}from"zod";var T=x.templateLiteral(["ethereum:",x.coerce.number().int().nonnegative()]),O=x.union([x.literal("solana"),T]),A=x.object({address:x.string(),network:O}),q=x.object({from:A,to:A,fromToken:x.string().optional(),toToken:x.string().optional(),amount:x.string(),slippage:x.string().optional()}),I=x.object({network:O,address:x.string(),token:x.string().nullable(),name:x.string().optional(),symbol:x.string().optional(),decimals:x.number().optional(),amount:x.string().optional(),minimumAmount:x.string().optional(),amountFormatted:x.string().optional(),amountUsd:x.string().optional()}),U=x.object({usd:x.string().optional(),percentage:x.string().optional()}),S=x.object({name:x.string(),amount:x.string().optional(),amountFormatted:x.string().optional(),amountUsd:x.string().optional()}),P=(x.object({programId:x.string(),keys:x.array(x.object({pubkey:x.string(),isSigner:x.boolean(),isWritable:x.boolean()})),data:x.union([x.string(),x.instanceof(Buffer)])}),x.object({type:x.literal("evm"),from:x.string().regex(/^0x[a-fA-F0-9]{40}$/),to:x.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:x.number(),value:x.string(),data:x.string().regex(/^0x[a-fA-F0-9]*$/),gas:x.number().optional(),maxFeePerGas:x.string().optional(),maxPriorityFeePerGas:x.string().optional()})),C=x.object({type:x.literal("solana"),serializedTransaction:x.string()}),j=x.object({type:x.literal("transaction"),description:x.string(),transactionDetails:x.union([P,C])}),H=x.object({type:x.literal("signature"),description:x.string(),signatureData:x.string()}),N=x.discriminatedUnion("type",[j,H]),M=x.object({engine:x.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:I,assetReceive:I,priceImpact:U,fees:x.array(S),steps:x.array(N)}),D=M.extend({expiresAt:x.string().datetime().optional().nullable().default(null),waitForConfirmation:x.boolean().optional().default(!0)}),_=x.object({network:x.string(),txs:x.array(x.string())}),R=x.object({status:x.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:_.optional(),out:_.optional(),lastUpdated:x.number(),error:x.string().optional()}),L={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},z=t=>x.object({success:x.boolean(),data:t.optional(),error:x.string().optional()}).passthrough(),G=z(M),W=z(x.union([R,w]));export{e as APIClient,f as Agent,h as AgentContext,i as AgentSdk,g as EMPTY_DATA,L as QUOTE_RESULT,D as SwidgeExecuteRequestSchema,W as SwidgeExecuteResponseWrapperSchema,q as SwidgeQuoteRequestSchema,G as SwidgeQuoteResponseWrapperSchema,n as getChainIdFromNetwork,r as isEthereumNetwork,k as isHyperliquidExecuted,F as isPolymarketExecuted,s as isSolanaNetwork,E as isSuccessResponse,v as isSuggestedTransaction,b as isSwidgeExecuted,$ as isTransactionExecuted};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.3.10",
3
+ "version": "1.4.0",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",