@circuitorg/agent-sdk 1.3.9 → 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 (4) hide show
  1. package/README.md +10 -8
  2. package/index.d.ts +40 -148
  3. package/index.js +1 -1
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -81,19 +81,21 @@ Every agent receives a single `AgentContext` object that provides:
81
81
  **Important:** `currentPositions` reflects your allocated assets at the **start** of each execution. To avoid failed transactions, you should be tracking intra-run position changes based on transactions the agent makes during the execution. Circuit will provide updated positions on the next execution request.
82
82
 
83
83
 
84
- #### Required Asset setup
85
- > Note: For native tokens, use the following null addresses for solana/ethereum
84
+ #### Starting Asset setup
85
+ > Note: For native tokens, use the canonical native token addresses:
86
+ > - EVM: `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` (EIP-7528)
87
+ > - Solana: `11111111111111111111111111111111` (System Program)
86
88
  ```toml
87
- // Requiring 1 SOL
88
- [[requiredAssets]]
89
+ # Requiring 1 SOL
90
+ [startingAsset]
89
91
  network = "solana"
90
92
  address = "11111111111111111111111111111111"
91
93
  minimumAmount = "1000000000"
92
94
 
93
- // Requiring 1 ETH
94
- [[requiredAssets]]
95
- network = "ethereum:<chainId>"
96
- address = "0x0000000000000000000000000000000000000000"
95
+ # Requiring 1 ETH
96
+ [startingAsset]
97
+ network = "ethereum:1"
98
+ address = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
97
99
  minimumAmount = "1000000000000000000"
98
100
  ```
99
101
 
package/index.d.ts CHANGED
@@ -18,16 +18,18 @@ 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
21
  /**
27
22
  * ISO 8601 timestamp for when the suggestion expires (only used in manual mode).
28
23
  * If not provided, the suggestion never expires.
29
24
  */
30
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;
31
33
  } & ({
32
34
  network: `ethereum:${number}`;
33
35
  request: {
@@ -56,13 +58,6 @@ declare const SignAndSendResponseSchema: z$1.ZodObject<{
56
58
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
57
59
  }, z$1.core.$strip>]>>;
58
60
  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
61
  }, z$1.core.$strip>;
67
62
  /**
68
63
  * Standard response from signAndSend operations (TypeScript type)
@@ -137,15 +132,6 @@ type SignMessageResponse = {
137
132
  data?: SignMessageData;
138
133
  /** Error category from API (only present on failure) */
139
134
  error?: string;
140
- /** Detailed error message from API (only present on failure) */
141
- errorMessage?: string;
142
- /** Detailed error information (only present on failure) */
143
- errorDetails?: {
144
- message?: string;
145
- error?: string;
146
- status?: number;
147
- statusText?: string;
148
- };
149
135
  };
150
136
  /**
151
137
  * Asset change representing a token transfer in a confirmed transaction
@@ -182,13 +168,6 @@ type TransactionsResponse = {
182
168
  data?: AssetChange[];
183
169
  /** Error message (only present on failure) */
184
170
  error?: string;
185
- /** Detailed error message (only present on failure) */
186
- errorMessage?: string;
187
- /** Detailed error information (only present on failure) */
188
- errorDetails?: {
189
- message?: string;
190
- status?: number;
191
- };
192
171
  };
193
172
  /**
194
173
  * Current position with optional Polymarket metadata enrichment
@@ -270,13 +249,6 @@ type CurrentPositionsResponse = {
270
249
  data?: CurrentPositionsData;
271
250
  /** Error message (only present on failure) */
272
251
  error?: string;
273
- /** Detailed error message (only present on failure) */
274
- errorMessage?: string;
275
- /** Detailed error information (only present on failure) */
276
- errorDetails?: {
277
- message?: string;
278
- status?: number;
279
- };
280
252
  };
281
253
 
282
254
  /**
@@ -306,8 +278,6 @@ type AgentLog = z$1.infer<typeof AgentLogSchema>;
306
278
  interface LogResponse {
307
279
  success: boolean;
308
280
  error?: string;
309
- errorMessage?: string;
310
- errorDetails?: object;
311
281
  }
312
282
 
313
283
  /**
@@ -404,9 +374,9 @@ declare const SwidgeQuoteDataSchema: z$1.ZodObject<{
404
374
  chainId: z$1.ZodNumber;
405
375
  value: z$1.ZodString;
406
376
  data: z$1.ZodString;
407
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
408
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
409
- 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>;
410
380
  }, z$1.core.$strip>, z$1.ZodObject<{
411
381
  type: z$1.ZodLiteral<"solana">;
412
382
  serializedTransaction: z$1.ZodString;
@@ -467,9 +437,9 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
467
437
  chainId: z$1.ZodNumber;
468
438
  value: z$1.ZodString;
469
439
  data: z$1.ZodString;
470
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
471
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
472
- 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>;
473
443
  }, z$1.core.$strip>, z$1.ZodObject<{
474
444
  type: z$1.ZodLiteral<"solana">;
475
445
  serializedTransaction: z$1.ZodString;
@@ -479,8 +449,8 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
479
449
  description: z$1.ZodString;
480
450
  signatureData: z$1.ZodString;
481
451
  }, z$1.core.$strip>], "type">>;
482
- bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
483
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>>;
484
454
  }, z$1.core.$strip>;
485
455
  /**
486
456
  * Quote result constants - type QUOTE_RESULT. to see available options
@@ -550,9 +520,9 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
550
520
  chainId: z$1.ZodNumber;
551
521
  value: z$1.ZodString;
552
522
  data: z$1.ZodString;
553
- gas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
554
- maxFeePerGas: z$1.ZodOptional<z$1.ZodNullable<z$1.ZodNumber>>;
555
- 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>;
556
526
  }, z$1.core.$strip>, z$1.ZodObject<{
557
527
  type: z$1.ZodLiteral<"solana">;
558
528
  serializedTransaction: z$1.ZodString;
@@ -564,13 +534,6 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
564
534
  }, z$1.core.$strip>], "type">>;
565
535
  }, z$1.core.$strip>>;
566
536
  error: z$1.ZodOptional<z$1.ZodString>;
567
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
568
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
569
- message: z$1.ZodOptional<z$1.ZodString>;
570
- error: z$1.ZodOptional<z$1.ZodString>;
571
- status: z$1.ZodOptional<z$1.ZodNumber>;
572
- statusText: z$1.ZodOptional<z$1.ZodString>;
573
- }, z$1.core.$strip>>;
574
537
  }, z$1.core.$loose>;
575
538
  /**
576
539
  * Swidge execute response wrapper with union type for manual mode support
@@ -595,13 +558,6 @@ declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
595
558
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
596
559
  }, z$1.core.$strip>]>>;
597
560
  error: z$1.ZodOptional<z$1.ZodString>;
598
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
599
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
600
- message: z$1.ZodOptional<z$1.ZodString>;
601
- error: z$1.ZodOptional<z$1.ZodString>;
602
- status: z$1.ZodOptional<z$1.ZodNumber>;
603
- statusText: z$1.ZodOptional<z$1.ZodString>;
604
- }, z$1.core.$strip>>;
605
561
  }, z$1.core.$loose>;
606
562
  type SwidgeQuoteData = z$1.infer<typeof SwidgeQuoteDataSchema>;
607
563
  type SwidgeQuoteResponse = z$1.infer<typeof SwidgeQuoteResponseWrapperSchema>;
@@ -615,11 +571,12 @@ declare const PolymarketMarketOrderRequestSchema: z$1.ZodObject<{
615
571
  BUY: "BUY";
616
572
  SELL: "SELL";
617
573
  }>;
618
- bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
619
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>>;
620
576
  }, z$1.core.$strip>;
621
577
  declare const PolymarketRedeemPositionsRequestSchema: z$1.ZodObject<{
622
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>>;
623
580
  }, z$1.core.$strip>;
624
581
  /**
625
582
  * Polymarket market order response with union type for manual mode support
@@ -642,13 +599,6 @@ declare const PolymarketMarketOrderResponseSchema: z$1.ZodObject<{
642
599
  details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
643
600
  }, z$1.core.$strip>]>>;
644
601
  error: z$1.ZodOptional<z$1.ZodString>;
645
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
646
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
647
- message: z$1.ZodOptional<z$1.ZodString>;
648
- error: z$1.ZodOptional<z$1.ZodString>;
649
- status: z$1.ZodOptional<z$1.ZodNumber>;
650
- statusText: z$1.ZodOptional<z$1.ZodString>;
651
- }, z$1.core.$strip>>;
652
602
  }, z$1.core.$loose>;
653
603
  declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
654
604
  success: z$1.ZodBoolean;
@@ -679,13 +629,6 @@ declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
679
629
  transactionHash: z$1.ZodNullable<z$1.ZodString>;
680
630
  }, z$1.core.$strip>>>;
681
631
  error: z$1.ZodOptional<z$1.ZodString>;
682
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
683
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
684
- message: z$1.ZodOptional<z$1.ZodString>;
685
- error: z$1.ZodOptional<z$1.ZodString>;
686
- status: z$1.ZodOptional<z$1.ZodNumber>;
687
- statusText: z$1.ZodOptional<z$1.ZodString>;
688
- }, z$1.core.$strip>>;
689
632
  }, z$1.core.$loose>;
690
633
  type PolymarketMarketOrderRequest = z$1.input<typeof PolymarketMarketOrderRequestSchema>;
691
634
  type PolymarketRedeemPositionsRequest = z$1.infer<typeof PolymarketRedeemPositionsRequestSchema>;
@@ -716,8 +659,8 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
716
659
  triggerPrice: z$1.ZodOptional<z$1.ZodNumber>;
717
660
  reduceOnly: z$1.ZodOptional<z$1.ZodBoolean>;
718
661
  postOnly: z$1.ZodOptional<z$1.ZodBoolean>;
719
- bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
720
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>>;
721
664
  }, z$1.core.$strip>;
722
665
  /**
723
666
  * Request to transfer between spot and perp accounts on Hyperliquid
@@ -725,8 +668,8 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
725
668
  declare const HyperliquidTransferRequestSchema: z$1.ZodObject<{
726
669
  amount: z$1.ZodNumber;
727
670
  toPerp: z$1.ZodBoolean;
728
- bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
729
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>>;
730
673
  }, z$1.core.$strip>;
731
674
  /**
732
675
  * Hyperliquid place order response with union type for manual mode support
@@ -898,13 +841,6 @@ declare const MemorySetResponseSchema: z$1.ZodObject<{
898
841
  key: z$1.ZodString;
899
842
  }, z$1.core.$strip>>;
900
843
  error: z$1.ZodOptional<z$1.ZodString>;
901
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
902
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
903
- message: z$1.ZodOptional<z$1.ZodString>;
904
- error: z$1.ZodOptional<z$1.ZodString>;
905
- status: z$1.ZodOptional<z$1.ZodNumber>;
906
- statusText: z$1.ZodOptional<z$1.ZodString>;
907
- }, z$1.core.$strip>>;
908
844
  }, z$1.core.$loose>;
909
845
  /**
910
846
  * Memory get response wrapper
@@ -916,13 +852,6 @@ declare const MemoryGetResponseSchema: z$1.ZodObject<{
916
852
  value: z$1.ZodString;
917
853
  }, z$1.core.$strip>>;
918
854
  error: z$1.ZodOptional<z$1.ZodString>;
919
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
920
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
921
- message: z$1.ZodOptional<z$1.ZodString>;
922
- error: z$1.ZodOptional<z$1.ZodString>;
923
- status: z$1.ZodOptional<z$1.ZodNumber>;
924
- statusText: z$1.ZodOptional<z$1.ZodString>;
925
- }, z$1.core.$strip>>;
926
855
  }, z$1.core.$loose>;
927
856
  /**
928
857
  * Memory delete response wrapper
@@ -933,13 +862,6 @@ declare const MemoryDeleteResponseSchema: z$1.ZodObject<{
933
862
  key: z$1.ZodString;
934
863
  }, z$1.core.$strip>>;
935
864
  error: z$1.ZodOptional<z$1.ZodString>;
936
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
937
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
938
- message: z$1.ZodOptional<z$1.ZodString>;
939
- error: z$1.ZodOptional<z$1.ZodString>;
940
- status: z$1.ZodOptional<z$1.ZodNumber>;
941
- statusText: z$1.ZodOptional<z$1.ZodString>;
942
- }, z$1.core.$strip>>;
943
865
  }, z$1.core.$loose>;
944
866
  /**
945
867
  * Memory list response wrapper
@@ -951,13 +873,6 @@ declare const MemoryListResponseSchema: z$1.ZodObject<{
951
873
  count: z$1.ZodNumber;
952
874
  }, z$1.core.$strip>>;
953
875
  error: z$1.ZodOptional<z$1.ZodString>;
954
- errorMessage: z$1.ZodOptional<z$1.ZodString>;
955
- errorDetails: z$1.ZodOptional<z$1.ZodObject<{
956
- message: z$1.ZodOptional<z$1.ZodString>;
957
- error: z$1.ZodOptional<z$1.ZodString>;
958
- status: z$1.ZodOptional<z$1.ZodNumber>;
959
- statusText: z$1.ZodOptional<z$1.ZodString>;
960
- }, z$1.core.$strip>>;
961
876
  }, z$1.core.$loose>;
962
877
  type MemorySetResponse = z$1.infer<typeof MemorySetResponseSchema>;
963
878
  type MemoryGetResponse = z$1.infer<typeof MemoryGetResponseSchema>;
@@ -975,9 +890,8 @@ type MemoryListResponse = z$1.infer<typeof MemoryListResponseSchema>;
975
890
  * Execution mode for agent sessions
976
891
  * - "auto": Transactions execute immediately (default behavior)
977
892
  * - "manual": Transactions are stored as suggestions for user approval
978
- * - "hybrid": Reserved for future use
979
893
  */
980
- type ExecutionMode = "auto" | "manual" | "hybrid";
894
+ type ExecutionMode = "auto" | "manual";
981
895
  /**
982
896
  * Empty data constant for Ethereum transactions.
983
897
  * Use this for simple transfers without any contract interaction.
@@ -1053,7 +967,6 @@ declare function isSuccessResponse<T>(response: {
1053
967
  success: boolean;
1054
968
  data?: T;
1055
969
  error?: string;
1056
- errorMessage?: string;
1057
970
  }): response is {
1058
971
  success: true;
1059
972
  data: T;
@@ -1143,7 +1056,6 @@ declare function isTransactionExecuted(data: unknown): data is {
1143
1056
  interface ClearSuggestionsResponse {
1144
1057
  success: boolean;
1145
1058
  error?: string;
1146
- errorMessage?: string;
1147
1059
  }
1148
1060
 
1149
1061
  /**
@@ -1231,7 +1143,7 @@ declare class AgentSdk {
1231
1143
  * - `enforceTransactionSuccess`: Enforce transaction success (optional)
1232
1144
  * - For Solana: `{ hexTransaction }`
1233
1145
  * - `hexTransaction`: Serialized `VersionedTransaction` as hex string
1234
- * @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
1235
1147
  * @example
1236
1148
  * ```ts
1237
1149
  * // Ethereum (Arbitrum) native transfer
@@ -1362,7 +1274,6 @@ declare class AgentSdk {
1362
1274
  * - `steps`: Transaction steps required to complete the swap
1363
1275
  * - `priceImpact`: Calculated price impact percentage
1364
1276
  * - `error` (string | undefined): Error message if quote failed
1365
- * - `errorDetails` (object | undefined): Detailed error information
1366
1277
  *
1367
1278
  * @example
1368
1279
  * ```ts
@@ -1423,7 +1334,6 @@ declare class AgentSdk {
1423
1334
  * - `out`: Destination transaction details with txs array (transaction hashes)
1424
1335
  * - Additional metadata about the swap/bridge operation
1425
1336
  * - `error` (string | undefined): Error message if execution failed
1426
- * - `errorDetails` (object | undefined): Detailed error information
1427
1337
  *
1428
1338
  * @example
1429
1339
  * ```ts
@@ -1508,7 +1418,6 @@ declare class AgentSdk {
1508
1418
  * - `data` (object | undefined): Present on success
1509
1419
  * - `key` (string): The key that was set
1510
1420
  * - `error` (string | undefined): Error message on failure
1511
- * - `errorDetails` (object | undefined): Detailed error info on failure
1512
1421
  */
1513
1422
  set: (key: string, value: string) => Promise<MemorySetResponse>;
1514
1423
  /**
@@ -1517,7 +1426,7 @@ declare class AgentSdk {
1517
1426
  * Retrieve a previously stored value. Returns an error if the key doesn't exist.
1518
1427
  *
1519
1428
  * @param key The key to retrieve
1520
- * @returns Promise with the key and its value, or error details
1429
+ * @returns Promise with the key and its value, or error
1521
1430
  *
1522
1431
  * @example
1523
1432
  * ```ts
@@ -1539,7 +1448,6 @@ declare class AgentSdk {
1539
1448
  * - `key` (string): The requested key
1540
1449
  * - `value` (string): The stored value
1541
1450
  * - `error` (string | undefined): Error message (e.g., "Key not found")
1542
- * - `errorDetails` (object | undefined): Detailed error info on failure
1543
1451
  */
1544
1452
  get: (key: string) => Promise<MemoryGetResponse>;
1545
1453
  /**
@@ -1567,7 +1475,6 @@ declare class AgentSdk {
1567
1475
  * - `data` (object | undefined): Present on success
1568
1476
  * - `key` (string): The key that was deleted
1569
1477
  * - `error` (string | undefined): Error message on failure
1570
- * - `errorDetails` (object | undefined): Detailed error info on failure
1571
1478
  */
1572
1479
  delete: (key: string) => Promise<MemoryDeleteResponse>;
1573
1480
  /**
@@ -1597,7 +1504,6 @@ declare class AgentSdk {
1597
1504
  * - `keys` (string[]): Array of all stored keys
1598
1505
  * - `count` (number): Number of keys
1599
1506
  * - `error` (string | undefined): Error message on failure
1600
- * - `errorDetails` (object | undefined): Detailed error info on failure
1601
1507
  */
1602
1508
  list: () => Promise<MemoryListResponse>;
1603
1509
  };
@@ -1641,7 +1547,6 @@ declare class AgentSdk {
1641
1547
  * - `totalPriceUsd` (string): Total order value in USD
1642
1548
  * - `txHashes` (string[]): List of transaction hashes
1643
1549
  * - `error` (string | undefined): Error message (only present on failure)
1644
- * - `errorDetails` (object | undefined): Detailed error info
1645
1550
  *
1646
1551
  * **Key Functionality**:
1647
1552
  * - Automatic approval handling for token spending
@@ -1694,8 +1599,7 @@ declare class AgentSdk {
1694
1599
  * ```json
1695
1600
  * {
1696
1601
  * "success": false,
1697
- * "error": "Could not get order",
1698
- * "errorDetails": { "message": "Invalid request", "status": 400 }
1602
+ * "error": "Could not get order"
1699
1603
  * }
1700
1604
  * ```
1701
1605
  */
@@ -1716,7 +1620,6 @@ declare class AgentSdk {
1716
1620
  * - `position` (PolymarketPosition | null): Position that was redeemed (full position details, null for unwrap collateral)
1717
1621
  * - `transactionHash` (string | null): Transaction hash (null if redemption failed)
1718
1622
  * - `error` (string | undefined): Error message (only present on failure)
1719
- * - `errorDetails` (object | undefined): Detailed error info
1720
1623
  *
1721
1624
  * **Key Functionality**:
1722
1625
  * - Automatic detection of redeemable positions
@@ -1791,8 +1694,7 @@ declare class AgentSdk {
1791
1694
  * {
1792
1695
  * "success": false,
1793
1696
  * "data": undefined,
1794
- * "error": "Could not get positions",
1795
- * "errorDetails": { "message": "No redeemable positions", "status": 404 }
1697
+ * "error": "Could not get positions"
1796
1698
  * }
1797
1699
  * ```
1798
1700
  */
@@ -2193,6 +2095,12 @@ declare class AgentSdk {
2193
2095
  liquidations: (startTime?: number) => Promise<HyperliquidLiquidationsResponse>;
2194
2096
  };
2195
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;
2196
2104
  /**
2197
2105
  * Handle EVM transaction signing and broadcasting
2198
2106
  */
@@ -2300,7 +2208,6 @@ declare class AgentSdk {
2300
2208
  * - `tokenUsdPrice` (string | null): Token price in USD at time of transaction
2301
2209
  * - `timestamp` (string): Transaction timestamp
2302
2210
  * - `error` (string | undefined): Error message on failure
2303
- * - `errorMessage` (string | undefined): Detailed error message on failure
2304
2211
  *
2305
2212
  * @returns Promise resolving to TransactionsResponse with array of asset changes
2306
2213
  *
@@ -2353,7 +2260,6 @@ declare class AgentSdk {
2353
2260
  * - Plus additional market details
2354
2261
  * - `hasPendingTxs` (boolean): Whether there are pending transactions
2355
2262
  * - `error` (string | undefined): Error message on failure
2356
- * - `errorMessage` (string | undefined): Detailed error message on failure
2357
2263
  *
2358
2264
  * @returns Promise resolving to CurrentPositionsResponse with enriched positions
2359
2265
  *
@@ -2601,7 +2507,6 @@ declare class AgentContext {
2601
2507
  * Execution mode for this session.
2602
2508
  * - "auto": Transactions execute immediately (default behavior)
2603
2509
  * - "manual": Transactions are stored as suggestions for user approval
2604
- * - "hybrid": Reserved for future use
2605
2510
  */
2606
2511
  readonly executionMode: ExecutionMode;
2607
2512
  /** Internal SDK instance */
@@ -2723,7 +2628,6 @@ declare class AgentContext {
2723
2628
  * **Input**: `SignAndSendRequest`
2724
2629
  * - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
2725
2630
  * - `message` (string | undefined): Optional context message
2726
- * - `bypassManualApproval` (boolean | undefined): Force execution even in manual mode
2727
2631
  * - `expiresAt` (string | null | undefined): ISO 8601 timestamp for suggestion expiry
2728
2632
  * - `request` (object): Transaction payload
2729
2633
  * - For Ethereum:
@@ -2742,10 +2646,8 @@ declare class AgentContext {
2742
2646
  * - `success` (boolean): Whether the operation succeeded
2743
2647
  * - `data` (SignAndSendData | SuggestedTransactionData | undefined): Response data
2744
2648
  * - In auto mode: SignAndSendData with txHash, transactionUrl, etc.
2745
- * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
2649
+ * - In manual mode: SuggestedTransactionData with suggestionId and details
2746
2650
  * - `error` (string | undefined): Error message on failure
2747
- * - `errorMessage` (string | undefined): Detailed error message on failure
2748
- * - `errorDetails` (object | undefined): Detailed error info
2749
2651
  *
2750
2652
  * @param request - Transaction request with network and transaction details
2751
2653
  * @returns Promise resolving to SignAndSendResponse
@@ -2989,16 +2891,14 @@ declare class AgentContext {
2989
2891
  * - `tokenId` (string): Market token ID for the position
2990
2892
  * - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
2991
2893
  * - `side` ("BUY" | "SELL"): Order side
2992
- * - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
2993
2894
  * - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
2994
2895
  *
2995
2896
  * **Output**: `PolymarketMarketOrderResponse`
2996
2897
  * - `success` (boolean): Whether the operation was successful
2997
2898
  * - `data` (PolymarketMarketOrderData | SuggestedTransactionData | undefined): Response data
2998
2899
  * - In auto mode: PolymarketMarketOrderData with orderInfo (orderId, side, priceUsd, txHashes)
2999
- * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
2900
+ * - In manual mode: SuggestedTransactionData with suggestionId and details
3000
2901
  * - `error` (string | undefined): Error message on failure
3001
- * - `errorMessage` (string | undefined): Detailed error message on failure
3002
2902
  *
3003
2903
  * @param request - Order parameters (tokenId, size, side)
3004
2904
  * @returns Promise resolving to PolymarketMarketOrderResponse with order details or suggestion
@@ -3022,7 +2922,7 @@ declare class AgentContext {
3022
2922
  * await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
3023
2923
  * }
3024
2924
  * } else {
3025
- * await agent.log(`Order failed: ${buyResult.errorMessage}`, { error: true });
2925
+ * await agent.log(`Order failed: ${buyResult.error}`, { error: true });
3026
2926
  * }
3027
2927
  *
3028
2928
  * // SELL order - size is number of shares
@@ -3092,16 +2992,14 @@ declare class AgentContext {
3092
2992
  * - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
3093
2993
  * - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
3094
2994
  * - `postOnly` (boolean, optional): Whether this is a post-only order
3095
- * - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
3096
2995
  * - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
3097
2996
  *
3098
2997
  * **Output**: `HyperliquidPlaceOrderResponse`
3099
2998
  * - `success` (boolean): Whether the operation was successful
3100
2999
  * - `data` (HyperliquidOrderInfo | SuggestedTransactionData | undefined): Response data
3101
3000
  * - 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
3001
+ * - In manual mode: SuggestedTransactionData with suggestionId and details
3103
3002
  * - `error` (string | undefined): Error message (only present on failure)
3104
- * - `errorMessage` (string | undefined): Detailed error message (only present on failure)
3105
3003
  *
3106
3004
  * @param request - Order parameters
3107
3005
  * @returns Promise resolving to HyperliquidPlaceOrderResponse
@@ -3128,7 +3026,7 @@ declare class AgentContext {
3128
3026
  * await agent.log(`Status: ${result.data.status}`);
3129
3027
  * }
3130
3028
  * } else {
3131
- * await agent.log(`Order failed: ${result.errorMessage}`, { error: true });
3029
+ * await agent.log(`Order failed: ${result.error}`, { error: true });
3132
3030
  * }
3133
3031
  *
3134
3032
  * // Limit order
@@ -3532,9 +3430,8 @@ declare class AgentContext {
3532
3430
  * - `success` (boolean): Whether the execution was successful
3533
3431
  * - `data` (SwidgeExecuteData | SuggestedTransactionData | undefined): Response data
3534
3432
  * - In auto mode: SwidgeExecuteData with status ("success", "failure", "refund", "delayed") and transaction hashes
3535
- * - In manual mode (without bypass): SuggestedTransactionData with suggestionId and details
3433
+ * - In manual mode: SuggestedTransactionData with suggestionId and details
3536
3434
  * - `error` (string | undefined): Error message if execution failed
3537
- * - `errorMessage` (string | undefined): Detailed error message if execution failed
3538
3435
  *
3539
3436
  * @param quoteData - Complete quote object(s) from agent.swidge.quote()
3540
3437
  * @returns Promise resolving to SwidgeExecuteResponse with transaction status
@@ -3559,7 +3456,7 @@ declare class AgentContext {
3559
3456
  * }
3560
3457
  * }
3561
3458
  * } else {
3562
- * await agent.log(`Swap failed: ${result.errorMessage}`, { error: true });
3459
+ * await agent.log(`Swap failed: ${result.error}`, { error: true });
3563
3460
  * }
3564
3461
  * }
3565
3462
  *
@@ -3598,7 +3495,6 @@ declare class AgentContext {
3598
3495
  * - `tokenUsdPrice` (string | null): Token price in USD at time of transaction
3599
3496
  * - `timestamp` (string): Transaction timestamp
3600
3497
  * - `error` (string | undefined): Error message on failure
3601
- * - `errorMessage` (string | undefined): Detailed error message on failure
3602
3498
  *
3603
3499
  * @returns Promise resolving to TransactionsResponse with asset changes
3604
3500
  *
@@ -3639,7 +3535,6 @@ declare class AgentContext {
3639
3535
  * **Output**: `ClearSuggestionsResponse`
3640
3536
  * - `success` (boolean): Whether the operation succeeded
3641
3537
  * - `error` (string | undefined): Error message on failure
3642
- * - `errorMessage` (string | undefined): Detailed error message on failure
3643
3538
  *
3644
3539
  * @returns Promise resolving to ClearSuggestionsResponse
3645
3540
  *
@@ -3691,7 +3586,6 @@ declare class AgentContext {
3691
3586
  * - `endDate` (string): Market end date
3692
3587
  * - Plus additional market details
3693
3588
  * - `error` (string | undefined): Error message on failure
3694
- * - `errorMessage` (string | undefined): Detailed error message on failure
3695
3589
  *
3696
3590
  * @returns Promise resolving to CurrentPositionsResponse with enriched positions
3697
3591
  *
@@ -3805,7 +3699,6 @@ interface AgentConfig {
3805
3699
  *
3806
3700
  * Exposes the following endpoints:
3807
3701
  * - `POST /run` — required, calls your execution function
3808
- * - `POST /execute` — backward compatibility, maps to run function
3809
3702
  * - `POST /unwind` — optional, uses provided or default unwind function
3810
3703
  * - `GET /health` — always available, uses default health check
3811
3704
  */
@@ -3850,14 +3743,13 @@ declare class Agent {
3850
3743
  */
3851
3744
  private updateJobStatus;
3852
3745
  private setupRoutes;
3853
- private getPortFromPackageJson;
3854
3746
  /**
3855
3747
  * Start a local HTTP server for development and testing.
3856
3748
  *
3857
3749
  * This method is used for local development and testing with the Circuit CLI.
3858
3750
  * For Lambda deployment, use `getExport()` instead.
3859
3751
  *
3860
- * @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)
3861
3753
  */
3862
3754
  run(port?: number): Promise<void>;
3863
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,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};
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.9",
3
+ "version": "1.4.0",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",