@circuitorg/agent-sdk 1.2.4 → 1.3.3

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 +32 -8
  2. package/index.d.ts +115 -182
  3. package/index.js +1 -1
  4. package/package.json +13 -13
package/README.md CHANGED
@@ -24,7 +24,7 @@ A simplified TypeScript SDK for building automated agents to deploy on Circuit.
24
24
  - [📈 Polymarket Prediction Markets](#-polymarket-prediction-markets)
25
25
  - [Place Market Orders](#place-market-orders)
26
26
  - [Redeem Positions](#redeem-positions)
27
- - [Hyperliquid Perpetuals Trading](#hyperliquid-perpetuals-trading)
27
+ - [Hyperliquid Trading](#hyperliquid-trading)
28
28
  - [Account Information](#account-information)
29
29
  - [Place Orders](#place-orders)
30
30
  - [Order Management](#order-management)
@@ -333,9 +333,17 @@ async function stop(agent: AgentContext): Promise<void> {
333
333
  }
334
334
  ```
335
335
 
336
- ## Hyperliquid Perpetuals Trading
336
+ ## Hyperliquid Trading
337
337
 
338
- Trade perpetual futures on Hyperliquid DEX with leverage.
338
+ Trade perpetual futures (with leverage) and spot markets on Hyperliquid DEX.
339
+
340
+ **Market Types:**
341
+ - **Perp**: Perpetual futures trading with leverage (use `market: "perp"` in order parameters)
342
+ - **Spot**: Spot trading (use `market: "spot"` in order parameters)
343
+
344
+ **Asset Naming for Spot:**
345
+ - Non-Hypercore-native assets use "Unit" prefix: `UBTC` (Unit BTC), `UETH` (Unit ETH)
346
+ - Example: To trade BTC spot, use symbol `UBTC-USDC`
339
347
 
340
348
  ### Account Information
341
349
 
@@ -363,8 +371,8 @@ async function run(agent: AgentContext): Promise<void> {
363
371
 
364
372
  ```typescript
365
373
  async function run(agent: AgentContext): Promise<void> {
366
- // Market order
367
- const order = await agent.platforms.hyperliquid.placeOrder({
374
+ // Perp market order
375
+ const perpOrder = await agent.platforms.hyperliquid.placeOrder({
368
376
  symbol: "BTC-USD",
369
377
  side: "buy",
370
378
  size: 0.0001,
@@ -373,10 +381,26 @@ async function run(agent: AgentContext): Promise<void> {
373
381
  type: "market"
374
382
  });
375
383
 
376
- if (order.success && order.data) {
377
- await agent.log(`Order ${order.data.orderId}: ${order.data.status}`);
384
+ if (perpOrder.success && perpOrder.data) {
385
+ await agent.log(`Perp Order ${perpOrder.data.orderId}: ${perpOrder.data.status}`);
386
+ } else {
387
+ await agent.log(perpOrder.error, { error: true });
388
+ }
389
+
390
+ // Spot market order (for non-Hypercore-native assets like BTC)
391
+ const spotOrder = await agent.platforms.hyperliquid.placeOrder({
392
+ symbol: "UBTC-USDC", // Unit BTC
393
+ side: "buy",
394
+ size: 0.0001,
395
+ price: 110000,
396
+ market: "spot", // Changed to spot
397
+ type: "market"
398
+ });
399
+
400
+ if (spotOrder.success && spotOrder.data) {
401
+ await agent.log(`Spot Order ${spotOrder.data.orderId}: ${spotOrder.data.status}`);
378
402
  } else {
379
- await agent.log(order.error, { error: true });
403
+ await agent.log(spotOrder.error, { error: true });
380
404
  }
381
405
  }
382
406
  ```
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import * as hono from 'hono';
2
3
 
3
4
  /**
4
5
  * Network type definitions
@@ -116,8 +117,8 @@ type SignMessageData = {
116
117
  s: string;
117
118
  /** Formatted signature string */
118
119
  formattedSignature: string;
119
- /** Signature type */
120
- type: "evm";
120
+ /** Signature type. Expected: 'evm' */
121
+ type: string;
121
122
  };
122
123
  /**
123
124
  * Standard response from signMessage operations
@@ -286,14 +287,14 @@ declare const AgentLogSchema: z.ZodObject<{
286
287
  reflect: "reflect";
287
288
  warning: "warning";
288
289
  }>;
289
- shortMessage: z.ZodString;
290
+ message: z.ZodString;
290
291
  }, z.core.$strip>;
291
292
  type AgentLog = z.infer<typeof AgentLogSchema>;
292
293
  /**
293
294
  * Response from agent.log() method
294
295
  *
295
296
  * The log method accepts strings, objects, or arrays and pretty-prints them to console.
296
- * Objects and arrays are serialized to JSON for backend (truncated to 250 chars).
297
+ * Objects and arrays are serialized to JSON for backend.
297
298
  */
298
299
  interface LogResponse {
299
300
  success: boolean;
@@ -351,7 +352,7 @@ declare const SwidgeQuoteRequestSchema: z.ZodObject<{
351
352
  }, z.core.$strip>;
352
353
  type SwidgeQuoteRequest = z.infer<typeof SwidgeQuoteRequestSchema>;
353
354
  declare const SwidgeQuoteDataSchema: z.ZodObject<{
354
- engine: z.ZodLiteral<"relay">;
355
+ engine: z.ZodString;
355
356
  assetSend: z.ZodObject<{
356
357
  network: z.ZodUnion<readonly [z.ZodLiteral<"solana">, z.ZodTemplateLiteral<`ethereum:${number}`>]>;
357
358
  address: z.ZodString;
@@ -394,37 +395,26 @@ declare const SwidgeQuoteDataSchema: z.ZodObject<{
394
395
  from: z.ZodString;
395
396
  to: z.ZodString;
396
397
  chainId: z.ZodNumber;
397
- value: z.ZodNumber;
398
+ value: z.ZodString;
398
399
  data: z.ZodString;
399
400
  gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
400
401
  maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
401
402
  maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
402
403
  }, z.core.$strip>, z.ZodObject<{
403
404
  type: z.ZodLiteral<"solana">;
404
- instructions: z.ZodArray<z.ZodObject<{
405
- programId: z.ZodString;
406
- keys: z.ZodArray<z.ZodObject<{
407
- pubkey: z.ZodString;
408
- isSigner: z.ZodBoolean;
409
- isWritable: z.ZodBoolean;
410
- }, z.core.$strip>>;
411
- data: z.ZodUnion<readonly [z.ZodString, z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>]>;
412
- }, z.core.$strip>>;
413
- addressLookupTableAddresses: z.ZodArray<z.ZodString>;
405
+ serializedTransaction: z.ZodString;
414
406
  }, z.core.$strip>]>;
415
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
416
407
  }, z.core.$strip>, z.ZodObject<{
417
408
  type: z.ZodLiteral<"signature">;
418
409
  description: z.ZodString;
419
410
  signatureData: z.ZodString;
420
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
421
411
  }, z.core.$strip>], "type">>;
422
412
  }, z.core.$strip>;
423
413
  /**
424
414
  * Execute request schema - takes the complete quote response from quote() method
425
415
  */
426
416
  declare const SwidgeExecuteRequestSchema: z.ZodObject<{
427
- engine: z.ZodLiteral<"relay">;
417
+ engine: z.ZodString;
428
418
  assetSend: z.ZodObject<{
429
419
  network: z.ZodUnion<readonly [z.ZodLiteral<"solana">, z.ZodTemplateLiteral<`ethereum:${number}`>]>;
430
420
  address: z.ZodString;
@@ -467,30 +457,19 @@ declare const SwidgeExecuteRequestSchema: z.ZodObject<{
467
457
  from: z.ZodString;
468
458
  to: z.ZodString;
469
459
  chainId: z.ZodNumber;
470
- value: z.ZodNumber;
460
+ value: z.ZodString;
471
461
  data: z.ZodString;
472
462
  gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
473
463
  maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
474
464
  maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
475
465
  }, z.core.$strip>, z.ZodObject<{
476
466
  type: z.ZodLiteral<"solana">;
477
- instructions: z.ZodArray<z.ZodObject<{
478
- programId: z.ZodString;
479
- keys: z.ZodArray<z.ZodObject<{
480
- pubkey: z.ZodString;
481
- isSigner: z.ZodBoolean;
482
- isWritable: z.ZodBoolean;
483
- }, z.core.$strip>>;
484
- data: z.ZodUnion<readonly [z.ZodString, z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>]>;
485
- }, z.core.$strip>>;
486
- addressLookupTableAddresses: z.ZodArray<z.ZodString>;
467
+ serializedTransaction: z.ZodString;
487
468
  }, z.core.$strip>]>;
488
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
489
469
  }, z.core.$strip>, z.ZodObject<{
490
470
  type: z.ZodLiteral<"signature">;
491
471
  description: z.ZodString;
492
472
  signatureData: z.ZodString;
493
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
494
473
  }, z.core.$strip>], "type">>;
495
474
  }, z.core.$strip>;
496
475
  /**
@@ -516,7 +495,7 @@ type SwidgeQuoteResult = (typeof QUOTE_RESULT)[keyof typeof QUOTE_RESULT];
516
495
  declare const SwidgeQuoteResponseWrapperSchema: z.ZodObject<{
517
496
  success: z.ZodBoolean;
518
497
  data: z.ZodOptional<z.ZodObject<{
519
- engine: z.ZodLiteral<"relay">;
498
+ engine: z.ZodString;
520
499
  assetSend: z.ZodObject<{
521
500
  network: z.ZodUnion<readonly [z.ZodLiteral<"solana">, z.ZodTemplateLiteral<`ethereum:${number}`>]>;
522
501
  address: z.ZodString;
@@ -559,30 +538,19 @@ declare const SwidgeQuoteResponseWrapperSchema: z.ZodObject<{
559
538
  from: z.ZodString;
560
539
  to: z.ZodString;
561
540
  chainId: z.ZodNumber;
562
- value: z.ZodNumber;
541
+ value: z.ZodString;
563
542
  data: z.ZodString;
564
543
  gas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
565
544
  maxFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
566
545
  maxPriorityFeePerGas: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
567
546
  }, z.core.$strip>, z.ZodObject<{
568
547
  type: z.ZodLiteral<"solana">;
569
- instructions: z.ZodArray<z.ZodObject<{
570
- programId: z.ZodString;
571
- keys: z.ZodArray<z.ZodObject<{
572
- pubkey: z.ZodString;
573
- isSigner: z.ZodBoolean;
574
- isWritable: z.ZodBoolean;
575
- }, z.core.$strip>>;
576
- data: z.ZodUnion<readonly [z.ZodString, z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>]>;
577
- }, z.core.$strip>>;
578
- addressLookupTableAddresses: z.ZodArray<z.ZodString>;
548
+ serializedTransaction: z.ZodString;
579
549
  }, z.core.$strip>]>;
580
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
581
550
  }, z.core.$strip>, z.ZodObject<{
582
551
  type: z.ZodLiteral<"signature">;
583
552
  description: z.ZodString;
584
553
  signatureData: z.ZodString;
585
- metadata: z.ZodRecord<z.ZodString, z.ZodString>;
586
554
  }, z.core.$strip>], "type">>;
587
555
  }, z.core.$strip>>;
588
556
  error: z.ZodOptional<z.ZodString>;
@@ -593,22 +561,22 @@ declare const SwidgeQuoteResponseWrapperSchema: z.ZodObject<{
593
561
  status: z.ZodOptional<z.ZodNumber>;
594
562
  statusText: z.ZodOptional<z.ZodString>;
595
563
  }, z.core.$strip>>;
596
- }, z.core.$strip>;
564
+ }, z.core.$loose>;
597
565
  /**
598
566
  * Swidge execute response wrapper
599
567
  */
600
568
  declare const SwidgeExecuteResponseWrapperSchema: z.ZodObject<{
601
569
  success: z.ZodBoolean;
602
570
  data: z.ZodOptional<z.ZodObject<{
603
- status: z.ZodUnion<readonly [z.ZodLiteral<"success">, z.ZodLiteral<"failure">, z.ZodLiteral<"refund">, z.ZodLiteral<"delayed">]>;
604
- in: z.ZodObject<{
571
+ status: z.ZodString;
572
+ in: z.ZodOptional<z.ZodObject<{
605
573
  network: z.ZodString;
606
574
  txs: z.ZodArray<z.ZodString>;
607
- }, z.core.$strip>;
608
- out: z.ZodObject<{
575
+ }, z.core.$strip>>;
576
+ out: z.ZodOptional<z.ZodObject<{
609
577
  network: z.ZodString;
610
578
  txs: z.ZodArray<z.ZodString>;
611
- }, z.core.$strip>;
579
+ }, z.core.$strip>>;
612
580
  lastUpdated: z.ZodNumber;
613
581
  error: z.ZodOptional<z.ZodString>;
614
582
  }, z.core.$strip>>;
@@ -620,7 +588,7 @@ declare const SwidgeExecuteResponseWrapperSchema: z.ZodObject<{
620
588
  status: z.ZodOptional<z.ZodNumber>;
621
589
  statusText: z.ZodOptional<z.ZodString>;
622
590
  }, z.core.$strip>>;
623
- }, z.core.$strip>;
591
+ }, z.core.$loose>;
624
592
  type SwidgeQuoteData = z.infer<typeof SwidgeQuoteDataSchema>;
625
593
  type SwidgeQuoteResponse = z.infer<typeof SwidgeQuoteResponseWrapperSchema>;
626
594
  type SwidgeExecuteRequest = z.infer<typeof SwidgeExecuteRequestSchema>;
@@ -640,15 +608,12 @@ declare const PolymarketRedeemPositionsRequestSchema: z.ZodObject<{
640
608
  declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
641
609
  success: z.ZodBoolean;
642
610
  data: z.ZodOptional<z.ZodObject<{
643
- success: z.ZodBoolean;
644
- orderInfo: z.ZodObject<{
645
- orderId: z.ZodString;
646
- side: z.ZodString;
647
- size: z.ZodString;
648
- priceUsd: z.ZodString;
649
- totalPriceUsd: z.ZodString;
650
- txHashes: z.ZodArray<z.ZodString>;
651
- }, z.core.$strip>;
611
+ orderId: z.ZodString;
612
+ side: z.ZodString;
613
+ size: z.ZodString;
614
+ priceUsd: z.ZodString;
615
+ totalPriceUsd: z.ZodString;
616
+ txHashes: z.ZodArray<z.ZodString>;
652
617
  }, z.core.$strip>>;
653
618
  error: z.ZodOptional<z.ZodString>;
654
619
  errorMessage: z.ZodOptional<z.ZodString>;
@@ -658,7 +623,7 @@ declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
658
623
  status: z.ZodOptional<z.ZodNumber>;
659
624
  statusText: z.ZodOptional<z.ZodString>;
660
625
  }, z.core.$strip>>;
661
- }, z.core.$strip>;
626
+ }, z.core.$loose>;
662
627
  declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
663
628
  success: z.ZodBoolean;
664
629
  data: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -695,7 +660,7 @@ declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
695
660
  status: z.ZodOptional<z.ZodNumber>;
696
661
  statusText: z.ZodOptional<z.ZodString>;
697
662
  }, z.core.$strip>>;
698
- }, z.core.$strip>;
663
+ }, z.core.$loose>;
699
664
  type PolymarketMarketOrderRequest = z.infer<typeof PolymarketMarketOrderRequestSchema>;
700
665
  type PolymarketRedeemPositionsRequest = z.infer<typeof PolymarketRedeemPositionsRequestSchema>;
701
666
  type PolymarketMarketOrderResponse = z.infer<typeof PolymarketMarketOrderResponseSchema>;
@@ -738,43 +703,31 @@ declare const HyperliquidPlaceOrderResponseSchema: z.ZodObject<{
738
703
  data: z.ZodOptional<z.ZodObject<{
739
704
  orderId: z.ZodString;
740
705
  symbol: z.ZodString;
741
- side: z.ZodEnum<{
742
- buy: "buy";
743
- sell: "sell";
744
- }>;
706
+ side: z.ZodString;
745
707
  price: z.ZodNumber;
746
708
  size: z.ZodNumber;
747
709
  filled: z.ZodNumber;
748
710
  status: z.ZodString;
749
- market: z.ZodEnum<{
750
- perp: "perp";
751
- spot: "spot";
752
- }>;
711
+ market: z.ZodString;
753
712
  clientOrderId: z.ZodOptional<z.ZodString>;
754
713
  }, z.core.$strip>>;
755
714
  error: z.ZodOptional<z.ZodString>;
756
- }, z.core.$strip>;
715
+ }, z.core.$loose>;
757
716
  declare const HyperliquidOrderResponseSchema: z.ZodObject<{
758
717
  success: z.ZodBoolean;
759
718
  data: z.ZodOptional<z.ZodObject<{
760
719
  orderId: z.ZodString;
761
720
  symbol: z.ZodString;
762
- side: z.ZodEnum<{
763
- buy: "buy";
764
- sell: "sell";
765
- }>;
721
+ side: z.ZodString;
766
722
  price: z.ZodNumber;
767
723
  size: z.ZodNumber;
768
724
  filled: z.ZodNumber;
769
725
  status: z.ZodString;
770
- market: z.ZodEnum<{
771
- perp: "perp";
772
- spot: "spot";
773
- }>;
726
+ market: z.ZodString;
774
727
  clientOrderId: z.ZodOptional<z.ZodString>;
775
728
  }, z.core.$strip>>;
776
729
  error: z.ZodOptional<z.ZodString>;
777
- }, z.core.$strip>;
730
+ }, z.core.$loose>;
778
731
  declare const HyperliquidDeleteOrderResponseSchema: z.ZodObject<{
779
732
  success: z.ZodBoolean;
780
733
  data: z.ZodOptional<z.ZodUndefined>;
@@ -795,15 +748,12 @@ declare const HyperliquidBalancesResponseSchema: z.ZodObject<{
795
748
  }, z.core.$strip>>;
796
749
  }, z.core.$strip>>;
797
750
  error: z.ZodOptional<z.ZodString>;
798
- }, z.core.$strip>;
751
+ }, z.core.$loose>;
799
752
  declare const HyperliquidPositionsResponseSchema: z.ZodObject<{
800
753
  success: z.ZodBoolean;
801
754
  data: z.ZodOptional<z.ZodArray<z.ZodObject<{
802
755
  symbol: z.ZodString;
803
- side: z.ZodEnum<{
804
- long: "long";
805
- short: "short";
806
- }>;
756
+ side: z.ZodString;
807
757
  size: z.ZodString;
808
758
  entryPrice: z.ZodString;
809
759
  markPrice: z.ZodString;
@@ -813,37 +763,28 @@ declare const HyperliquidPositionsResponseSchema: z.ZodObject<{
813
763
  marginUsed: z.ZodString;
814
764
  }, z.core.$strip>>>;
815
765
  error: z.ZodOptional<z.ZodString>;
816
- }, z.core.$strip>;
766
+ }, z.core.$loose>;
817
767
  declare const HyperliquidOpenOrdersResponseSchema: z.ZodObject<{
818
768
  success: z.ZodBoolean;
819
769
  data: z.ZodOptional<z.ZodArray<z.ZodObject<{
820
770
  orderId: z.ZodString;
821
771
  symbol: z.ZodString;
822
- side: z.ZodEnum<{
823
- buy: "buy";
824
- sell: "sell";
825
- }>;
772
+ side: z.ZodString;
826
773
  price: z.ZodNumber;
827
774
  size: z.ZodNumber;
828
775
  filled: z.ZodNumber;
829
776
  status: z.ZodString;
830
- market: z.ZodEnum<{
831
- perp: "perp";
832
- spot: "spot";
833
- }>;
777
+ market: z.ZodString;
834
778
  clientOrderId: z.ZodOptional<z.ZodString>;
835
779
  }, z.core.$strip>>>;
836
780
  error: z.ZodOptional<z.ZodString>;
837
- }, z.core.$strip>;
781
+ }, z.core.$loose>;
838
782
  declare const HyperliquidOrderFillsResponseSchema: z.ZodObject<{
839
783
  success: z.ZodBoolean;
840
784
  data: z.ZodOptional<z.ZodArray<z.ZodObject<{
841
785
  orderId: z.ZodString;
842
786
  symbol: z.ZodString;
843
- side: z.ZodEnum<{
844
- buy: "buy";
845
- sell: "sell";
846
- }>;
787
+ side: z.ZodString;
847
788
  price: z.ZodString;
848
789
  size: z.ZodString;
849
790
  fee: z.ZodString;
@@ -851,46 +792,25 @@ declare const HyperliquidOrderFillsResponseSchema: z.ZodObject<{
851
792
  isMaker: z.ZodBoolean;
852
793
  }, z.core.$strip>>>;
853
794
  error: z.ZodOptional<z.ZodString>;
854
- }, z.core.$strip>;
795
+ }, z.core.$loose>;
855
796
  declare const HyperliquidHistoricalOrdersResponseSchema: z.ZodObject<{
856
797
  success: z.ZodBoolean;
857
798
  data: z.ZodOptional<z.ZodArray<z.ZodObject<{
858
799
  orderId: z.ZodString;
859
800
  symbol: z.ZodString;
860
- side: z.ZodEnum<{
861
- buy: "buy";
862
- sell: "sell";
863
- }>;
801
+ side: z.ZodString;
864
802
  price: z.ZodNumber;
865
803
  size: z.ZodNumber;
866
804
  filled: z.ZodNumber;
867
- status: z.ZodEnum<{
868
- filled: "filled";
869
- open: "open";
870
- canceled: "canceled";
871
- triggered: "triggered";
872
- rejected: "rejected";
873
- marginCanceled: "marginCanceled";
874
- liquidatedCanceled: "liquidatedCanceled";
875
- }>;
876
- market: z.ZodEnum<{
877
- perp: "perp";
878
- spot: "spot";
879
- }>;
805
+ status: z.ZodString;
806
+ market: z.ZodString;
880
807
  timestamp: z.ZodNumber;
881
808
  statusTimestamp: z.ZodNumber;
882
- orderType: z.ZodEnum<{
883
- Market: "Market";
884
- Limit: "Limit";
885
- "Stop Market": "Stop Market";
886
- "Stop Limit": "Stop Limit";
887
- "Take Profit Market": "Take Profit Market";
888
- "Take Profit Limit": "Take Profit Limit";
889
- }>;
809
+ orderType: z.ZodString;
890
810
  clientOrderId: z.ZodOptional<z.ZodString>;
891
811
  }, z.core.$strip>>>;
892
812
  error: z.ZodOptional<z.ZodString>;
893
- }, z.core.$strip>;
813
+ }, z.core.$loose>;
894
814
  declare const HyperliquidTransferResponseSchema: z.ZodObject<{
895
815
  success: z.ZodBoolean;
896
816
  data: z.ZodOptional<z.ZodUndefined>;
@@ -902,22 +822,16 @@ declare const HyperliquidLiquidationsResponseSchema: z.ZodObject<{
902
822
  timestamp: z.ZodNumber;
903
823
  liquidatedPositions: z.ZodArray<z.ZodObject<{
904
824
  symbol: z.ZodString;
905
- side: z.ZodEnum<{
906
- long: "long";
907
- short: "short";
908
- }>;
825
+ side: z.ZodString;
909
826
  size: z.ZodString;
910
827
  }, z.core.$strip>>;
911
828
  totalNotional: z.ZodString;
912
829
  accountValue: z.ZodString;
913
- leverageType: z.ZodEnum<{
914
- Cross: "Cross";
915
- Isolated: "Isolated";
916
- }>;
830
+ leverageType: z.ZodString;
917
831
  txHash: z.ZodString;
918
832
  }, z.core.$strip>>>;
919
833
  error: z.ZodOptional<z.ZodString>;
920
- }, z.core.$strip>;
834
+ }, z.core.$loose>;
921
835
  type HyperliquidPlaceOrderRequest = z.infer<typeof HyperliquidPlaceOrderRequestSchema>;
922
836
  type HyperliquidTransferRequest = z.infer<typeof HyperliquidTransferRequestSchema>;
923
837
  type HyperliquidPlaceOrderResponse = z.infer<typeof HyperliquidPlaceOrderResponseSchema>;
@@ -954,7 +868,7 @@ declare const MemorySetResponseSchema: z.ZodObject<{
954
868
  status: z.ZodOptional<z.ZodNumber>;
955
869
  statusText: z.ZodOptional<z.ZodString>;
956
870
  }, z.core.$strip>>;
957
- }, z.core.$strip>;
871
+ }, z.core.$loose>;
958
872
  /**
959
873
  * Memory get response wrapper
960
874
  */
@@ -972,7 +886,7 @@ declare const MemoryGetResponseSchema: z.ZodObject<{
972
886
  status: z.ZodOptional<z.ZodNumber>;
973
887
  statusText: z.ZodOptional<z.ZodString>;
974
888
  }, z.core.$strip>>;
975
- }, z.core.$strip>;
889
+ }, z.core.$loose>;
976
890
  /**
977
891
  * Memory delete response wrapper
978
892
  */
@@ -989,7 +903,7 @@ declare const MemoryDeleteResponseSchema: z.ZodObject<{
989
903
  status: z.ZodOptional<z.ZodNumber>;
990
904
  statusText: z.ZodOptional<z.ZodString>;
991
905
  }, z.core.$strip>>;
992
- }, z.core.$strip>;
906
+ }, z.core.$loose>;
993
907
  /**
994
908
  * Memory list response wrapper
995
909
  */
@@ -1007,7 +921,7 @@ declare const MemoryListResponseSchema: z.ZodObject<{
1007
921
  status: z.ZodOptional<z.ZodNumber>;
1008
922
  statusText: z.ZodOptional<z.ZodString>;
1009
923
  }, z.core.$strip>>;
1010
- }, z.core.$strip>;
924
+ }, z.core.$loose>;
1011
925
  type MemorySetResponse = z.infer<typeof MemorySetResponseSchema>;
1012
926
  type MemoryGetResponse = z.infer<typeof MemoryGetResponseSchema>;
1013
927
  type MemoryDeleteResponse = z.infer<typeof MemoryDeleteResponseSchema>;
@@ -1034,7 +948,7 @@ type MemoryListResponse = z.infer<typeof MemoryListResponseSchema>;
1034
948
  * sessionId: 12345,
1035
949
  * });
1036
950
  *
1037
- * await sdk.sendLog({ type: "observe", shortMessage: "Starting" });
951
+ * await sdk.sendLog({ type: "observe", message: "Starting" });
1038
952
  * const tx = await sdk.signAndSend({
1039
953
  * network: "ethereum:42161",
1040
954
  * request: {
@@ -1060,6 +974,17 @@ declare class AgentSdk {
1060
974
  * ```
1061
975
  */
1062
976
  constructor(config: SDKConfig);
977
+ /**
978
+ * @internal
979
+ *
980
+ * **DO NOT USE - WILL BREAK YOUR AGENTS**
981
+ *
982
+ * ⚠️ **WARNING**: This method will cause issues and break your agents.
983
+ * Do not use this method.
984
+ *
985
+ * @param baseUrl - New base URL to use for API requests
986
+ */
987
+ setBaseUrl(baseUrl: string): void;
1063
988
  /**
1064
989
  * Internal method to send logs to the backend.
1065
990
  * Used by AgentContext.log() method.
@@ -1489,15 +1414,13 @@ declare class AgentSdk {
1489
1414
  *
1490
1415
  * **Output**: `PolymarketMarketOrderResponse`
1491
1416
  * - `success` (boolean): Whether the operation was successful
1492
- * - `data` (PolymarketMarketOrderData | undefined): Market order data (only present on success)
1493
- * - `success` (boolean): Whether the order was successfully submitted
1494
- * - `orderInfo` (PolymarketOrderInfo): Order information with transaction details
1495
- * - `orderId` (string): Unique order identifier
1496
- * - `side` (string): Order side ("BUY" or "SELL")
1497
- * - `size` (string): Order size
1498
- * - `priceUsd` (string): Price per share in USD
1499
- * - `totalPriceUsd` (string): Total order value in USD
1500
- * - `txHashes` (string[]): List of transaction hashes
1417
+ * - `data` (PolymarketOrderInfo | undefined): Order information (only present on success)
1418
+ * - `orderId` (string): Unique order identifier
1419
+ * - `side` (string): Order side ("BUY" or "SELL")
1420
+ * - `size` (string): Order size
1421
+ * - `priceUsd` (string): Price per share in USD
1422
+ * - `totalPriceUsd` (string): Total order value in USD
1423
+ * - `txHashes` (string[]): List of transaction hashes
1501
1424
  * - `error` (string | undefined): Error message (only present on failure)
1502
1425
  * - `errorDetails` (object | undefined): Detailed error info
1503
1426
  *
@@ -1526,9 +1449,8 @@ declare class AgentSdk {
1526
1449
  * });
1527
1450
  *
1528
1451
  * if (buyResult.success && buyResult.data) {
1529
- * console.log(`Order Success: ${buyResult.data.success}`);
1530
- * console.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
1531
- * console.log(`Total Price: $${buyResult.data.orderInfo.totalPriceUsd}`);
1452
+ * console.log(`Order ID: ${buyResult.data.orderId}`);
1453
+ * console.log(`Total Price: $${buyResult.data.totalPriceUsd}`);
1532
1454
  * } else {
1533
1455
  * console.error(`Error: ${buyResult.error}`);
1534
1456
  * }
@@ -1539,17 +1461,13 @@ declare class AgentSdk {
1539
1461
  * {
1540
1462
  * "success": true,
1541
1463
  * "data": {
1542
- * "success": true,
1543
- * "orderInfo": {
1544
- * "orderId": "abc123",
1545
- * "side": "BUY",
1546
- * "size": "10.0",
1547
- * "priceUsd": "0.52",
1548
- * "totalPriceUsd": "5.20",
1549
- * "txHashes": ["0xabc..."]
1550
- * }
1551
- * },
1552
- * "error": undefined
1464
+ * "orderId": "abc123",
1465
+ * "side": "BUY",
1466
+ * "size": "10.0",
1467
+ * "priceUsd": "0.52",
1468
+ * "totalPriceUsd": "5.20",
1469
+ * "txHashes": ["0xabc..."]
1470
+ * }
1553
1471
  * }
1554
1472
  * ```
1555
1473
  *
@@ -1557,7 +1475,6 @@ declare class AgentSdk {
1557
1475
  * ```json
1558
1476
  * {
1559
1477
  * "success": false,
1560
- * "data": undefined,
1561
1478
  * "error": "Could not get order",
1562
1479
  * "errorDetails": { "message": "Invalid request", "status": 400 }
1563
1480
  * }
@@ -2288,8 +2205,8 @@ declare class AgentSdk {
2288
2205
  /**
2289
2206
  * Low-level HTTP client used internally by the SDK.
2290
2207
  *
2291
- * - Automatically detects Cloudflare Worker environment and uses service bindings
2292
- * - Falls back to HTTP requests for standard environments
2208
+ * - Automatically detects Lambda environment and uses internal VPC URL
2209
+ * - Falls back to HTTP requests for local development
2293
2210
  * - For local development, automatically reads auth token from ~/.config/circuit/auth.json
2294
2211
  * - Adds session ID and agent slug headers automatically
2295
2212
  * - Emits verbose request/response logs when `SDKConfig.verbose` is enabled
@@ -2301,8 +2218,7 @@ declare class APIClient {
2301
2218
  private config;
2302
2219
  private baseUrl;
2303
2220
  private authorizationHeader?;
2304
- private isCloudflareWorker;
2305
- private hasServiceBinding;
2221
+ private isLambdaEnvironment;
2306
2222
  /**
2307
2223
  * Create an API client.
2308
2224
  * @param config - SDK configuration
@@ -2315,7 +2231,7 @@ declare class APIClient {
2315
2231
  /**
2316
2232
  * Perform a JSON HTTP request.
2317
2233
  *
2318
- * Automatically uses service bindings when available, otherwise falls back to HTTP.
2234
+ * Automatically uses internal VPC URL for Lambda environments, otherwise falls back to HTTP.
2319
2235
  * Throws with a helpful message when the response is not ok.
2320
2236
  *
2321
2237
  * @param endpoint - API path beginning with `/v1/...`
@@ -2485,6 +2401,17 @@ declare class AgentContext {
2485
2401
  baseUrl?: string;
2486
2402
  authorizationHeader?: string;
2487
2403
  });
2404
+ /**
2405
+ * @internal
2406
+ *
2407
+ * **DO NOT USE - WILL BREAK YOUR AGENTS**
2408
+ *
2409
+ * ⚠️ **WARNING**: This method will cause issues and break your agents.
2410
+ * Do not use this method.
2411
+ *
2412
+ * @param baseUrl - New base URL to use for API requests
2413
+ */
2414
+ setBaseUrl(baseUrl: string): void;
2488
2415
  /**
2489
2416
  * Unified logging method that handles console output and backend messaging.
2490
2417
  *
@@ -2501,15 +2428,15 @@ declare class AgentContext {
2501
2428
  * - `agent.log("message")` → console.info() + backend POST with type="observe"
2502
2429
  * - `agent.log("message", { error: true })` → console.error() + backend POST with type="error"
2503
2430
  * - `agent.log("message", { debug: true })` → console.info() + NO backend call
2504
- * - `agent.log({ key: "value" })` → Pretty-printed to console + serialized to backend (truncated to 250 chars)
2505
- * - `agent.log([1, 2, 3])` → Pretty-printed to console + serialized to backend (truncated to 250 chars)
2431
+ * - `agent.log({ key: "value" })` → Pretty-printed to console + serialized to backend
2432
+ * - `agent.log([1, 2, 3])` → Pretty-printed to console + serialized to backend
2506
2433
  *
2507
2434
  * **What happens:**
2508
2435
  * - Default (no flags): Shows in your terminal AND in the Circuit UI for your user
2509
2436
  * - error: true: Shows as error in terminal AND Circuit UI
2510
2437
  * - debug: true: Shows ONLY in your terminal (users don't see it)
2511
2438
  *
2512
- * @param message - The message to log (string, object, or array) - backend receives max 250 chars
2439
+ * @param message - The message to log (string, object, or array)
2513
2440
  * @param options - Logging options
2514
2441
  * @param options.error - If true, log as error and send to backend as error type (default: false)
2515
2442
  * @param options.debug - If true, only log to console, skip backend call (default: false)
@@ -2558,7 +2485,7 @@ declare class AgentContext {
2558
2485
  *
2559
2486
  * **Input**: `SignAndSendRequest`
2560
2487
  * - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
2561
- * - `message` (string | undefined): Optional context message (max 250 chars)
2488
+ * - `message` (string | undefined): Optional context message
2562
2489
  * - `request` (object): Transaction payload
2563
2490
  * - For Ethereum:
2564
2491
  * - `toAddress` (string): Recipient address as hex string
@@ -3542,7 +3469,7 @@ interface AgentConfig {
3542
3469
  stopFunction?: StopFunctionContract;
3543
3470
  }
3544
3471
  /**
3545
- * HTTP server wrapper for agent functions.
3472
+ * HTTP handler wrapper for agent functions.
3546
3473
  *
3547
3474
  * Exposes the following endpoints:
3548
3475
  * - `POST /run` — required, calls your execution function
@@ -3589,12 +3516,18 @@ declare class Agent {
3589
3516
  private updateJobStatus;
3590
3517
  private setupRoutes;
3591
3518
  private getPortFromPackageJson;
3592
- run(port?: number): Promise<{
3593
- fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
3594
- } | undefined>;
3595
- /** Get the worker export for Cloudflare Workers environments. */
3519
+ /**
3520
+ * Start a local HTTP server for development and testing.
3521
+ *
3522
+ * This method is used for local development and testing with the Circuit CLI.
3523
+ * For Lambda deployment, use `getExport()` instead.
3524
+ *
3525
+ * @param port - Optional port number (defaults to 3000 or AGENT_PORT env var)
3526
+ */
3527
+ run(port?: number): Promise<void>;
3528
+ /** Get the handler export for Lambda environments. */
3596
3529
  getExport(): {
3597
- fetch: (request: Request, env: any, ctx: any) => Promise<Response>;
3530
+ fetch: (request: Request, Env?: unknown, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
3598
3531
  };
3599
3532
  }
3600
3533
 
@@ -3621,4 +3554,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
3621
3554
  */
3622
3555
  declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
3623
3556
 
3624
- 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, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, type TransactionsResponse, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
3557
+ 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, type StopFunctionContract, SwidgeExecuteRequestSchema, type SwidgeExecuteResponse, SwidgeExecuteResponseWrapperSchema, type SwidgeQuoteRequest, SwidgeQuoteRequestSchema, type SwidgeQuoteResponse, SwidgeQuoteResponseWrapperSchema, type SwidgeQuoteResult, type TransactionsResponse, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
package/index.js CHANGED
@@ -1 +1 @@
1
- import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){if(this.isCloudflareWorker()){if(void 0!==globalThis.AGENTS_TO_API_PROXY)return!0;if(void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)return!0}return!1}constructor(r){this.config=r,this.baseUrl=r.baseUrl||"https://agents.circuit.org",this.authorizationHeader=r.authorizationHeader}getAgentSlug(){return"undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG?process.env.CIRCUIT_AGENT_SLUG:void 0!==globalThis.CIRCUIT_AGENT_SLUG?globalThis.CIRCUIT_AGENT_SLUG:void 0}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCloudflareWorker())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",...this.getAuthHeaders()},...e.headers};let s;if(this.hasServiceBinding()){let o;if(void 0!==globalThis.AGENTS_TO_API_PROXY)o=globalThis.AGENTS_TO_API_PROXY;else{if(void 0===globalThis.__AGENT_ENV__||!globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)throw new Error("Service binding detected but not accessible");o=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}const a={...e,headers:t},n=`https://agents-to-api-proxy.circuit-0bc.workers.dev${r}`;s=await o.fetch(n,a)}else{const o=`${this.baseUrl}${r}`,a={...e,headers:t};s=await fetch(o,a)}if(!s.ok){const r=await s.json().catch(()=>({})),e=r.message||r.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.message,t.errorDetails=r,t.statusCode=s.status,t}return await s.json()}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 a=class{client;config;constructor(r){this.config=r,this.client=new e(r)}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),t=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}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),t=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}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{success:!0,data: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{success:!0,data:await this.client.post("/v1/swidge/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{const e=await this.client.post("/v1/swidge/execute",r);if(Array.isArray(e))return e.map(r=>{const e="success"===r.status;return{success:e,data:r,error:e?void 0:r.error}});const t="success"===e.status;return{success:t,data:e,error:t?void 0:e.error}}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},a=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{return{success:!0,data: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{success:!0,data: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{success:!0,data: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{success:!0,data: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{success:!0,data: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{success:!0,data: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{success:!0,data: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{success:!0,data: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 n,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 a({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,a;const n=(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,n,2),a=JSON.stringify(r,n)):(o=String(r),a=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{const r=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,shortMessage:r}]),{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)}),g=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.stopFunction=r.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async r=>{await r.log(`Agent stopped for session ${r.sessionId}`)};async executeWithJobTracking(r,e,t){let s,o=!1;try{const s=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:t});await e(s),o=!0}catch(r){s=this.getErrorMessage(r),o=!1,console.error("Agent function error:",s)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,o?"success":"failed",s,t)}}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 n=new a({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await n._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 n._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,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,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(e,s,t),r.json({success:!0,message:"Stop 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(n(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){if("undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare)return this.getExport();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 /stop"),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:async(r,e,t)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(r,e,t))}}});import{z as f}from"zod";var w=f.templateLiteral(["ethereum:",f.coerce.number().int().nonnegative()]),v=f.union([f.literal("solana"),w]),E=f.object({address:f.string(),network:v}),b=(f.object({from:E,to:E,fromToken:f.string().optional(),toToken:f.string().optional(),amount:f.string(),slippage:f.string().optional()}),f.object({network:v,address:f.string(),token:f.string().nullable(),name:f.string().optional(),symbol:f.string().optional(),decimals:f.number().optional(),amount:f.string().optional(),minimumAmount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()})),T=f.object({usd:f.string().optional(),percentage:f.string().optional()}),k=f.object({name:f.string(),amount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()}),D=f.object({programId:f.string(),keys:f.array(f.object({pubkey:f.string(),isSigner:f.boolean(),isWritable:f.boolean()})),data:f.union([f.string(),f.instanceof(Buffer)])}),F=f.object({type:f.literal("evm"),from:f.string().regex(/^0x[a-fA-F0-9]{40}$/),to:f.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:f.number(),value:f.number(),data:f.string().regex(/^0x[a-fA-F0-9]*$/),gas:f.number().nullish(),maxFeePerGas:f.number().nullish(),maxPriorityFeePerGas:f.number().nullish()}),S=f.object({type:f.literal("solana"),instructions:f.array(D),addressLookupTableAddresses:f.array(f.string())}),O=f.object({type:f.literal("transaction"),description:f.string(),transactionDetails:f.union([F,S]),metadata:f.record(f.string(),f.string())}),A=f.object({type:f.literal("signature"),description:f.string(),signatureData:f.string(),metadata:f.record(f.string(),f.string())}),M=f.discriminatedUnion("type",[O,A]),$=f.object({engine:f.literal("relay"),assetSend:b,assetReceive:b,priceImpact:T,fees:f.array(k),steps:f.array(M)}),q=f.object({network:f.string(),txs:f.array(f.string())}),P=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:q,out:q,lastUpdated:f.number(),error:f.string().optional()}),U={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"},x=r=>f.object({success:f.boolean(),data:r.optional(),error:f.string().optional(),errorMessage:f.string().optional(),errorDetails:f.object({message:f.string().optional(),error:f.string().optional(),status:f.number().optional(),statusText:f.string().optional()}).optional()});x($),x(P);export{e as APIClient,g as Agent,y as AgentContext,a as AgentSdk,U as QUOTE_RESULT,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
1
+ import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isLambdaEnvironment(){return!("undefined"==typeof process||!process.env||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,this.baseUrl=r.baseUrl||(this.isLambdaEnvironment()?"http://transaction-service.agent.internal":"https://agents.circuit.org"),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.isLambdaEnvironment())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",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${r}`,o={...e,headers:t},a=await fetch(s,o);if(!a.ok){const r=await a.json().catch(()=>({})),e=r.error||`HTTP ${a.status}: ${a.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.error,t.errorDetails=r,t.statusCode=a.status,t}return await a.json()}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 a=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||{},a=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,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 n,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 a({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,a;const n=(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,n,2),a=JSON.stringify(r,n)):(o=String(r),a=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:a}]),{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)}),f=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.stopFunction=r.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async r=>{await r.log(`Agent stopped for session ${r.sessionId}`)};async executeWithJobTracking(r,e,t){let s,o=!1;try{const s=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:t});await e(s),o=!0}catch(r){s=this.getErrorMessage(r),o=!1,console.error("Agent function error:",s)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,o?"success":"failed",s,t)}}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 n=new a({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await n._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 n._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,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,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(e,s,t),r.json({success:!0,message:"Stop 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(n(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 /stop"),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}),D=g.object({from:v,to:v,fromToken:g.string().optional(),toToken:g.string().optional(),amount:g.string(),slippage:g.string().optional()}),k=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()}),F=g.object({usd:g.string().optional(),percentage:g.string().optional()}),S=g.object({name:g.string(),amount:g.string().optional(),amountFormatted:g.string().optional(),amountUsd:g.string().optional()}),O=(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()})),T=g.object({type:g.literal("solana"),serializedTransaction:g.string()}),b=g.object({type:g.literal("transaction"),description:g.string(),transactionDetails:g.union([O,T])}),M=g.object({type:g.literal("signature"),description:g.string(),signatureData:g.string()}),A=g.discriminatedUnion("type",[b,M]),$=g.object({engine:g.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:k,assetReceive:k,priceImpact:F,fees:g.array(S),steps:g.array(A)}),q=$,U=g.object({network:g.string(),txs:g.array(g.string())}),P=g.object({status:g.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:U.optional(),out:U.optional(),lastUpdated:g.number(),error:g.string().optional()}),x={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(),j=I($),H=I(P);export{e as APIClient,f as Agent,y as AgentContext,a as AgentSdk,x as QUOTE_RESULT,q as SwidgeExecuteRequestSchema,H as SwidgeExecuteResponseWrapperSchema,D as SwidgeQuoteRequestSchema,j as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.2.4",
3
+ "version": "1.3.3",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -40,27 +40,27 @@
40
40
  "@solana/transaction-confirmation": "./stubs/subscriptions-stub.js"
41
41
  },
42
42
  "dependencies": {
43
- "@hono/zod-validator": "^0.7.2",
44
- "@solana-program/system": "^0.7.0",
45
- "@solana/kit": "^2.3.0",
46
- "@solana/transactions": "^2.3.0",
47
- "hono": "^4.9.1",
48
- "zod": "^4.0.17"
43
+ "@hono/zod-validator": "0.7.2",
44
+ "@solana-program/system": "0.7.0",
45
+ "@solana/kit": "2.3.0",
46
+ "@solana/transactions": "2.3.0",
47
+ "hono": "4.9.1",
48
+ "zod": "4.0.17"
49
49
  },
50
50
  "optionalDependencies": {
51
- "@hono/node-server": "^1.18.2",
51
+ "@hono/node-server": "1.18.2",
52
52
  "@solana-program/token": "0.5.1",
53
53
  "@solana-program/token-2022": "0.4.2"
54
54
  },
55
55
  "devDependencies": {
56
- "@biomejs/biome": "^1.7.0",
56
+ "@biomejs/biome": "1.7.0",
57
57
  "@types/jest": "29.5.14",
58
58
  "@types/node": "^20.19.7",
59
- "dts-bundle-generator": "^9.5.1",
60
- "esbuild": "^0.25.9",
59
+ "dts-bundle-generator": "9.5.1",
60
+ "esbuild": "0.25.9",
61
61
  "jest": "29.7.0",
62
- "terser": "^5.43.1",
63
- "tsup": "^8.5.0",
62
+ "terser": "5.43.1",
63
+ "tsup": "8.5.0",
64
64
  "typescript": "5.8.3"
65
65
  },
66
66
  "repository": {