@circuitorg/agent-sdk 1.3.0 → 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.
- package/index.d.ts +65 -143
- package/index.js +1 -1
- package/package.json +13 -13
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:
|
|
120
|
+
/** Signature type. Expected: 'evm' */
|
|
121
|
+
type: string;
|
|
121
122
|
};
|
|
122
123
|
/**
|
|
123
124
|
* Standard response from signMessage operations
|
|
@@ -293,7 +294,7 @@ type AgentLog = z.infer<typeof AgentLogSchema>;
|
|
|
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
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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.
|
|
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
|
-
|
|
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,14 +561,14 @@ 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.$
|
|
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.
|
|
571
|
+
status: z.ZodString;
|
|
604
572
|
in: z.ZodOptional<z.ZodObject<{
|
|
605
573
|
network: z.ZodString;
|
|
606
574
|
txs: z.ZodArray<z.ZodString>;
|
|
@@ -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.$
|
|
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>;
|
|
@@ -655,7 +623,7 @@ declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
|
|
|
655
623
|
status: z.ZodOptional<z.ZodNumber>;
|
|
656
624
|
statusText: z.ZodOptional<z.ZodString>;
|
|
657
625
|
}, z.core.$strip>>;
|
|
658
|
-
}, z.core.$
|
|
626
|
+
}, z.core.$loose>;
|
|
659
627
|
declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
|
|
660
628
|
success: z.ZodBoolean;
|
|
661
629
|
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
@@ -692,7 +660,7 @@ declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
|
|
|
692
660
|
status: z.ZodOptional<z.ZodNumber>;
|
|
693
661
|
statusText: z.ZodOptional<z.ZodString>;
|
|
694
662
|
}, z.core.$strip>>;
|
|
695
|
-
}, z.core.$
|
|
663
|
+
}, z.core.$loose>;
|
|
696
664
|
type PolymarketMarketOrderRequest = z.infer<typeof PolymarketMarketOrderRequestSchema>;
|
|
697
665
|
type PolymarketRedeemPositionsRequest = z.infer<typeof PolymarketRedeemPositionsRequestSchema>;
|
|
698
666
|
type PolymarketMarketOrderResponse = z.infer<typeof PolymarketMarketOrderResponseSchema>;
|
|
@@ -735,43 +703,31 @@ declare const HyperliquidPlaceOrderResponseSchema: z.ZodObject<{
|
|
|
735
703
|
data: z.ZodOptional<z.ZodObject<{
|
|
736
704
|
orderId: z.ZodString;
|
|
737
705
|
symbol: z.ZodString;
|
|
738
|
-
side: z.
|
|
739
|
-
buy: "buy";
|
|
740
|
-
sell: "sell";
|
|
741
|
-
}>;
|
|
706
|
+
side: z.ZodString;
|
|
742
707
|
price: z.ZodNumber;
|
|
743
708
|
size: z.ZodNumber;
|
|
744
709
|
filled: z.ZodNumber;
|
|
745
710
|
status: z.ZodString;
|
|
746
|
-
market: z.
|
|
747
|
-
perp: "perp";
|
|
748
|
-
spot: "spot";
|
|
749
|
-
}>;
|
|
711
|
+
market: z.ZodString;
|
|
750
712
|
clientOrderId: z.ZodOptional<z.ZodString>;
|
|
751
713
|
}, z.core.$strip>>;
|
|
752
714
|
error: z.ZodOptional<z.ZodString>;
|
|
753
|
-
}, z.core.$
|
|
715
|
+
}, z.core.$loose>;
|
|
754
716
|
declare const HyperliquidOrderResponseSchema: z.ZodObject<{
|
|
755
717
|
success: z.ZodBoolean;
|
|
756
718
|
data: z.ZodOptional<z.ZodObject<{
|
|
757
719
|
orderId: z.ZodString;
|
|
758
720
|
symbol: z.ZodString;
|
|
759
|
-
side: z.
|
|
760
|
-
buy: "buy";
|
|
761
|
-
sell: "sell";
|
|
762
|
-
}>;
|
|
721
|
+
side: z.ZodString;
|
|
763
722
|
price: z.ZodNumber;
|
|
764
723
|
size: z.ZodNumber;
|
|
765
724
|
filled: z.ZodNumber;
|
|
766
725
|
status: z.ZodString;
|
|
767
|
-
market: z.
|
|
768
|
-
perp: "perp";
|
|
769
|
-
spot: "spot";
|
|
770
|
-
}>;
|
|
726
|
+
market: z.ZodString;
|
|
771
727
|
clientOrderId: z.ZodOptional<z.ZodString>;
|
|
772
728
|
}, z.core.$strip>>;
|
|
773
729
|
error: z.ZodOptional<z.ZodString>;
|
|
774
|
-
}, z.core.$
|
|
730
|
+
}, z.core.$loose>;
|
|
775
731
|
declare const HyperliquidDeleteOrderResponseSchema: z.ZodObject<{
|
|
776
732
|
success: z.ZodBoolean;
|
|
777
733
|
data: z.ZodOptional<z.ZodUndefined>;
|
|
@@ -792,15 +748,12 @@ declare const HyperliquidBalancesResponseSchema: z.ZodObject<{
|
|
|
792
748
|
}, z.core.$strip>>;
|
|
793
749
|
}, z.core.$strip>>;
|
|
794
750
|
error: z.ZodOptional<z.ZodString>;
|
|
795
|
-
}, z.core.$
|
|
751
|
+
}, z.core.$loose>;
|
|
796
752
|
declare const HyperliquidPositionsResponseSchema: z.ZodObject<{
|
|
797
753
|
success: z.ZodBoolean;
|
|
798
754
|
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
799
755
|
symbol: z.ZodString;
|
|
800
|
-
side: z.
|
|
801
|
-
long: "long";
|
|
802
|
-
short: "short";
|
|
803
|
-
}>;
|
|
756
|
+
side: z.ZodString;
|
|
804
757
|
size: z.ZodString;
|
|
805
758
|
entryPrice: z.ZodString;
|
|
806
759
|
markPrice: z.ZodString;
|
|
@@ -810,37 +763,28 @@ declare const HyperliquidPositionsResponseSchema: z.ZodObject<{
|
|
|
810
763
|
marginUsed: z.ZodString;
|
|
811
764
|
}, z.core.$strip>>>;
|
|
812
765
|
error: z.ZodOptional<z.ZodString>;
|
|
813
|
-
}, z.core.$
|
|
766
|
+
}, z.core.$loose>;
|
|
814
767
|
declare const HyperliquidOpenOrdersResponseSchema: z.ZodObject<{
|
|
815
768
|
success: z.ZodBoolean;
|
|
816
769
|
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
817
770
|
orderId: z.ZodString;
|
|
818
771
|
symbol: z.ZodString;
|
|
819
|
-
side: z.
|
|
820
|
-
buy: "buy";
|
|
821
|
-
sell: "sell";
|
|
822
|
-
}>;
|
|
772
|
+
side: z.ZodString;
|
|
823
773
|
price: z.ZodNumber;
|
|
824
774
|
size: z.ZodNumber;
|
|
825
775
|
filled: z.ZodNumber;
|
|
826
776
|
status: z.ZodString;
|
|
827
|
-
market: z.
|
|
828
|
-
perp: "perp";
|
|
829
|
-
spot: "spot";
|
|
830
|
-
}>;
|
|
777
|
+
market: z.ZodString;
|
|
831
778
|
clientOrderId: z.ZodOptional<z.ZodString>;
|
|
832
779
|
}, z.core.$strip>>>;
|
|
833
780
|
error: z.ZodOptional<z.ZodString>;
|
|
834
|
-
}, z.core.$
|
|
781
|
+
}, z.core.$loose>;
|
|
835
782
|
declare const HyperliquidOrderFillsResponseSchema: z.ZodObject<{
|
|
836
783
|
success: z.ZodBoolean;
|
|
837
784
|
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
838
785
|
orderId: z.ZodString;
|
|
839
786
|
symbol: z.ZodString;
|
|
840
|
-
side: z.
|
|
841
|
-
buy: "buy";
|
|
842
|
-
sell: "sell";
|
|
843
|
-
}>;
|
|
787
|
+
side: z.ZodString;
|
|
844
788
|
price: z.ZodString;
|
|
845
789
|
size: z.ZodString;
|
|
846
790
|
fee: z.ZodString;
|
|
@@ -848,46 +792,25 @@ declare const HyperliquidOrderFillsResponseSchema: z.ZodObject<{
|
|
|
848
792
|
isMaker: z.ZodBoolean;
|
|
849
793
|
}, z.core.$strip>>>;
|
|
850
794
|
error: z.ZodOptional<z.ZodString>;
|
|
851
|
-
}, z.core.$
|
|
795
|
+
}, z.core.$loose>;
|
|
852
796
|
declare const HyperliquidHistoricalOrdersResponseSchema: z.ZodObject<{
|
|
853
797
|
success: z.ZodBoolean;
|
|
854
798
|
data: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
855
799
|
orderId: z.ZodString;
|
|
856
800
|
symbol: z.ZodString;
|
|
857
|
-
side: z.
|
|
858
|
-
buy: "buy";
|
|
859
|
-
sell: "sell";
|
|
860
|
-
}>;
|
|
801
|
+
side: z.ZodString;
|
|
861
802
|
price: z.ZodNumber;
|
|
862
803
|
size: z.ZodNumber;
|
|
863
804
|
filled: z.ZodNumber;
|
|
864
|
-
status: z.
|
|
865
|
-
|
|
866
|
-
open: "open";
|
|
867
|
-
canceled: "canceled";
|
|
868
|
-
triggered: "triggered";
|
|
869
|
-
rejected: "rejected";
|
|
870
|
-
marginCanceled: "marginCanceled";
|
|
871
|
-
liquidatedCanceled: "liquidatedCanceled";
|
|
872
|
-
}>;
|
|
873
|
-
market: z.ZodEnum<{
|
|
874
|
-
perp: "perp";
|
|
875
|
-
spot: "spot";
|
|
876
|
-
}>;
|
|
805
|
+
status: z.ZodString;
|
|
806
|
+
market: z.ZodString;
|
|
877
807
|
timestamp: z.ZodNumber;
|
|
878
808
|
statusTimestamp: z.ZodNumber;
|
|
879
|
-
orderType: z.
|
|
880
|
-
Market: "Market";
|
|
881
|
-
Limit: "Limit";
|
|
882
|
-
"Stop Market": "Stop Market";
|
|
883
|
-
"Stop Limit": "Stop Limit";
|
|
884
|
-
"Take Profit Market": "Take Profit Market";
|
|
885
|
-
"Take Profit Limit": "Take Profit Limit";
|
|
886
|
-
}>;
|
|
809
|
+
orderType: z.ZodString;
|
|
887
810
|
clientOrderId: z.ZodOptional<z.ZodString>;
|
|
888
811
|
}, z.core.$strip>>>;
|
|
889
812
|
error: z.ZodOptional<z.ZodString>;
|
|
890
|
-
}, z.core.$
|
|
813
|
+
}, z.core.$loose>;
|
|
891
814
|
declare const HyperliquidTransferResponseSchema: z.ZodObject<{
|
|
892
815
|
success: z.ZodBoolean;
|
|
893
816
|
data: z.ZodOptional<z.ZodUndefined>;
|
|
@@ -899,22 +822,16 @@ declare const HyperliquidLiquidationsResponseSchema: z.ZodObject<{
|
|
|
899
822
|
timestamp: z.ZodNumber;
|
|
900
823
|
liquidatedPositions: z.ZodArray<z.ZodObject<{
|
|
901
824
|
symbol: z.ZodString;
|
|
902
|
-
side: z.
|
|
903
|
-
long: "long";
|
|
904
|
-
short: "short";
|
|
905
|
-
}>;
|
|
825
|
+
side: z.ZodString;
|
|
906
826
|
size: z.ZodString;
|
|
907
827
|
}, z.core.$strip>>;
|
|
908
828
|
totalNotional: z.ZodString;
|
|
909
829
|
accountValue: z.ZodString;
|
|
910
|
-
leverageType: z.
|
|
911
|
-
Cross: "Cross";
|
|
912
|
-
Isolated: "Isolated";
|
|
913
|
-
}>;
|
|
830
|
+
leverageType: z.ZodString;
|
|
914
831
|
txHash: z.ZodString;
|
|
915
832
|
}, z.core.$strip>>>;
|
|
916
833
|
error: z.ZodOptional<z.ZodString>;
|
|
917
|
-
}, z.core.$
|
|
834
|
+
}, z.core.$loose>;
|
|
918
835
|
type HyperliquidPlaceOrderRequest = z.infer<typeof HyperliquidPlaceOrderRequestSchema>;
|
|
919
836
|
type HyperliquidTransferRequest = z.infer<typeof HyperliquidTransferRequestSchema>;
|
|
920
837
|
type HyperliquidPlaceOrderResponse = z.infer<typeof HyperliquidPlaceOrderResponseSchema>;
|
|
@@ -951,7 +868,7 @@ declare const MemorySetResponseSchema: z.ZodObject<{
|
|
|
951
868
|
status: z.ZodOptional<z.ZodNumber>;
|
|
952
869
|
statusText: z.ZodOptional<z.ZodString>;
|
|
953
870
|
}, z.core.$strip>>;
|
|
954
|
-
}, z.core.$
|
|
871
|
+
}, z.core.$loose>;
|
|
955
872
|
/**
|
|
956
873
|
* Memory get response wrapper
|
|
957
874
|
*/
|
|
@@ -969,7 +886,7 @@ declare const MemoryGetResponseSchema: z.ZodObject<{
|
|
|
969
886
|
status: z.ZodOptional<z.ZodNumber>;
|
|
970
887
|
statusText: z.ZodOptional<z.ZodString>;
|
|
971
888
|
}, z.core.$strip>>;
|
|
972
|
-
}, z.core.$
|
|
889
|
+
}, z.core.$loose>;
|
|
973
890
|
/**
|
|
974
891
|
* Memory delete response wrapper
|
|
975
892
|
*/
|
|
@@ -986,7 +903,7 @@ declare const MemoryDeleteResponseSchema: z.ZodObject<{
|
|
|
986
903
|
status: z.ZodOptional<z.ZodNumber>;
|
|
987
904
|
statusText: z.ZodOptional<z.ZodString>;
|
|
988
905
|
}, z.core.$strip>>;
|
|
989
|
-
}, z.core.$
|
|
906
|
+
}, z.core.$loose>;
|
|
990
907
|
/**
|
|
991
908
|
* Memory list response wrapper
|
|
992
909
|
*/
|
|
@@ -1004,7 +921,7 @@ declare const MemoryListResponseSchema: z.ZodObject<{
|
|
|
1004
921
|
status: z.ZodOptional<z.ZodNumber>;
|
|
1005
922
|
statusText: z.ZodOptional<z.ZodString>;
|
|
1006
923
|
}, z.core.$strip>>;
|
|
1007
|
-
}, z.core.$
|
|
924
|
+
}, z.core.$loose>;
|
|
1008
925
|
type MemorySetResponse = z.infer<typeof MemorySetResponseSchema>;
|
|
1009
926
|
type MemoryGetResponse = z.infer<typeof MemoryGetResponseSchema>;
|
|
1010
927
|
type MemoryDeleteResponse = z.infer<typeof MemoryDeleteResponseSchema>;
|
|
@@ -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
|
|
2292
|
-
* - Falls back to HTTP requests for
|
|
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
|
|
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
|
|
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/...`
|
|
@@ -2512,15 +2428,15 @@ declare class AgentContext {
|
|
|
2512
2428
|
* - `agent.log("message")` → console.info() + backend POST with type="observe"
|
|
2513
2429
|
* - `agent.log("message", { error: true })` → console.error() + backend POST with type="error"
|
|
2514
2430
|
* - `agent.log("message", { debug: true })` → console.info() + NO backend call
|
|
2515
|
-
* - `agent.log({ key: "value" })` → Pretty-printed to console + serialized to backend
|
|
2516
|
-
* - `agent.log([1, 2, 3])` → Pretty-printed to console + serialized to backend
|
|
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
|
|
2517
2433
|
*
|
|
2518
2434
|
* **What happens:**
|
|
2519
2435
|
* - Default (no flags): Shows in your terminal AND in the Circuit UI for your user
|
|
2520
2436
|
* - error: true: Shows as error in terminal AND Circuit UI
|
|
2521
2437
|
* - debug: true: Shows ONLY in your terminal (users don't see it)
|
|
2522
2438
|
*
|
|
2523
|
-
* @param message - The message to log (string, object, or array)
|
|
2439
|
+
* @param message - The message to log (string, object, or array)
|
|
2524
2440
|
* @param options - Logging options
|
|
2525
2441
|
* @param options.error - If true, log as error and send to backend as error type (default: false)
|
|
2526
2442
|
* @param options.debug - If true, only log to console, skip backend call (default: false)
|
|
@@ -2569,7 +2485,7 @@ declare class AgentContext {
|
|
|
2569
2485
|
*
|
|
2570
2486
|
* **Input**: `SignAndSendRequest`
|
|
2571
2487
|
* - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
|
|
2572
|
-
* - `message` (string | undefined): Optional context message
|
|
2488
|
+
* - `message` (string | undefined): Optional context message
|
|
2573
2489
|
* - `request` (object): Transaction payload
|
|
2574
2490
|
* - For Ethereum:
|
|
2575
2491
|
* - `toAddress` (string): Recipient address as hex string
|
|
@@ -3553,7 +3469,7 @@ interface AgentConfig {
|
|
|
3553
3469
|
stopFunction?: StopFunctionContract;
|
|
3554
3470
|
}
|
|
3555
3471
|
/**
|
|
3556
|
-
* HTTP
|
|
3472
|
+
* HTTP handler wrapper for agent functions.
|
|
3557
3473
|
*
|
|
3558
3474
|
* Exposes the following endpoints:
|
|
3559
3475
|
* - `POST /run` — required, calls your execution function
|
|
@@ -3600,12 +3516,18 @@ declare class Agent {
|
|
|
3600
3516
|
private updateJobStatus;
|
|
3601
3517
|
private setupRoutes;
|
|
3602
3518
|
private getPortFromPackageJson;
|
|
3603
|
-
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
|
|
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. */
|
|
3607
3529
|
getExport(): {
|
|
3608
|
-
fetch: (request: Request,
|
|
3530
|
+
fetch: (request: Request, Env?: unknown, executionCtx?: hono.ExecutionContext) => Response | Promise<Response>;
|
|
3609
3531
|
};
|
|
3610
3532
|
}
|
|
3611
3533
|
|
|
@@ -3632,4 +3554,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
|
|
|
3632
3554
|
*/
|
|
3633
3555
|
declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
|
|
3634
3556
|
|
|
3635
|
-
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.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.error,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)}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{const r=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,message: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())}),U=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:q.optional(),out:q.optional(),lastUpdated:f.number(),error:f.string().optional()}),P={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(U);export{e as APIClient,g as Agent,y as AgentContext,a as AgentSdk,P 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.3.
|
|
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": "
|
|
44
|
-
"@solana-program/system": "
|
|
45
|
-
"@solana/kit": "
|
|
46
|
-
"@solana/transactions": "
|
|
47
|
-
"hono": "
|
|
48
|
-
"zod": "
|
|
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": "
|
|
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": "
|
|
56
|
+
"@biomejs/biome": "1.7.0",
|
|
57
57
|
"@types/jest": "29.5.14",
|
|
58
58
|
"@types/node": "^20.19.7",
|
|
59
|
-
"dts-bundle-generator": "
|
|
60
|
-
"esbuild": "
|
|
59
|
+
"dts-bundle-generator": "9.5.1",
|
|
60
|
+
"esbuild": "0.25.9",
|
|
61
61
|
"jest": "29.7.0",
|
|
62
|
-
"terser": "
|
|
63
|
-
"tsup": "
|
|
62
|
+
"terser": "5.43.1",
|
|
63
|
+
"tsup": "8.5.0",
|
|
64
64
|
"typescript": "5.8.3"
|
|
65
65
|
},
|
|
66
66
|
"repository": {
|