@circuitorg/agent-sdk 1.3.8 → 1.3.9

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 +422 -94
  2. package/index.js +1 -1
  3. package/package.json +1 -1
package/index.d.ts CHANGED
@@ -18,6 +18,16 @@ type SignAndSendRequest = {
18
18
  network: Network;
19
19
  /** Optional short message to be attached to the transaction for observability */
20
20
  message?: string;
21
+ /**
22
+ * When true, forces immediate execution even if session is in manual mode.
23
+ * @default false
24
+ */
25
+ bypassManualApproval?: boolean;
26
+ /**
27
+ * ISO 8601 timestamp for when the suggestion expires (only used in manual mode).
28
+ * If not provided, the suggestion never expires.
29
+ */
30
+ expiresAt?: string | null;
21
31
  } & ({
22
32
  network: `ethereum:${number}`;
23
33
  request: {
@@ -32,36 +42,32 @@ type SignAndSendRequest = {
32
42
  };
33
43
  });
34
44
  /**
35
- * Success data from signAndSend operations
45
+ * SignAndSend response with union type for manual mode support
36
46
  */
37
- type SignAndSendData = {
38
- /** Internal transaction ID for tracking */
39
- internalTransactionId: number;
40
- /** Transaction hash once broadcast */
41
- txHash: string;
42
- /** Optional transaction URL (explorer link) */
43
- transactionUrl?: string;
44
- };
47
+ declare const SignAndSendResponseSchema: z$1.ZodObject<{
48
+ success: z$1.ZodBoolean;
49
+ data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
50
+ internalTransactionId: z$1.ZodNumber;
51
+ txHash: z$1.ZodString;
52
+ transactionUrl: z$1.ZodOptional<z$1.ZodString>;
53
+ }, z$1.core.$strip>, z$1.ZodObject<{
54
+ suggested: z$1.ZodLiteral<true>;
55
+ suggestionId: z$1.ZodNumber;
56
+ details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
57
+ }, z$1.core.$strip>]>>;
58
+ error: z$1.ZodOptional<z$1.ZodString>;
59
+ errorMessage: z$1.ZodOptional<z$1.ZodString>;
60
+ errorDetails: z$1.ZodOptional<z$1.ZodObject<{
61
+ message: z$1.ZodOptional<z$1.ZodString>;
62
+ error: z$1.ZodOptional<z$1.ZodString>;
63
+ status: z$1.ZodOptional<z$1.ZodNumber>;
64
+ statusText: z$1.ZodOptional<z$1.ZodString>;
65
+ }, z$1.core.$strip>>;
66
+ }, z$1.core.$strip>;
45
67
  /**
46
- * Standard response from signAndSend operations
68
+ * Standard response from signAndSend operations (TypeScript type)
47
69
  */
48
- type SignAndSendResponse = {
49
- /** Whether the operation was successful */
50
- success: boolean;
51
- /** Transaction data (only present on success) */
52
- data?: SignAndSendData;
53
- /** Error category from API (only present on failure) */
54
- error?: string;
55
- /** Detailed error message from API (only present on failure) */
56
- errorMessage?: string;
57
- /** Detailed error information (only present on failure) */
58
- errorDetails?: {
59
- message?: string;
60
- error?: string;
61
- status?: number;
62
- statusText?: string;
63
- };
64
- };
70
+ type SignAndSendResponse = z$1.infer<typeof SignAndSendResponseSchema>;
65
71
  /**
66
72
  * EIP712 TypedData schema for typed message signing
67
73
  */
@@ -413,6 +419,7 @@ declare const SwidgeQuoteDataSchema: z$1.ZodObject<{
413
419
  }, z$1.core.$strip>;
414
420
  /**
415
421
  * Execute request schema - takes the complete quote response from quote() method
422
+ * with optional manual mode options
416
423
  */
417
424
  declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
418
425
  engine: z$1.ZodString;
@@ -472,6 +479,8 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
472
479
  description: z$1.ZodString;
473
480
  signatureData: z$1.ZodString;
474
481
  }, z$1.core.$strip>], "type">>;
482
+ bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
483
+ expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
475
484
  }, z$1.core.$strip>;
476
485
  /**
477
486
  * Quote result constants - type QUOTE_RESULT. to see available options
@@ -564,11 +573,11 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
564
573
  }, z$1.core.$strip>>;
565
574
  }, z$1.core.$loose>;
566
575
  /**
567
- * Swidge execute response wrapper
576
+ * Swidge execute response wrapper with union type for manual mode support
568
577
  */
569
578
  declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
570
579
  success: z$1.ZodBoolean;
571
- data: z$1.ZodOptional<z$1.ZodObject<{
580
+ data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
572
581
  status: z$1.ZodString;
573
582
  in: z$1.ZodOptional<z$1.ZodObject<{
574
583
  network: z$1.ZodString;
@@ -580,7 +589,11 @@ declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
580
589
  }, z$1.core.$strip>>;
581
590
  lastUpdated: z$1.ZodNumber;
582
591
  error: z$1.ZodOptional<z$1.ZodString>;
583
- }, z$1.core.$strip>>;
592
+ }, z$1.core.$strip>, z$1.ZodObject<{
593
+ suggested: z$1.ZodLiteral<true>;
594
+ suggestionId: z$1.ZodNumber;
595
+ details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
596
+ }, z$1.core.$strip>]>>;
584
597
  error: z$1.ZodOptional<z$1.ZodString>;
585
598
  errorMessage: z$1.ZodOptional<z$1.ZodString>;
586
599
  errorDetails: z$1.ZodOptional<z$1.ZodObject<{
@@ -602,20 +615,32 @@ declare const PolymarketMarketOrderRequestSchema: z$1.ZodObject<{
602
615
  BUY: "BUY";
603
616
  SELL: "SELL";
604
617
  }>;
618
+ bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
619
+ expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
605
620
  }, z$1.core.$strip>;
606
621
  declare const PolymarketRedeemPositionsRequestSchema: z$1.ZodObject<{
607
622
  tokenIds: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>>;
608
623
  }, z$1.core.$strip>;
624
+ /**
625
+ * Polymarket market order response with union type for manual mode support
626
+ */
609
627
  declare const PolymarketMarketOrderResponseSchema: z$1.ZodObject<{
610
628
  success: z$1.ZodBoolean;
611
- data: z$1.ZodOptional<z$1.ZodObject<{
612
- orderId: z$1.ZodString;
613
- side: z$1.ZodString;
614
- size: z$1.ZodString;
615
- priceUsd: z$1.ZodString;
616
- totalPriceUsd: z$1.ZodString;
617
- txHashes: z$1.ZodArray<z$1.ZodString>;
618
- }, z$1.core.$strip>>;
629
+ data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
630
+ success: z$1.ZodBoolean;
631
+ orderInfo: z$1.ZodObject<{
632
+ orderId: z$1.ZodString;
633
+ side: z$1.ZodString;
634
+ size: z$1.ZodString;
635
+ priceUsd: z$1.ZodString;
636
+ totalPriceUsd: z$1.ZodString;
637
+ txHashes: z$1.ZodArray<z$1.ZodString>;
638
+ }, z$1.core.$strip>;
639
+ }, z$1.core.$strip>, z$1.ZodObject<{
640
+ suggested: z$1.ZodLiteral<true>;
641
+ suggestionId: z$1.ZodNumber;
642
+ details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
643
+ }, z$1.core.$strip>]>>;
619
644
  error: z$1.ZodOptional<z$1.ZodString>;
620
645
  errorMessage: z$1.ZodOptional<z$1.ZodString>;
621
646
  errorDetails: z$1.ZodOptional<z$1.ZodObject<{
@@ -662,7 +687,7 @@ declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
662
687
  statusText: z$1.ZodOptional<z$1.ZodString>;
663
688
  }, z$1.core.$strip>>;
664
689
  }, z$1.core.$loose>;
665
- type PolymarketMarketOrderRequest = z$1.infer<typeof PolymarketMarketOrderRequestSchema>;
690
+ type PolymarketMarketOrderRequest = z$1.input<typeof PolymarketMarketOrderRequestSchema>;
666
691
  type PolymarketRedeemPositionsRequest = z$1.infer<typeof PolymarketRedeemPositionsRequestSchema>;
667
692
  type PolymarketMarketOrderResponse = z$1.infer<typeof PolymarketMarketOrderResponseSchema>;
668
693
  type PolymarketRedeemPositionsResponse = z$1.infer<typeof PolymarketRedeemPositionsResponseSchema>;
@@ -691,6 +716,8 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
691
716
  triggerPrice: z$1.ZodOptional<z$1.ZodNumber>;
692
717
  reduceOnly: z$1.ZodOptional<z$1.ZodBoolean>;
693
718
  postOnly: z$1.ZodOptional<z$1.ZodBoolean>;
719
+ bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
720
+ expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
694
721
  }, z$1.core.$strip>;
695
722
  /**
696
723
  * Request to transfer between spot and perp accounts on Hyperliquid
@@ -698,10 +725,15 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
698
725
  declare const HyperliquidTransferRequestSchema: z$1.ZodObject<{
699
726
  amount: z$1.ZodNumber;
700
727
  toPerp: z$1.ZodBoolean;
728
+ bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
729
+ expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
701
730
  }, z$1.core.$strip>;
731
+ /**
732
+ * Hyperliquid place order response with union type for manual mode support
733
+ */
702
734
  declare const HyperliquidPlaceOrderResponseSchema: z$1.ZodObject<{
703
735
  success: z$1.ZodBoolean;
704
- data: z$1.ZodOptional<z$1.ZodObject<{
736
+ data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
705
737
  orderId: z$1.ZodString;
706
738
  symbol: z$1.ZodString;
707
739
  side: z$1.ZodString;
@@ -711,7 +743,11 @@ declare const HyperliquidPlaceOrderResponseSchema: z$1.ZodObject<{
711
743
  status: z$1.ZodString;
712
744
  market: z$1.ZodString;
713
745
  clientOrderId: z$1.ZodOptional<z$1.ZodString>;
714
- }, z$1.core.$strip>>;
746
+ }, z$1.core.$strip>, z$1.ZodObject<{
747
+ suggested: z$1.ZodLiteral<true>;
748
+ suggestionId: z$1.ZodNumber;
749
+ details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
750
+ }, z$1.core.$strip>]>>;
715
751
  error: z$1.ZodOptional<z$1.ZodString>;
716
752
  }, z$1.core.$loose>;
717
753
  declare const HyperliquidOrderResponseSchema: z$1.ZodObject<{
@@ -833,8 +869,8 @@ declare const HyperliquidLiquidationsResponseSchema: z$1.ZodObject<{
833
869
  }, z$1.core.$strip>>>;
834
870
  error: z$1.ZodOptional<z$1.ZodString>;
835
871
  }, z$1.core.$loose>;
836
- type HyperliquidPlaceOrderRequest = z$1.infer<typeof HyperliquidPlaceOrderRequestSchema>;
837
- type HyperliquidTransferRequest = z$1.infer<typeof HyperliquidTransferRequestSchema>;
872
+ type HyperliquidPlaceOrderRequest = z$1.input<typeof HyperliquidPlaceOrderRequestSchema>;
873
+ type HyperliquidTransferRequest = z$1.input<typeof HyperliquidTransferRequestSchema>;
838
874
  type HyperliquidPlaceOrderResponse = z$1.infer<typeof HyperliquidPlaceOrderResponseSchema>;
839
875
  type HyperliquidOrderResponse = z$1.infer<typeof HyperliquidOrderResponseSchema>;
840
876
  type HyperliquidDeleteOrderResponse = z$1.infer<typeof HyperliquidDeleteOrderResponseSchema>;
@@ -928,6 +964,188 @@ type MemoryGetResponse = z$1.infer<typeof MemoryGetResponseSchema>;
928
964
  type MemoryDeleteResponse = z$1.infer<typeof MemoryDeleteResponseSchema>;
929
965
  type MemoryListResponse = z$1.infer<typeof MemoryListResponseSchema>;
930
966
 
967
+ /**
968
+ * Manual execution mode types for suggested transactions.
969
+ *
970
+ * When a session is in "manual" mode, transaction operations return
971
+ * suggested transactions instead of executing them immediately.
972
+ */
973
+
974
+ /**
975
+ * Execution mode for agent sessions
976
+ * - "auto": Transactions execute immediately (default behavior)
977
+ * - "manual": Transactions are stored as suggestions for user approval
978
+ * - "hybrid": Reserved for future use
979
+ */
980
+ type ExecutionMode = "auto" | "manual" | "hybrid";
981
+ /**
982
+ * Empty data constant for Ethereum transactions.
983
+ * Use this for simple transfers without any contract interaction.
984
+ *
985
+ * @example
986
+ * ```typescript
987
+ * await agent.signAndSend({
988
+ * network: "ethereum:1",
989
+ * request: {
990
+ * toAddress: recipientAddress,
991
+ * data: EMPTY_DATA,
992
+ * value: "1000000000000000000", // 1 ETH
993
+ * }
994
+ * });
995
+ * ```
996
+ */
997
+ declare const EMPTY_DATA: "0x";
998
+ /**
999
+ * Type alias for Ethereum addresses.
1000
+ * Ensures addresses start with "0x" followed by 40 hex characters.
1001
+ */
1002
+ type EthereumAddress = `0x${string}`;
1003
+ /**
1004
+ * Type alias for Ethereum data/calldata.
1005
+ * Must start with "0x" followed by even number of hex characters.
1006
+ */
1007
+ type EthereumData = `0x${string}`;
1008
+ /**
1009
+ * Base data structure for all suggested transaction responses.
1010
+ * Nested under the `data` field in the response.
1011
+ */
1012
+ interface SuggestedTransactionData {
1013
+ /** Indicates this is a suggested transaction, not an executed one */
1014
+ suggested: true;
1015
+ /** Unique identifier for the suggestion record */
1016
+ suggestionId: number;
1017
+ /** Transaction details for display to the user */
1018
+ details: Record<string, unknown>;
1019
+ }
1020
+ /**
1021
+ * Type guard to check if a response is a suggested transaction
1022
+ *
1023
+ * @example
1024
+ * ```typescript
1025
+ * const swap = await agent.swidge.execute(quote.data);
1026
+ * if (isSuggestedTransaction(swap)) {
1027
+ * console.log(`Suggestion ID: ${swap.data.suggestionId}`);
1028
+ * } else {
1029
+ * console.log(`Executed: ${swap.data}`);
1030
+ * }
1031
+ * ```
1032
+ */
1033
+ declare function isSuggestedTransaction<T extends {
1034
+ success: boolean;
1035
+ data?: unknown;
1036
+ }>(response: T): response is T & {
1037
+ success: true;
1038
+ data: SuggestedTransactionData;
1039
+ };
1040
+ /**
1041
+ * Generic type guard to check if a response is successful and has data
1042
+ *
1043
+ * @example
1044
+ * ```typescript
1045
+ * const result = await agent.memory.get("key");
1046
+ * if (isSuccessResponse(result)) {
1047
+ * // TypeScript knows result.data exists and is defined
1048
+ * console.log(result.data.value);
1049
+ * }
1050
+ * ```
1051
+ */
1052
+ declare function isSuccessResponse<T>(response: {
1053
+ success: boolean;
1054
+ data?: T;
1055
+ error?: string;
1056
+ errorMessage?: string;
1057
+ }): response is {
1058
+ success: true;
1059
+ data: T;
1060
+ };
1061
+ /**
1062
+ * Type guard to check if swap data is an executed swap (not a suggestion)
1063
+ *
1064
+ * @example
1065
+ * ```typescript
1066
+ * import type { SwidgeExecuteData, SuggestedTransactionData } from "@circuitorg/agent-sdk";
1067
+ *
1068
+ * const swap = await agent.swidge.execute(quote.data);
1069
+ * if (swap.success && swap.data) {
1070
+ * if (isSwidgeExecuted(swap.data)) {
1071
+ * console.log(`Swap executed: ${swap.data.out?.txs[0]}`);
1072
+ * } else {
1073
+ * console.log(`Swap suggested: ${swap.data.suggestionId}`);
1074
+ * }
1075
+ * }
1076
+ * ```
1077
+ */
1078
+ declare function isSwidgeExecuted(data: unknown): data is {
1079
+ out?: {
1080
+ txs?: string[];
1081
+ };
1082
+ };
1083
+ /**
1084
+ * Type guard to check if Polymarket order data is an executed order (not a suggestion)
1085
+ *
1086
+ * @example
1087
+ * ```typescript
1088
+ * const order = await agent.platforms.polymarket.marketOrder({...});
1089
+ * if (order.success && order.data) {
1090
+ * if (isPolymarketExecuted(order.data)) {
1091
+ * console.log(`Order executed: ${order.data.orderInfo}`);
1092
+ * } else {
1093
+ * console.log(`Order suggested: ${order.data.suggestionId}`);
1094
+ * }
1095
+ * }
1096
+ * ```
1097
+ */
1098
+ declare function isPolymarketExecuted(data: unknown): data is {
1099
+ success: boolean;
1100
+ orderInfo: unknown;
1101
+ };
1102
+ /**
1103
+ * Type guard to check if Hyperliquid order data is an executed order (not a suggestion)
1104
+ *
1105
+ * @example
1106
+ * ```typescript
1107
+ * const order = await agent.platforms.hyperliquid.placeOrder({...});
1108
+ * if (order.success && order.data) {
1109
+ * if (isHyperliquidExecuted(order.data)) {
1110
+ * console.log(`Order ID: ${order.data.orderId}`);
1111
+ * } else {
1112
+ * console.log(`Order suggested: ${order.data.suggestionId}`);
1113
+ * }
1114
+ * }
1115
+ * ```
1116
+ */
1117
+ declare function isHyperliquidExecuted(data: unknown): data is {
1118
+ orderId: string;
1119
+ };
1120
+ /**
1121
+ * Type guard to check if transaction data is an executed transaction (not a suggestion)
1122
+ *
1123
+ * @example
1124
+ * ```typescript
1125
+ * const tx = await agent.signAndSend({...});
1126
+ * if (tx.success && tx.data) {
1127
+ * if (isTransactionExecuted(tx.data)) {
1128
+ * console.log(`Tx hash: ${tx.data.txHash}`);
1129
+ * } else {
1130
+ * console.log(`Transaction suggested: ${tx.data.suggestionId}`);
1131
+ * }
1132
+ * }
1133
+ * ```
1134
+ */
1135
+ declare function isTransactionExecuted(data: unknown): data is {
1136
+ internalTransactionId: number;
1137
+ txHash: string;
1138
+ transactionUrl?: string;
1139
+ };
1140
+ /**
1141
+ * Response from clearing suggested transactions
1142
+ */
1143
+ interface ClearSuggestionsResponse {
1144
+ success: boolean;
1145
+ error?: string;
1146
+ errorMessage?: string;
1147
+ }
1148
+
931
1149
  /**
932
1150
  * Main AgentSdk class with simplified API surface
933
1151
  */
@@ -1250,7 +1468,7 @@ declare class AgentSdk {
1250
1468
  */
1251
1469
  execute: {
1252
1470
  (executeQuote: SwidgeExecuteRequest): Promise<SwidgeExecuteResponse>;
1253
- (executeQuotes: SwidgeExecuteRequest[]): Promise<SwidgeExecuteResponse[]>;
1471
+ (executeQuotes: SwidgeExecuteRequest[]): Promise<SwidgeExecuteResponse[] | SwidgeExecuteResponse[]>;
1254
1472
  };
1255
1473
  };
1256
1474
  /**
@@ -2201,6 +2419,15 @@ declare class AgentSdk {
2201
2419
  * ```
2202
2420
  */
2203
2421
  getCurrentPositions(): Promise<CurrentPositionsResponse>;
2422
+ /**
2423
+ * Clear all pending suggested transactions for this session.
2424
+ *
2425
+ * Performs a soft delete by setting the `deletedAt` timestamp on all
2426
+ * unprocessed suggestions across all suggestion tables.
2427
+ *
2428
+ * @returns Promise resolving to ClearSuggestionsResponse
2429
+ */
2430
+ clearSuggestedTransactions(): Promise<ClearSuggestionsResponse>;
2204
2431
  }
2205
2432
 
2206
2433
  /**
@@ -2220,6 +2447,7 @@ declare class APIClient {
2220
2447
  private baseUrl;
2221
2448
  private authorizationHeader?;
2222
2449
  private isCircuitEnvironment;
2450
+ private getCircuitDevMode;
2223
2451
  /**
2224
2452
  * Create an API client.
2225
2453
  * @param config - SDK configuration
@@ -2369,6 +2597,13 @@ declare class AgentContext {
2369
2597
  readonly sessionWalletAddress: string;
2370
2598
  /** Current positions allocated to this agent (required) */
2371
2599
  readonly currentPositions: CurrentPosition[];
2600
+ /**
2601
+ * Execution mode for this session.
2602
+ * - "auto": Transactions execute immediately (default behavior)
2603
+ * - "manual": Transactions are stored as suggestions for user approval
2604
+ * - "hybrid": Reserved for future use
2605
+ */
2606
+ readonly executionMode: ExecutionMode;
2372
2607
  /** Internal SDK instance */
2373
2608
  private _sdk;
2374
2609
  /**
@@ -2399,6 +2634,7 @@ declare class AgentContext {
2399
2634
  sessionId: number;
2400
2635
  sessionWalletAddress: string;
2401
2636
  currentPositions: CurrentPosition[];
2637
+ executionMode?: ExecutionMode;
2402
2638
  baseUrl?: string;
2403
2639
  authorizationHeader?: string;
2404
2640
  });
@@ -2487,6 +2723,8 @@ declare class AgentContext {
2487
2723
  * **Input**: `SignAndSendRequest`
2488
2724
  * - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
2489
2725
  * - `message` (string | undefined): Optional context message
2726
+ * - `bypassManualApproval` (boolean | undefined): Force execution even in manual mode
2727
+ * - `expiresAt` (string | null | undefined): ISO 8601 timestamp for suggestion expiry
2490
2728
  * - `request` (object): Transaction payload
2491
2729
  * - For Ethereum:
2492
2730
  * - `toAddress` (string): Recipient address as hex string
@@ -2502,33 +2740,52 @@ declare class AgentContext {
2502
2740
  *
2503
2741
  * **Output**: `SignAndSendResponse`
2504
2742
  * - `success` (boolean): Whether the operation succeeded
2505
- * - `txHash` (string | undefined): Transaction hash on success
2506
- * - `transactionUrl` (string | undefined): Explorer link on success
2507
- * - `internalTransactionId` (number | undefined): Internal tracking ID
2743
+ * - `data` (SignAndSendData | SuggestedTransactionData | undefined): Response data
2744
+ * - In auto mode: SignAndSendData with txHash, transactionUrl, etc.
2745
+ * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
2508
2746
  * - `error` (string | undefined): Error message on failure
2747
+ * - `errorMessage` (string | undefined): Detailed error message on failure
2509
2748
  * - `errorDetails` (object | undefined): Detailed error info
2510
2749
  *
2511
2750
  * @param request - Transaction request with network and transaction details
2512
- * @returns Promise resolving to SignAndSendResponse with transaction hash or error details
2751
+ * @returns Promise resolving to SignAndSendResponse
2513
2752
  *
2514
2753
  * @example
2515
2754
  * ```typescript
2516
- * const response = await agent.signAndSend({
2517
- * network: "ethereum:42161",
2755
+ * // Auto mode or manual mode with bypass - transaction is executed
2756
+ * const result = await agent.signAndSend({
2757
+ * network: "ethereum:8453",
2518
2758
  * request: {
2519
- * toAddress: "0x742d35cc6634C0532925a3b8D65e95f32B6b5582",
2520
- * data: "0x",
2521
- * value: "1000000000000000000", // 1 ETH
2522
- * gas: 21000,
2523
- * maxFeePerGas: "20000000000"
2759
+ * toAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bB70" as `0x${string}`,
2760
+ * data: "0x" as `0x${string}`,
2761
+ * value: "1000000000000000000", // 1 ETH
2524
2762
  * },
2525
- * message: "Sending 1 ETH"
2763
+ * message: "Send 1 ETH to Bob",
2526
2764
  * });
2527
2765
  *
2528
- * if (response.success) {
2529
- * await agent.log(`Transaction sent: ${response.txHash}`);
2530
- * } else {
2531
- * await agent.log(response.error || 'Transaction failed', { error: true });
2766
+ * if (result.success && result.data) {
2767
+ * if (isTransactionExecuted(result.data)) {
2768
+ * console.log(`Transaction sent: ${result.data.txHash}`);
2769
+ * }
2770
+ * }
2771
+ *
2772
+ * // Manual mode - transaction is suggested for approval
2773
+ * const result = await agent.signAndSend({
2774
+ * network: "ethereum:8453",
2775
+ * request: {
2776
+ * toAddress: recipient as `0x${string}`,
2777
+ * data: EMPTY_DATA,
2778
+ * value: amount,
2779
+ * },
2780
+ * message: "Transfer to recipient",
2781
+ * });
2782
+ *
2783
+ * if (result.success && result.data) {
2784
+ * if (isSuggestedTransaction(result)) {
2785
+ * console.log(`Transaction suggested (ID: ${result.data.suggestionId})`);
2786
+ * } else if (isTransactionExecuted(result.data)) {
2787
+ * console.log(`Transaction executed: ${result.data.txHash}`);
2788
+ * }
2532
2789
  * }
2533
2790
  * ```
2534
2791
  */
@@ -2732,17 +2989,24 @@ declare class AgentContext {
2732
2989
  * - `tokenId` (string): Market token ID for the position
2733
2990
  * - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
2734
2991
  * - `side` ("BUY" | "SELL"): Order side
2992
+ * - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
2993
+ * - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
2735
2994
  *
2736
2995
  * **Output**: `PolymarketMarketOrderResponse`
2737
2996
  * - `success` (boolean): Whether the operation was successful
2738
- * - `data`: Market order data with orderInfo (orderId, side, priceUsd, txHashes)
2739
- * - `error`: Error message on failure
2997
+ * - `data` (PolymarketMarketOrderData | SuggestedTransactionData | undefined): Response data
2998
+ * - In auto mode: PolymarketMarketOrderData with orderInfo (orderId, side, priceUsd, txHashes)
2999
+ * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
3000
+ * - `error` (string | undefined): Error message on failure
3001
+ * - `errorMessage` (string | undefined): Detailed error message on failure
2740
3002
  *
2741
3003
  * @param request - Order parameters (tokenId, size, side)
2742
- * @returns Promise resolving to PolymarketMarketOrderResponse with order details
3004
+ * @returns Promise resolving to PolymarketMarketOrderResponse with order details or suggestion
2743
3005
  *
2744
3006
  * @example
2745
3007
  * ```typescript
3008
+ * import { isSuggestedTransaction, isPolymarketExecuted } from "@circuitorg/agent-sdk";
3009
+ *
2746
3010
  * // BUY order - size is USD amount
2747
3011
  * const buyResult = await agent.platforms.polymarket.marketOrder({
2748
3012
  * tokenId: "123456",
@@ -2751,8 +3015,14 @@ declare class AgentContext {
2751
3015
  * });
2752
3016
  *
2753
3017
  * if (buyResult.success && buyResult.data) {
2754
- * await agent.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
2755
- * await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
3018
+ * if (isSuggestedTransaction(buyResult)) {
3019
+ * await agent.log(`Order suggested (ID: ${buyResult.data.suggestionId})`);
3020
+ * } else if (isPolymarketExecuted(buyResult.data)) {
3021
+ * await agent.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
3022
+ * await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
3023
+ * }
3024
+ * } else {
3025
+ * await agent.log(`Order failed: ${buyResult.errorMessage}`, { error: true });
2756
3026
  * }
2757
3027
  *
2758
3028
  * // SELL order - size is number of shares
@@ -2813,7 +3083,7 @@ declare class AgentContext {
2813
3083
  * Submit a market, limit, stop, or take-profit order for perpetuals or spot trading.
2814
3084
  *
2815
3085
  * **Input**: `HyperliquidPlaceOrderRequest`
2816
- * - `symbol` (string): Trading pair symbol (e.g., "BTC-USD")
3086
+ * - `symbol` (string): Trading pair symbol (e.g., "BTC", "ETH")
2817
3087
  * - `side` ("buy" | "sell"): Order side
2818
3088
  * - `size` (number): Order size
2819
3089
  * - `price` (number): Order price (for market orders, acts as slippage limit)
@@ -2822,29 +3092,27 @@ declare class AgentContext {
2822
3092
  * - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
2823
3093
  * - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
2824
3094
  * - `postOnly` (boolean, optional): Whether this is a post-only order
3095
+ * - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
3096
+ * - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
2825
3097
  *
2826
3098
  * **Output**: `HyperliquidPlaceOrderResponse`
2827
3099
  * - `success` (boolean): Whether the operation was successful
2828
- * - `data` (HyperliquidOrderInfo | undefined): Order information (only present on success)
2829
- * - `data.orderId` (string): Order ID
2830
- * - `data.symbol` (string): Trading pair symbol
2831
- * - `data.side` ("buy" | "sell"): Order side
2832
- * - `data.price` (number): Order price
2833
- * - `data.size` (number): Order size
2834
- * - `data.filled` (number): Filled amount
2835
- * - `data.status` (string): Order status
2836
- * - `data.market` ("perp" | "spot"): Market type
2837
- * - `data.clientOrderId` (string | undefined): Client order ID
3100
+ * - `data` (HyperliquidOrderInfo | SuggestedTransactionData | undefined): Response data
3101
+ * - In auto mode: HyperliquidOrderInfo with orderId, symbol, side, price, size, filled, status, market, clientOrderId
3102
+ * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
2838
3103
  * - `error` (string | undefined): Error message (only present on failure)
3104
+ * - `errorMessage` (string | undefined): Detailed error message (only present on failure)
2839
3105
  *
2840
3106
  * @param request - Order parameters
2841
3107
  * @returns Promise resolving to HyperliquidPlaceOrderResponse
2842
3108
  *
2843
3109
  * @example
2844
3110
  * ```ts
3111
+ * import { isSuggestedTransaction, isHyperliquidExecuted } from "@circuitorg/agent-sdk";
3112
+ *
2845
3113
  * // Market order
2846
3114
  * const result = await agent.platforms.hyperliquid.placeOrder({
2847
- * symbol: "BTC-USD",
3115
+ * symbol: "BTC",
2848
3116
  * side: "buy",
2849
3117
  * size: 0.0001,
2850
3118
  * price: 110000,
@@ -2852,19 +3120,31 @@ declare class AgentContext {
2852
3120
  * type: "market",
2853
3121
  * });
2854
3122
  *
3123
+ * if (result.success && result.data) {
3124
+ * if (isSuggestedTransaction(result)) {
3125
+ * await agent.log(`Order suggested (ID: ${result.data.suggestionId})`);
3126
+ * } else if (isHyperliquidExecuted(result.data)) {
3127
+ * await agent.log(`Order placed: ${result.data.orderId}`);
3128
+ * await agent.log(`Status: ${result.data.status}`);
3129
+ * }
3130
+ * } else {
3131
+ * await agent.log(`Order failed: ${result.errorMessage}`, { error: true });
3132
+ * }
3133
+ *
2855
3134
  * // Limit order
2856
- * const result = await agent.platforms.hyperliquid.placeOrder({
2857
- * symbol: "BTC-USD",
3135
+ * const limitResult = await agent.platforms.hyperliquid.placeOrder({
3136
+ * symbol: "BTC",
2858
3137
  * side: "buy",
2859
3138
  * size: 0.0001,
2860
3139
  * price: 100000,
2861
3140
  * market: "perp",
2862
3141
  * type: "limit",
2863
3142
  * });
2864
- *
2865
- * if (result.success && result.data) {
2866
- * await agent.log(`Order placed: ${result.data.orderId}`);
2867
- * await agent.log(`Status: ${result.data.status}`);
3143
+ * * await agent.log(`Order suggested: ${result.data.suggestionId}`);
3144
+ * } else {
3145
+ * await agent.log(`Order placed: ${result.data.orderId}`);
3146
+ * await agent.log(`Status: ${result.data.status}`);
3147
+ * }
2868
3148
  * } else {
2869
3149
  * await agent.log(`Error: ${result.error}`, { error: true });
2870
3150
  * }
@@ -3249,34 +3529,47 @@ declare class AgentContext {
3249
3529
  * **Input**: `SwidgeQuoteData | SwidgeQuoteData[]` - Complete quote object(s) from agent.swidge.quote()
3250
3530
  *
3251
3531
  * **Output**: `SwidgeExecuteResponse | SwidgeExecuteResponse[]` (matching input type)
3252
- * - `success`: Whether the execution was successful
3253
- * - `data`: Execution result with status ("success", "failure", "refund", "delayed") and transaction hashes
3254
- * - `error`: Error message if execution failed
3532
+ * - `success` (boolean): Whether the execution was successful
3533
+ * - `data` (SwidgeExecuteData | SuggestedTransactionData | undefined): Response data
3534
+ * - In auto mode: SwidgeExecuteData with status ("success", "failure", "refund", "delayed") and transaction hashes
3535
+ * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
3536
+ * - `error` (string | undefined): Error message if execution failed
3537
+ * - `errorMessage` (string | undefined): Detailed error message if execution failed
3255
3538
  *
3256
3539
  * @param quoteData - Complete quote object(s) from agent.swidge.quote()
3257
3540
  * @returns Promise resolving to SwidgeExecuteResponse with transaction status
3258
3541
  *
3259
3542
  * @example
3260
3543
  * ```typescript
3261
- * // Single execution
3544
+ * import { isSuggestedTransaction, isSwidgeExecuted } from "@circuitorg/agent-sdk";
3545
+ *
3546
+ * // Single execution with type guards
3262
3547
  * const quote = await agent.swidge.quote({...});
3263
3548
  * if (quote.success && quote.data) {
3264
3549
  * const result = await agent.swidge.execute(quote.data);
3550
+ *
3265
3551
  * if (result.success && result.data) {
3266
- * await agent.log(`Swap status: ${result.data.status}`);
3267
- * if (result.data.status === "success") {
3268
- * await agent.log(`Tx hash: ${result.data.out.txs[0]}`);
3552
+ * // Use type guard to check if transaction was suggested
3553
+ * if (isSuggestedTransaction(result)) {
3554
+ * await agent.log(`Swap suggested (ID: ${result.data.suggestionId})`);
3555
+ * } else if (isSwidgeExecuted(result.data)) {
3556
+ * await agent.log(`Swap status: ${result.data.status}`);
3557
+ * if (result.data.status === "success" && result.data.out?.txs) {
3558
+ * await agent.log(`Tx hash: ${result.data.out.txs[0]}`);
3559
+ * }
3269
3560
  * }
3561
+ * } else {
3562
+ * await agent.log(`Swap failed: ${result.errorMessage}`, { error: true });
3270
3563
  * }
3271
3564
  * }
3272
3565
  *
3273
3566
  * // Bulk execution
3274
3567
  * const results = await agent.swidge.execute([quote.data, quote2.data]);
3275
- * results.forEach((result, index) => {
3276
- * if (result.success && result.data) {
3568
+ * for (const [index, result] of results.entries()) {
3569
+ * if (result.success && result.data && isSwidgeExecuted(result.data)) {
3277
3570
  * console.log(`Swap ${index + 1} status: ${result.data.status}`);
3278
3571
  * }
3279
- * });
3572
+ * }
3280
3573
  * ```
3281
3574
  */
3282
3575
  execute: {
@@ -3333,6 +3626,41 @@ declare class AgentContext {
3333
3626
  * ```
3334
3627
  */
3335
3628
  transactions(): Promise<TransactionsResponse>;
3629
+ /**
3630
+ * Clear all pending suggested transactions for this session.
3631
+ *
3632
+ * This performs a soft delete by setting the `deletedAt` timestamp on all
3633
+ * unprocessed suggestions. Useful for clearing stale suggestions before
3634
+ * creating new ones or when the agent's strategy has changed.
3635
+ *
3636
+ * **Best Practice**: Call this at the start of your run() function when in
3637
+ * manual mode to ensure you're working with a clean slate.
3638
+ *
3639
+ * **Output**: `ClearSuggestionsResponse`
3640
+ * - `success` (boolean): Whether the operation succeeded
3641
+ * - `error` (string | undefined): Error message on failure
3642
+ * - `errorMessage` (string | undefined): Detailed error message on failure
3643
+ *
3644
+ * @returns Promise resolving to ClearSuggestionsResponse
3645
+ *
3646
+ * @example
3647
+ * ```typescript
3648
+ * async function run(agent: AgentContext): Promise<void> {
3649
+ * // Clear any stale suggestions from previous runs
3650
+ * await agent.clearSuggestedTransactions();
3651
+ *
3652
+ * // Now create fresh suggestions
3653
+ * await agent.signAndSend({...});
3654
+ * await agent.platforms.polymarket.marketOrder({...});
3655
+ * }
3656
+ *
3657
+ * async function unwind(agent: AgentContext): Promise<void> {
3658
+ * // Clear suggestions when stopping
3659
+ * await agent.clearSuggestedTransactions();
3660
+ * }
3661
+ * ```
3662
+ */
3663
+ clearSuggestedTransactions(): Promise<ClearSuggestionsResponse>;
3336
3664
  /**
3337
3665
  * Get current live positions for the session.
3338
3666
  *
@@ -3561,4 +3889,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
3561
3889
  */
3562
3890
  declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
3563
3891
 
3564
- export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, type EnrichedPosition, type HyperliquidBalancesResponse, type HyperliquidDeleteOrderResponse, type HyperliquidHistoricalOrdersResponse, type HyperliquidLiquidationsResponse, type HyperliquidOpenOrdersResponse, type HyperliquidOrderFillsResponse, type HyperliquidOrderResponse, type HyperliquidPlaceOrderRequest, type HyperliquidPlaceOrderResponse, type HyperliquidPositionsResponse, type HyperliquidTransferRequest, type HyperliquidTransferResponse, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, SwidgeExecuteRequestSchema, type SwidgeExecuteResponse, SwidgeExecuteResponseWrapperSchema, type SwidgeQuoteRequest, SwidgeQuoteRequestSchema, type SwidgeQuoteResponse, SwidgeQuoteResponseWrapperSchema, type SwidgeQuoteResult, type TransactionsResponse, type UnwindFunctionContract, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
3892
+ export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type ClearSuggestionsResponse, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, EMPTY_DATA, type EnrichedPosition, type EthereumAddress, type EthereumData, type ExecutionMode, type HyperliquidBalancesResponse, type HyperliquidDeleteOrderResponse, type HyperliquidHistoricalOrdersResponse, type HyperliquidLiquidationsResponse, type HyperliquidOpenOrdersResponse, type HyperliquidOrderFillsResponse, type HyperliquidOrderResponse, type HyperliquidPlaceOrderRequest, type HyperliquidPlaceOrderResponse, type HyperliquidPositionsResponse, type HyperliquidTransferRequest, type HyperliquidTransferResponse, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type SuggestedTransactionData, SwidgeExecuteRequestSchema, type SwidgeExecuteResponse, SwidgeExecuteResponseWrapperSchema, type SwidgeQuoteRequest, SwidgeQuoteRequestSchema, type SwidgeQuoteResponse, SwidgeQuoteResponseWrapperSchema, type SwidgeQuoteResult, type TransactionsResponse, type UnwindFunctionContract, getChainIdFromNetwork, isEthereumNetwork, isHyperliquidExecuted, isPolymarketExecuted, isSolanaNetwork, isSuccessResponse, isSuggestedTransaction, isSwidgeExecuted, isTransactionExecuted, type runFunctionContract };
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)}constructor(r){this.config=r;const e=this.isCircuitEnvironment(),t=e?"http://transaction-service.agent.internal":"https://agents.circuit.org";this.baseUrl=r.baseUrl||t,console.log("[Circuit SDK] Environment: "+(e?"Circuit (internal)":"Local (public)"),{CIRCUIT_ENVIRONMENT:process.env?.CIRCUIT_ENVIRONMENT??"not set",baseUrl:this.baseUrl}),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 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};console.log("[Circuit SDK] ========== OUTGOING REQUEST =========="),console.log(`[Circuit SDK] ${e.method||"GET"} ${s}`),console.log("[Circuit SDK] Headers:",JSON.stringify(t,null,2)),e.body&&console.log("[Circuit SDK] Body:",e.body),console.log("[Circuit SDK] Environment:",{CIRCUIT_ENVIRONMENT:process.env?.CIRCUIT_ENVIRONMENT??"NOT SET",CIRCUIT_AGENT_SLUG:process.env?.CIRCUIT_AGENT_SLUG??"NOT SET",isCircuitEnvironment:this.isCircuitEnvironment()}),console.log("[Circuit SDK] =====================================");try{const r=await fetch(s,i);if(clearTimeout(a),console.log("[Circuit SDK] ========== RESPONSE =========="),console.log(`[Circuit SDK] Status: ${r.status} ${r.statusText}`),console.log("[Circuit SDK] Response Headers:",Object.fromEntries(r.headers.entries())),!r.ok){const e=await r.text();console.log("[Circuit SDK] Error Body:",e),console.log("[Circuit SDK] ==============================");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}const e=await r.json();return console.log("[Circuit SDK] Success Body:",JSON.stringify(e).slice(0,500)),console.log("[Circuit SDK] =============================="),e}catch(e){if(clearTimeout(a),console.log("[Circuit SDK] ========== REQUEST ERROR =========="),console.log("[Circuit SDK] Error:",e),console.log("[Circuit SDK] ==================================="),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})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message});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,t=(await this.client.post(`/v1/transactions/evm/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.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,t=(await this.client.post(`/v1/transactions/solana/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.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{return await this.client.post("/v1/platforms/polymarket/market-order",r)}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{return await this.client.post("/v1/platforms/hyperliquid/order",r)}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}}}};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;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,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 getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),m=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p),unwindPositions:h.array(p).optional()}),f=(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,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",m),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",m),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",m),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 g}from"zod";var w=g.templateLiteral(["ethereum:",g.coerce.number().int().nonnegative()]),E=g.union([g.literal("solana"),w]),v=g.object({address:g.string(),network:E}),S=g.object({from:v,to:v,fromToken:g.string().optional(),toToken:g.string().optional(),amount:g.string(),slippage:g.string().optional()}),D=g.object({network:E,address:g.string(),token:g.string().nullable(),name:g.string().optional(),symbol:g.string().optional(),decimals:g.number().optional(),amount:g.string().optional(),minimumAmount:g.string().optional(),amountFormatted:g.string().optional(),amountUsd:g.string().optional()}),T=g.object({usd:g.string().optional(),percentage:g.string().optional()}),O=g.object({name:g.string(),amount:g.string().optional(),amountFormatted:g.string().optional(),amountUsd:g.string().optional()}),k=(g.object({programId:g.string(),keys:g.array(g.object({pubkey:g.string(),isSigner:g.boolean(),isWritable:g.boolean()})),data:g.union([g.string(),g.instanceof(Buffer)])}),g.object({type:g.literal("evm"),from:g.string().regex(/^0x[a-fA-F0-9]{40}$/),to:g.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:g.number(),value:g.string(),data:g.string().regex(/^0x[a-fA-F0-9]*$/),gas:g.number().nullish(),maxFeePerGas:g.number().nullish(),maxPriorityFeePerGas:g.number().nullish()})),F=g.object({type:g.literal("solana"),serializedTransaction:g.string()}),U=g.object({type:g.literal("transaction"),description:g.string(),transactionDetails:g.union([k,F])}),$=g.object({type:g.literal("signature"),description:g.string(),signatureData:g.string()}),b=g.discriminatedUnion("type",[U,$]),A=g.object({engine:g.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:D,assetReceive:D,priceImpact:T,fees:g.array(O),steps:g.array(b)}),C=A,M=g.object({network:g.string(),txs:g.array(g.string())}),q=g.object({status:g.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:M.optional(),out:M.optional(),lastUpdated:g.number(),error:g.string().optional()}),N={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"},I=r=>g.object({success:g.boolean(),data:r.optional(),error:g.string().optional(),errorMessage:g.string().optional(),errorDetails:g.object({message:g.string().optional(),error:g.string().optional(),status:g.number().optional(),statusText:g.string().optional()}).optional()}).passthrough(),K=I(A),P=I(q);export{e as APIClient,f as Agent,y as AgentContext,n as AgentSdk,N as QUOTE_RESULT,C as SwidgeExecuteRequestSchema,P as SwidgeExecuteResponseWrapperSchema,S as SwidgeQuoteRequestSchema,K as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
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,bypassManualApproval:r.bypassManualApproval??!1,expiresAt:r.expiresAt??null})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message,bypassManualApproval:r.bypassManualApproval??!1,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","hybrid"]).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","hybrid"]);var w="0x",E=(f.object({bypassManualApproval:f.boolean().optional().default(!1),expiresAt:f.string().datetime().optional().nullable().default(null)}),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 b(r){return"object"==typeof r&&null!==r&&"out"in r&&!("suggested"in r)}function k(r){return"object"==typeof r&&null!==r&&"orderInfo"in r&&!("suggested"in r)}function F(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 A}from"zod";var M=A.templateLiteral(["ethereum:",A.coerce.number().int().nonnegative()]),S=A.union([A.literal("solana"),M]),O=A.object({address:A.string(),network:S}),$=A.object({from:O,to:O,fromToken:A.string().optional(),toToken:A.string().optional(),amount:A.string(),slippage:A.string().optional()}),U=A.object({network:S,address:A.string(),token:A.string().nullable(),name:A.string().optional(),symbol:A.string().optional(),decimals:A.number().optional(),amount:A.string().optional(),minimumAmount:A.string().optional(),amountFormatted:A.string().optional(),amountUsd:A.string().optional()}),q=A.object({usd:A.string().optional(),percentage:A.string().optional()}),x=A.object({name:A.string(),amount:A.string().optional(),amountFormatted:A.string().optional(),amountUsd:A.string().optional()}),I=(A.object({programId:A.string(),keys:A.array(A.object({pubkey:A.string(),isSigner:A.boolean(),isWritable:A.boolean()})),data:A.union([A.string(),A.instanceof(Buffer)])}),A.object({type:A.literal("evm"),from:A.string().regex(/^0x[a-fA-F0-9]{40}$/),to:A.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:A.number(),value:A.string(),data:A.string().regex(/^0x[a-fA-F0-9]*$/),gas:A.number().nullish(),maxFeePerGas:A.number().nullish(),maxPriorityFeePerGas:A.number().nullish()})),P=A.object({type:A.literal("solana"),serializedTransaction:A.string()}),j=A.object({type:A.literal("transaction"),description:A.string(),transactionDetails:A.union([I,P])}),N=A.object({type:A.literal("signature"),description:A.string(),signatureData:A.string()}),H=A.discriminatedUnion("type",[j,N]),C=A.object({engine:A.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:U,assetReceive:U,priceImpact:q,fees:A.array(x),steps:A.array(H)}),_=C.extend({bypassManualApproval:A.boolean().optional().default(!1),expiresAt:A.string().datetime().optional().nullable().default(null)}),K=A.object({network:A.string(),txs:A.array(A.string())}),L=A.object({status:A.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:K.optional(),out:K.optional(),lastUpdated:A.number(),error:A.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=>A.object({success:A.boolean(),data:r.optional(),error:A.string().optional(),errorMessage:A.string().optional(),errorDetails:A.object({message:A.string().optional(),error:A.string().optional(),status:A.number().optional(),statusText:A.string().optional()}).optional()}).passthrough(),z=G(C),W=G(A.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,F as isHyperliquidExecuted,k as isPolymarketExecuted,s as isSolanaNetwork,D as isSuccessResponse,v as isSuggestedTransaction,b as isSwidgeExecuted,T as isTransactionExecuted};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.3.8",
3
+ "version": "1.3.9",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",