@circuitorg/agent-sdk 1.3.8 → 1.3.10
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/README.md +10 -8
- package/index.d.ts +408 -94
- package/index.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -81,19 +81,21 @@ Every agent receives a single `AgentContext` object that provides:
|
|
|
81
81
|
**Important:** `currentPositions` reflects your allocated assets at the **start** of each execution. To avoid failed transactions, you should be tracking intra-run position changes based on transactions the agent makes during the execution. Circuit will provide updated positions on the next execution request.
|
|
82
82
|
|
|
83
83
|
|
|
84
|
-
####
|
|
85
|
-
> Note: For native tokens, use the
|
|
84
|
+
#### Starting Asset setup
|
|
85
|
+
> Note: For native tokens, use the canonical native token addresses:
|
|
86
|
+
> - EVM: `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` (EIP-7528)
|
|
87
|
+
> - Solana: `11111111111111111111111111111111` (System Program)
|
|
86
88
|
```toml
|
|
87
|
-
|
|
88
|
-
[
|
|
89
|
+
# Requiring 1 SOL
|
|
90
|
+
[startingAsset]
|
|
89
91
|
network = "solana"
|
|
90
92
|
address = "11111111111111111111111111111111"
|
|
91
93
|
minimumAmount = "1000000000"
|
|
92
94
|
|
|
93
|
-
|
|
94
|
-
[
|
|
95
|
-
network = "ethereum
|
|
96
|
-
address = "
|
|
95
|
+
# Requiring 1 ETH
|
|
96
|
+
[startingAsset]
|
|
97
|
+
network = "ethereum:1"
|
|
98
|
+
address = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
|
|
97
99
|
minimumAmount = "1000000000000000000"
|
|
98
100
|
```
|
|
99
101
|
|
package/index.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ type SignAndSendRequest = {
|
|
|
18
18
|
network: Network;
|
|
19
19
|
/** Optional short message to be attached to the transaction for observability */
|
|
20
20
|
message?: string;
|
|
21
|
+
/**
|
|
22
|
+
* ISO 8601 timestamp for when the suggestion expires (only used in manual mode).
|
|
23
|
+
* If not provided, the suggestion never expires.
|
|
24
|
+
*/
|
|
25
|
+
expiresAt?: string | null;
|
|
21
26
|
} & ({
|
|
22
27
|
network: `ethereum:${number}`;
|
|
23
28
|
request: {
|
|
@@ -32,36 +37,32 @@ type SignAndSendRequest = {
|
|
|
32
37
|
};
|
|
33
38
|
});
|
|
34
39
|
/**
|
|
35
|
-
*
|
|
40
|
+
* SignAndSend response with union type for manual mode support
|
|
36
41
|
*/
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
declare const SignAndSendResponseSchema: z$1.ZodObject<{
|
|
43
|
+
success: z$1.ZodBoolean;
|
|
44
|
+
data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
45
|
+
internalTransactionId: z$1.ZodNumber;
|
|
46
|
+
txHash: z$1.ZodString;
|
|
47
|
+
transactionUrl: z$1.ZodOptional<z$1.ZodString>;
|
|
48
|
+
}, z$1.core.$strip>, z$1.ZodObject<{
|
|
49
|
+
suggested: z$1.ZodLiteral<true>;
|
|
50
|
+
suggestionId: z$1.ZodNumber;
|
|
51
|
+
details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
|
|
52
|
+
}, z$1.core.$strip>]>>;
|
|
53
|
+
error: z$1.ZodOptional<z$1.ZodString>;
|
|
54
|
+
errorMessage: z$1.ZodOptional<z$1.ZodString>;
|
|
55
|
+
errorDetails: z$1.ZodOptional<z$1.ZodObject<{
|
|
56
|
+
message: z$1.ZodOptional<z$1.ZodString>;
|
|
57
|
+
error: z$1.ZodOptional<z$1.ZodString>;
|
|
58
|
+
status: z$1.ZodOptional<z$1.ZodNumber>;
|
|
59
|
+
statusText: z$1.ZodOptional<z$1.ZodString>;
|
|
60
|
+
}, z$1.core.$strip>>;
|
|
61
|
+
}, z$1.core.$strip>;
|
|
45
62
|
/**
|
|
46
|
-
* Standard response from signAndSend operations
|
|
63
|
+
* Standard response from signAndSend operations (TypeScript type)
|
|
47
64
|
*/
|
|
48
|
-
type SignAndSendResponse =
|
|
49
|
-
/** Whether the operation was successful */
|
|
50
|
-
success: boolean;
|
|
51
|
-
/** Transaction data (only present on success) */
|
|
52
|
-
data?: SignAndSendData;
|
|
53
|
-
/** Error category from API (only present on failure) */
|
|
54
|
-
error?: string;
|
|
55
|
-
/** Detailed error message from API (only present on failure) */
|
|
56
|
-
errorMessage?: string;
|
|
57
|
-
/** Detailed error information (only present on failure) */
|
|
58
|
-
errorDetails?: {
|
|
59
|
-
message?: string;
|
|
60
|
-
error?: string;
|
|
61
|
-
status?: number;
|
|
62
|
-
statusText?: string;
|
|
63
|
-
};
|
|
64
|
-
};
|
|
65
|
+
type SignAndSendResponse = z$1.infer<typeof SignAndSendResponseSchema>;
|
|
65
66
|
/**
|
|
66
67
|
* EIP712 TypedData schema for typed message signing
|
|
67
68
|
*/
|
|
@@ -413,6 +414,7 @@ declare const SwidgeQuoteDataSchema: z$1.ZodObject<{
|
|
|
413
414
|
}, z$1.core.$strip>;
|
|
414
415
|
/**
|
|
415
416
|
* Execute request schema - takes the complete quote response from quote() method
|
|
417
|
+
* with optional manual mode options
|
|
416
418
|
*/
|
|
417
419
|
declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
|
|
418
420
|
engine: z$1.ZodString;
|
|
@@ -472,6 +474,7 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
|
|
|
472
474
|
description: z$1.ZodString;
|
|
473
475
|
signatureData: z$1.ZodString;
|
|
474
476
|
}, z$1.core.$strip>], "type">>;
|
|
477
|
+
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
475
478
|
}, z$1.core.$strip>;
|
|
476
479
|
/**
|
|
477
480
|
* Quote result constants - type QUOTE_RESULT. to see available options
|
|
@@ -564,11 +567,11 @@ declare const SwidgeQuoteResponseWrapperSchema: z$1.ZodObject<{
|
|
|
564
567
|
}, z$1.core.$strip>>;
|
|
565
568
|
}, z$1.core.$loose>;
|
|
566
569
|
/**
|
|
567
|
-
* Swidge execute response wrapper
|
|
570
|
+
* Swidge execute response wrapper with union type for manual mode support
|
|
568
571
|
*/
|
|
569
572
|
declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
|
|
570
573
|
success: z$1.ZodBoolean;
|
|
571
|
-
data: z$1.ZodOptional<z$1.ZodObject<{
|
|
574
|
+
data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
572
575
|
status: z$1.ZodString;
|
|
573
576
|
in: z$1.ZodOptional<z$1.ZodObject<{
|
|
574
577
|
network: z$1.ZodString;
|
|
@@ -580,7 +583,11 @@ declare const SwidgeExecuteResponseWrapperSchema: z$1.ZodObject<{
|
|
|
580
583
|
}, z$1.core.$strip>>;
|
|
581
584
|
lastUpdated: z$1.ZodNumber;
|
|
582
585
|
error: z$1.ZodOptional<z$1.ZodString>;
|
|
583
|
-
}, z$1.core.$strip
|
|
586
|
+
}, z$1.core.$strip>, z$1.ZodObject<{
|
|
587
|
+
suggested: z$1.ZodLiteral<true>;
|
|
588
|
+
suggestionId: z$1.ZodNumber;
|
|
589
|
+
details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
|
|
590
|
+
}, z$1.core.$strip>]>>;
|
|
584
591
|
error: z$1.ZodOptional<z$1.ZodString>;
|
|
585
592
|
errorMessage: z$1.ZodOptional<z$1.ZodString>;
|
|
586
593
|
errorDetails: z$1.ZodOptional<z$1.ZodObject<{
|
|
@@ -602,20 +609,31 @@ declare const PolymarketMarketOrderRequestSchema: z$1.ZodObject<{
|
|
|
602
609
|
BUY: "BUY";
|
|
603
610
|
SELL: "SELL";
|
|
604
611
|
}>;
|
|
612
|
+
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
605
613
|
}, z$1.core.$strip>;
|
|
606
614
|
declare const PolymarketRedeemPositionsRequestSchema: z$1.ZodObject<{
|
|
607
615
|
tokenIds: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodArray<z$1.ZodString>>>;
|
|
608
616
|
}, z$1.core.$strip>;
|
|
617
|
+
/**
|
|
618
|
+
* Polymarket market order response with union type for manual mode support
|
|
619
|
+
*/
|
|
609
620
|
declare const PolymarketMarketOrderResponseSchema: z$1.ZodObject<{
|
|
610
621
|
success: z$1.ZodBoolean;
|
|
611
|
-
data: z$1.ZodOptional<z$1.ZodObject<{
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
622
|
+
data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
623
|
+
success: z$1.ZodBoolean;
|
|
624
|
+
orderInfo: z$1.ZodObject<{
|
|
625
|
+
orderId: z$1.ZodString;
|
|
626
|
+
side: z$1.ZodString;
|
|
627
|
+
size: z$1.ZodString;
|
|
628
|
+
priceUsd: z$1.ZodString;
|
|
629
|
+
totalPriceUsd: z$1.ZodString;
|
|
630
|
+
txHashes: z$1.ZodArray<z$1.ZodString>;
|
|
631
|
+
}, z$1.core.$strip>;
|
|
632
|
+
}, z$1.core.$strip>, z$1.ZodObject<{
|
|
633
|
+
suggested: z$1.ZodLiteral<true>;
|
|
634
|
+
suggestionId: z$1.ZodNumber;
|
|
635
|
+
details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
|
|
636
|
+
}, z$1.core.$strip>]>>;
|
|
619
637
|
error: z$1.ZodOptional<z$1.ZodString>;
|
|
620
638
|
errorMessage: z$1.ZodOptional<z$1.ZodString>;
|
|
621
639
|
errorDetails: z$1.ZodOptional<z$1.ZodObject<{
|
|
@@ -662,7 +680,7 @@ declare const PolymarketRedeemPositionsResponseSchema: z$1.ZodObject<{
|
|
|
662
680
|
statusText: z$1.ZodOptional<z$1.ZodString>;
|
|
663
681
|
}, z$1.core.$strip>>;
|
|
664
682
|
}, z$1.core.$loose>;
|
|
665
|
-
type PolymarketMarketOrderRequest = z$1.
|
|
683
|
+
type PolymarketMarketOrderRequest = z$1.input<typeof PolymarketMarketOrderRequestSchema>;
|
|
666
684
|
type PolymarketRedeemPositionsRequest = z$1.infer<typeof PolymarketRedeemPositionsRequestSchema>;
|
|
667
685
|
type PolymarketMarketOrderResponse = z$1.infer<typeof PolymarketMarketOrderResponseSchema>;
|
|
668
686
|
type PolymarketRedeemPositionsResponse = z$1.infer<typeof PolymarketRedeemPositionsResponseSchema>;
|
|
@@ -691,6 +709,7 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
|
|
|
691
709
|
triggerPrice: z$1.ZodOptional<z$1.ZodNumber>;
|
|
692
710
|
reduceOnly: z$1.ZodOptional<z$1.ZodBoolean>;
|
|
693
711
|
postOnly: z$1.ZodOptional<z$1.ZodBoolean>;
|
|
712
|
+
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
694
713
|
}, z$1.core.$strip>;
|
|
695
714
|
/**
|
|
696
715
|
* Request to transfer between spot and perp accounts on Hyperliquid
|
|
@@ -698,10 +717,14 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
|
|
|
698
717
|
declare const HyperliquidTransferRequestSchema: z$1.ZodObject<{
|
|
699
718
|
amount: z$1.ZodNumber;
|
|
700
719
|
toPerp: z$1.ZodBoolean;
|
|
720
|
+
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
701
721
|
}, z$1.core.$strip>;
|
|
722
|
+
/**
|
|
723
|
+
* Hyperliquid place order response with union type for manual mode support
|
|
724
|
+
*/
|
|
702
725
|
declare const HyperliquidPlaceOrderResponseSchema: z$1.ZodObject<{
|
|
703
726
|
success: z$1.ZodBoolean;
|
|
704
|
-
data: z$1.ZodOptional<z$1.ZodObject<{
|
|
727
|
+
data: z$1.ZodOptional<z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
705
728
|
orderId: z$1.ZodString;
|
|
706
729
|
symbol: z$1.ZodString;
|
|
707
730
|
side: z$1.ZodString;
|
|
@@ -711,7 +734,11 @@ declare const HyperliquidPlaceOrderResponseSchema: z$1.ZodObject<{
|
|
|
711
734
|
status: z$1.ZodString;
|
|
712
735
|
market: z$1.ZodString;
|
|
713
736
|
clientOrderId: z$1.ZodOptional<z$1.ZodString>;
|
|
714
|
-
}, z$1.core.$strip
|
|
737
|
+
}, z$1.core.$strip>, z$1.ZodObject<{
|
|
738
|
+
suggested: z$1.ZodLiteral<true>;
|
|
739
|
+
suggestionId: z$1.ZodNumber;
|
|
740
|
+
details: z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>;
|
|
741
|
+
}, z$1.core.$strip>]>>;
|
|
715
742
|
error: z$1.ZodOptional<z$1.ZodString>;
|
|
716
743
|
}, z$1.core.$loose>;
|
|
717
744
|
declare const HyperliquidOrderResponseSchema: z$1.ZodObject<{
|
|
@@ -833,8 +860,8 @@ declare const HyperliquidLiquidationsResponseSchema: z$1.ZodObject<{
|
|
|
833
860
|
}, z$1.core.$strip>>>;
|
|
834
861
|
error: z$1.ZodOptional<z$1.ZodString>;
|
|
835
862
|
}, z$1.core.$loose>;
|
|
836
|
-
type HyperliquidPlaceOrderRequest = z$1.
|
|
837
|
-
type HyperliquidTransferRequest = z$1.
|
|
863
|
+
type HyperliquidPlaceOrderRequest = z$1.input<typeof HyperliquidPlaceOrderRequestSchema>;
|
|
864
|
+
type HyperliquidTransferRequest = z$1.input<typeof HyperliquidTransferRequestSchema>;
|
|
838
865
|
type HyperliquidPlaceOrderResponse = z$1.infer<typeof HyperliquidPlaceOrderResponseSchema>;
|
|
839
866
|
type HyperliquidOrderResponse = z$1.infer<typeof HyperliquidOrderResponseSchema>;
|
|
840
867
|
type HyperliquidDeleteOrderResponse = z$1.infer<typeof HyperliquidDeleteOrderResponseSchema>;
|
|
@@ -928,6 +955,187 @@ type MemoryGetResponse = z$1.infer<typeof MemoryGetResponseSchema>;
|
|
|
928
955
|
type MemoryDeleteResponse = z$1.infer<typeof MemoryDeleteResponseSchema>;
|
|
929
956
|
type MemoryListResponse = z$1.infer<typeof MemoryListResponseSchema>;
|
|
930
957
|
|
|
958
|
+
/**
|
|
959
|
+
* Manual execution mode types for suggested transactions.
|
|
960
|
+
*
|
|
961
|
+
* When a session is in "manual" mode, transaction operations return
|
|
962
|
+
* suggested transactions instead of executing them immediately.
|
|
963
|
+
*/
|
|
964
|
+
|
|
965
|
+
/**
|
|
966
|
+
* Execution mode for agent sessions
|
|
967
|
+
* - "auto": Transactions execute immediately (default behavior)
|
|
968
|
+
* - "manual": Transactions are stored as suggestions for user approval
|
|
969
|
+
*/
|
|
970
|
+
type ExecutionMode = "auto" | "manual";
|
|
971
|
+
/**
|
|
972
|
+
* Empty data constant for Ethereum transactions.
|
|
973
|
+
* Use this for simple transfers without any contract interaction.
|
|
974
|
+
*
|
|
975
|
+
* @example
|
|
976
|
+
* ```typescript
|
|
977
|
+
* await agent.signAndSend({
|
|
978
|
+
* network: "ethereum:1",
|
|
979
|
+
* request: {
|
|
980
|
+
* toAddress: recipientAddress,
|
|
981
|
+
* data: EMPTY_DATA,
|
|
982
|
+
* value: "1000000000000000000", // 1 ETH
|
|
983
|
+
* }
|
|
984
|
+
* });
|
|
985
|
+
* ```
|
|
986
|
+
*/
|
|
987
|
+
declare const EMPTY_DATA: "0x";
|
|
988
|
+
/**
|
|
989
|
+
* Type alias for Ethereum addresses.
|
|
990
|
+
* Ensures addresses start with "0x" followed by 40 hex characters.
|
|
991
|
+
*/
|
|
992
|
+
type EthereumAddress = `0x${string}`;
|
|
993
|
+
/**
|
|
994
|
+
* Type alias for Ethereum data/calldata.
|
|
995
|
+
* Must start with "0x" followed by even number of hex characters.
|
|
996
|
+
*/
|
|
997
|
+
type EthereumData = `0x${string}`;
|
|
998
|
+
/**
|
|
999
|
+
* Base data structure for all suggested transaction responses.
|
|
1000
|
+
* Nested under the `data` field in the response.
|
|
1001
|
+
*/
|
|
1002
|
+
interface SuggestedTransactionData {
|
|
1003
|
+
/** Indicates this is a suggested transaction, not an executed one */
|
|
1004
|
+
suggested: true;
|
|
1005
|
+
/** Unique identifier for the suggestion record */
|
|
1006
|
+
suggestionId: number;
|
|
1007
|
+
/** Transaction details for display to the user */
|
|
1008
|
+
details: Record<string, unknown>;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Type guard to check if a response is a suggested transaction
|
|
1012
|
+
*
|
|
1013
|
+
* @example
|
|
1014
|
+
* ```typescript
|
|
1015
|
+
* const swap = await agent.swidge.execute(quote.data);
|
|
1016
|
+
* if (isSuggestedTransaction(swap)) {
|
|
1017
|
+
* console.log(`Suggestion ID: ${swap.data.suggestionId}`);
|
|
1018
|
+
* } else {
|
|
1019
|
+
* console.log(`Executed: ${swap.data}`);
|
|
1020
|
+
* }
|
|
1021
|
+
* ```
|
|
1022
|
+
*/
|
|
1023
|
+
declare function isSuggestedTransaction<T extends {
|
|
1024
|
+
success: boolean;
|
|
1025
|
+
data?: unknown;
|
|
1026
|
+
}>(response: T): response is T & {
|
|
1027
|
+
success: true;
|
|
1028
|
+
data: SuggestedTransactionData;
|
|
1029
|
+
};
|
|
1030
|
+
/**
|
|
1031
|
+
* Generic type guard to check if a response is successful and has data
|
|
1032
|
+
*
|
|
1033
|
+
* @example
|
|
1034
|
+
* ```typescript
|
|
1035
|
+
* const result = await agent.memory.get("key");
|
|
1036
|
+
* if (isSuccessResponse(result)) {
|
|
1037
|
+
* // TypeScript knows result.data exists and is defined
|
|
1038
|
+
* console.log(result.data.value);
|
|
1039
|
+
* }
|
|
1040
|
+
* ```
|
|
1041
|
+
*/
|
|
1042
|
+
declare function isSuccessResponse<T>(response: {
|
|
1043
|
+
success: boolean;
|
|
1044
|
+
data?: T;
|
|
1045
|
+
error?: string;
|
|
1046
|
+
errorMessage?: string;
|
|
1047
|
+
}): response is {
|
|
1048
|
+
success: true;
|
|
1049
|
+
data: T;
|
|
1050
|
+
};
|
|
1051
|
+
/**
|
|
1052
|
+
* Type guard to check if swap data is an executed swap (not a suggestion)
|
|
1053
|
+
*
|
|
1054
|
+
* @example
|
|
1055
|
+
* ```typescript
|
|
1056
|
+
* import type { SwidgeExecuteData, SuggestedTransactionData } from "@circuitorg/agent-sdk";
|
|
1057
|
+
*
|
|
1058
|
+
* const swap = await agent.swidge.execute(quote.data);
|
|
1059
|
+
* if (swap.success && swap.data) {
|
|
1060
|
+
* if (isSwidgeExecuted(swap.data)) {
|
|
1061
|
+
* console.log(`Swap executed: ${swap.data.out?.txs[0]}`);
|
|
1062
|
+
* } else {
|
|
1063
|
+
* console.log(`Swap suggested: ${swap.data.suggestionId}`);
|
|
1064
|
+
* }
|
|
1065
|
+
* }
|
|
1066
|
+
* ```
|
|
1067
|
+
*/
|
|
1068
|
+
declare function isSwidgeExecuted(data: unknown): data is {
|
|
1069
|
+
out?: {
|
|
1070
|
+
txs?: string[];
|
|
1071
|
+
};
|
|
1072
|
+
};
|
|
1073
|
+
/**
|
|
1074
|
+
* Type guard to check if Polymarket order data is an executed order (not a suggestion)
|
|
1075
|
+
*
|
|
1076
|
+
* @example
|
|
1077
|
+
* ```typescript
|
|
1078
|
+
* const order = await agent.platforms.polymarket.marketOrder({...});
|
|
1079
|
+
* if (order.success && order.data) {
|
|
1080
|
+
* if (isPolymarketExecuted(order.data)) {
|
|
1081
|
+
* console.log(`Order executed: ${order.data.orderInfo}`);
|
|
1082
|
+
* } else {
|
|
1083
|
+
* console.log(`Order suggested: ${order.data.suggestionId}`);
|
|
1084
|
+
* }
|
|
1085
|
+
* }
|
|
1086
|
+
* ```
|
|
1087
|
+
*/
|
|
1088
|
+
declare function isPolymarketExecuted(data: unknown): data is {
|
|
1089
|
+
success: boolean;
|
|
1090
|
+
orderInfo: unknown;
|
|
1091
|
+
};
|
|
1092
|
+
/**
|
|
1093
|
+
* Type guard to check if Hyperliquid order data is an executed order (not a suggestion)
|
|
1094
|
+
*
|
|
1095
|
+
* @example
|
|
1096
|
+
* ```typescript
|
|
1097
|
+
* const order = await agent.platforms.hyperliquid.placeOrder({...});
|
|
1098
|
+
* if (order.success && order.data) {
|
|
1099
|
+
* if (isHyperliquidExecuted(order.data)) {
|
|
1100
|
+
* console.log(`Order ID: ${order.data.orderId}`);
|
|
1101
|
+
* } else {
|
|
1102
|
+
* console.log(`Order suggested: ${order.data.suggestionId}`);
|
|
1103
|
+
* }
|
|
1104
|
+
* }
|
|
1105
|
+
* ```
|
|
1106
|
+
*/
|
|
1107
|
+
declare function isHyperliquidExecuted(data: unknown): data is {
|
|
1108
|
+
orderId: string;
|
|
1109
|
+
};
|
|
1110
|
+
/**
|
|
1111
|
+
* Type guard to check if transaction data is an executed transaction (not a suggestion)
|
|
1112
|
+
*
|
|
1113
|
+
* @example
|
|
1114
|
+
* ```typescript
|
|
1115
|
+
* const tx = await agent.signAndSend({...});
|
|
1116
|
+
* if (tx.success && tx.data) {
|
|
1117
|
+
* if (isTransactionExecuted(tx.data)) {
|
|
1118
|
+
* console.log(`Tx hash: ${tx.data.txHash}`);
|
|
1119
|
+
* } else {
|
|
1120
|
+
* console.log(`Transaction suggested: ${tx.data.suggestionId}`);
|
|
1121
|
+
* }
|
|
1122
|
+
* }
|
|
1123
|
+
* ```
|
|
1124
|
+
*/
|
|
1125
|
+
declare function isTransactionExecuted(data: unknown): data is {
|
|
1126
|
+
internalTransactionId: number;
|
|
1127
|
+
txHash: string;
|
|
1128
|
+
transactionUrl?: string;
|
|
1129
|
+
};
|
|
1130
|
+
/**
|
|
1131
|
+
* Response from clearing suggested transactions
|
|
1132
|
+
*/
|
|
1133
|
+
interface ClearSuggestionsResponse {
|
|
1134
|
+
success: boolean;
|
|
1135
|
+
error?: string;
|
|
1136
|
+
errorMessage?: string;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
931
1139
|
/**
|
|
932
1140
|
* Main AgentSdk class with simplified API surface
|
|
933
1141
|
*/
|
|
@@ -1250,7 +1458,7 @@ declare class AgentSdk {
|
|
|
1250
1458
|
*/
|
|
1251
1459
|
execute: {
|
|
1252
1460
|
(executeQuote: SwidgeExecuteRequest): Promise<SwidgeExecuteResponse>;
|
|
1253
|
-
(executeQuotes: SwidgeExecuteRequest[]): Promise<SwidgeExecuteResponse[]>;
|
|
1461
|
+
(executeQuotes: SwidgeExecuteRequest[]): Promise<SwidgeExecuteResponse[] | SwidgeExecuteResponse[]>;
|
|
1254
1462
|
};
|
|
1255
1463
|
};
|
|
1256
1464
|
/**
|
|
@@ -2201,6 +2409,15 @@ declare class AgentSdk {
|
|
|
2201
2409
|
* ```
|
|
2202
2410
|
*/
|
|
2203
2411
|
getCurrentPositions(): Promise<CurrentPositionsResponse>;
|
|
2412
|
+
/**
|
|
2413
|
+
* Clear all pending suggested transactions for this session.
|
|
2414
|
+
*
|
|
2415
|
+
* Performs a soft delete by setting the `deletedAt` timestamp on all
|
|
2416
|
+
* unprocessed suggestions across all suggestion tables.
|
|
2417
|
+
*
|
|
2418
|
+
* @returns Promise resolving to ClearSuggestionsResponse
|
|
2419
|
+
*/
|
|
2420
|
+
clearSuggestedTransactions(): Promise<ClearSuggestionsResponse>;
|
|
2204
2421
|
}
|
|
2205
2422
|
|
|
2206
2423
|
/**
|
|
@@ -2220,6 +2437,7 @@ declare class APIClient {
|
|
|
2220
2437
|
private baseUrl;
|
|
2221
2438
|
private authorizationHeader?;
|
|
2222
2439
|
private isCircuitEnvironment;
|
|
2440
|
+
private getCircuitDevMode;
|
|
2223
2441
|
/**
|
|
2224
2442
|
* Create an API client.
|
|
2225
2443
|
* @param config - SDK configuration
|
|
@@ -2369,6 +2587,12 @@ declare class AgentContext {
|
|
|
2369
2587
|
readonly sessionWalletAddress: string;
|
|
2370
2588
|
/** Current positions allocated to this agent (required) */
|
|
2371
2589
|
readonly currentPositions: CurrentPosition[];
|
|
2590
|
+
/**
|
|
2591
|
+
* Execution mode for this session.
|
|
2592
|
+
* - "auto": Transactions execute immediately (default behavior)
|
|
2593
|
+
* - "manual": Transactions are stored as suggestions for user approval
|
|
2594
|
+
*/
|
|
2595
|
+
readonly executionMode: ExecutionMode;
|
|
2372
2596
|
/** Internal SDK instance */
|
|
2373
2597
|
private _sdk;
|
|
2374
2598
|
/**
|
|
@@ -2399,6 +2623,7 @@ declare class AgentContext {
|
|
|
2399
2623
|
sessionId: number;
|
|
2400
2624
|
sessionWalletAddress: string;
|
|
2401
2625
|
currentPositions: CurrentPosition[];
|
|
2626
|
+
executionMode?: ExecutionMode;
|
|
2402
2627
|
baseUrl?: string;
|
|
2403
2628
|
authorizationHeader?: string;
|
|
2404
2629
|
});
|
|
@@ -2487,6 +2712,7 @@ declare class AgentContext {
|
|
|
2487
2712
|
* **Input**: `SignAndSendRequest`
|
|
2488
2713
|
* - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
|
|
2489
2714
|
* - `message` (string | undefined): Optional context message
|
|
2715
|
+
* - `expiresAt` (string | null | undefined): ISO 8601 timestamp for suggestion expiry
|
|
2490
2716
|
* - `request` (object): Transaction payload
|
|
2491
2717
|
* - For Ethereum:
|
|
2492
2718
|
* - `toAddress` (string): Recipient address as hex string
|
|
@@ -2502,33 +2728,52 @@ declare class AgentContext {
|
|
|
2502
2728
|
*
|
|
2503
2729
|
* **Output**: `SignAndSendResponse`
|
|
2504
2730
|
* - `success` (boolean): Whether the operation succeeded
|
|
2505
|
-
* - `
|
|
2506
|
-
*
|
|
2507
|
-
*
|
|
2731
|
+
* - `data` (SignAndSendData | SuggestedTransactionData | undefined): Response data
|
|
2732
|
+
* - In auto mode: SignAndSendData with txHash, transactionUrl, etc.
|
|
2733
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
2508
2734
|
* - `error` (string | undefined): Error message on failure
|
|
2735
|
+
* - `errorMessage` (string | undefined): Detailed error message on failure
|
|
2509
2736
|
* - `errorDetails` (object | undefined): Detailed error info
|
|
2510
2737
|
*
|
|
2511
2738
|
* @param request - Transaction request with network and transaction details
|
|
2512
|
-
* @returns Promise resolving to SignAndSendResponse
|
|
2739
|
+
* @returns Promise resolving to SignAndSendResponse
|
|
2513
2740
|
*
|
|
2514
2741
|
* @example
|
|
2515
2742
|
* ```typescript
|
|
2516
|
-
*
|
|
2517
|
-
*
|
|
2743
|
+
* // Auto mode or manual mode with bypass - transaction is executed
|
|
2744
|
+
* const result = await agent.signAndSend({
|
|
2745
|
+
* network: "ethereum:8453",
|
|
2518
2746
|
* request: {
|
|
2519
|
-
* toAddress: "
|
|
2520
|
-
* data: "0x"
|
|
2521
|
-
* value: "1000000000000000000",
|
|
2522
|
-
* gas: 21000,
|
|
2523
|
-
* maxFeePerGas: "20000000000"
|
|
2747
|
+
* toAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bB70" as `0x${string}`,
|
|
2748
|
+
* data: "0x" as `0x${string}`,
|
|
2749
|
+
* value: "1000000000000000000", // 1 ETH
|
|
2524
2750
|
* },
|
|
2525
|
-
* message: "
|
|
2751
|
+
* message: "Send 1 ETH to Bob",
|
|
2526
2752
|
* });
|
|
2527
2753
|
*
|
|
2528
|
-
* if (
|
|
2529
|
-
*
|
|
2530
|
-
*
|
|
2531
|
-
*
|
|
2754
|
+
* if (result.success && result.data) {
|
|
2755
|
+
* if (isTransactionExecuted(result.data)) {
|
|
2756
|
+
* console.log(`Transaction sent: ${result.data.txHash}`);
|
|
2757
|
+
* }
|
|
2758
|
+
* }
|
|
2759
|
+
*
|
|
2760
|
+
* // Manual mode - transaction is suggested for approval
|
|
2761
|
+
* const result = await agent.signAndSend({
|
|
2762
|
+
* network: "ethereum:8453",
|
|
2763
|
+
* request: {
|
|
2764
|
+
* toAddress: recipient as `0x${string}`,
|
|
2765
|
+
* data: EMPTY_DATA,
|
|
2766
|
+
* value: amount,
|
|
2767
|
+
* },
|
|
2768
|
+
* message: "Transfer to recipient",
|
|
2769
|
+
* });
|
|
2770
|
+
*
|
|
2771
|
+
* if (result.success && result.data) {
|
|
2772
|
+
* if (isSuggestedTransaction(result)) {
|
|
2773
|
+
* console.log(`Transaction suggested (ID: ${result.data.suggestionId})`);
|
|
2774
|
+
* } else if (isTransactionExecuted(result.data)) {
|
|
2775
|
+
* console.log(`Transaction executed: ${result.data.txHash}`);
|
|
2776
|
+
* }
|
|
2532
2777
|
* }
|
|
2533
2778
|
* ```
|
|
2534
2779
|
*/
|
|
@@ -2732,17 +2977,23 @@ declare class AgentContext {
|
|
|
2732
2977
|
* - `tokenId` (string): Market token ID for the position
|
|
2733
2978
|
* - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
|
|
2734
2979
|
* - `side` ("BUY" | "SELL"): Order side
|
|
2980
|
+
* - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
|
|
2735
2981
|
*
|
|
2736
2982
|
* **Output**: `PolymarketMarketOrderResponse`
|
|
2737
2983
|
* - `success` (boolean): Whether the operation was successful
|
|
2738
|
-
* - `data
|
|
2739
|
-
*
|
|
2984
|
+
* - `data` (PolymarketMarketOrderData | SuggestedTransactionData | undefined): Response data
|
|
2985
|
+
* - In auto mode: PolymarketMarketOrderData with orderInfo (orderId, side, priceUsd, txHashes)
|
|
2986
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
2987
|
+
* - `error` (string | undefined): Error message on failure
|
|
2988
|
+
* - `errorMessage` (string | undefined): Detailed error message on failure
|
|
2740
2989
|
*
|
|
2741
2990
|
* @param request - Order parameters (tokenId, size, side)
|
|
2742
|
-
* @returns Promise resolving to PolymarketMarketOrderResponse with order details
|
|
2991
|
+
* @returns Promise resolving to PolymarketMarketOrderResponse with order details or suggestion
|
|
2743
2992
|
*
|
|
2744
2993
|
* @example
|
|
2745
2994
|
* ```typescript
|
|
2995
|
+
* import { isSuggestedTransaction, isPolymarketExecuted } from "@circuitorg/agent-sdk";
|
|
2996
|
+
*
|
|
2746
2997
|
* // BUY order - size is USD amount
|
|
2747
2998
|
* const buyResult = await agent.platforms.polymarket.marketOrder({
|
|
2748
2999
|
* tokenId: "123456",
|
|
@@ -2751,8 +3002,14 @@ declare class AgentContext {
|
|
|
2751
3002
|
* });
|
|
2752
3003
|
*
|
|
2753
3004
|
* if (buyResult.success && buyResult.data) {
|
|
2754
|
-
*
|
|
2755
|
-
*
|
|
3005
|
+
* if (isSuggestedTransaction(buyResult)) {
|
|
3006
|
+
* await agent.log(`Order suggested (ID: ${buyResult.data.suggestionId})`);
|
|
3007
|
+
* } else if (isPolymarketExecuted(buyResult.data)) {
|
|
3008
|
+
* await agent.log(`Order ID: ${buyResult.data.orderInfo.orderId}`);
|
|
3009
|
+
* await agent.log(`Total: $${buyResult.data.orderInfo.totalPriceUsd}`);
|
|
3010
|
+
* }
|
|
3011
|
+
* } else {
|
|
3012
|
+
* await agent.log(`Order failed: ${buyResult.errorMessage}`, { error: true });
|
|
2756
3013
|
* }
|
|
2757
3014
|
*
|
|
2758
3015
|
* // SELL order - size is number of shares
|
|
@@ -2813,7 +3070,7 @@ declare class AgentContext {
|
|
|
2813
3070
|
* Submit a market, limit, stop, or take-profit order for perpetuals or spot trading.
|
|
2814
3071
|
*
|
|
2815
3072
|
* **Input**: `HyperliquidPlaceOrderRequest`
|
|
2816
|
-
* - `symbol` (string): Trading pair symbol (e.g., "BTC
|
|
3073
|
+
* - `symbol` (string): Trading pair symbol (e.g., "BTC", "ETH")
|
|
2817
3074
|
* - `side` ("buy" | "sell"): Order side
|
|
2818
3075
|
* - `size` (number): Order size
|
|
2819
3076
|
* - `price` (number): Order price (for market orders, acts as slippage limit)
|
|
@@ -2822,29 +3079,26 @@ declare class AgentContext {
|
|
|
2822
3079
|
* - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
|
|
2823
3080
|
* - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
|
|
2824
3081
|
* - `postOnly` (boolean, optional): Whether this is a post-only order
|
|
3082
|
+
* - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
|
|
2825
3083
|
*
|
|
2826
3084
|
* **Output**: `HyperliquidPlaceOrderResponse`
|
|
2827
3085
|
* - `success` (boolean): Whether the operation was successful
|
|
2828
|
-
* - `data` (HyperliquidOrderInfo | undefined):
|
|
2829
|
-
* -
|
|
2830
|
-
* -
|
|
2831
|
-
* - `data.side` ("buy" | "sell"): Order side
|
|
2832
|
-
* - `data.price` (number): Order price
|
|
2833
|
-
* - `data.size` (number): Order size
|
|
2834
|
-
* - `data.filled` (number): Filled amount
|
|
2835
|
-
* - `data.status` (string): Order status
|
|
2836
|
-
* - `data.market` ("perp" | "spot"): Market type
|
|
2837
|
-
* - `data.clientOrderId` (string | undefined): Client order ID
|
|
3086
|
+
* - `data` (HyperliquidOrderInfo | SuggestedTransactionData | undefined): Response data
|
|
3087
|
+
* - In auto mode: HyperliquidOrderInfo with orderId, symbol, side, price, size, filled, status, market, clientOrderId
|
|
3088
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
2838
3089
|
* - `error` (string | undefined): Error message (only present on failure)
|
|
3090
|
+
* - `errorMessage` (string | undefined): Detailed error message (only present on failure)
|
|
2839
3091
|
*
|
|
2840
3092
|
* @param request - Order parameters
|
|
2841
3093
|
* @returns Promise resolving to HyperliquidPlaceOrderResponse
|
|
2842
3094
|
*
|
|
2843
3095
|
* @example
|
|
2844
3096
|
* ```ts
|
|
3097
|
+
* import { isSuggestedTransaction, isHyperliquidExecuted } from "@circuitorg/agent-sdk";
|
|
3098
|
+
*
|
|
2845
3099
|
* // Market order
|
|
2846
3100
|
* const result = await agent.platforms.hyperliquid.placeOrder({
|
|
2847
|
-
* symbol: "BTC
|
|
3101
|
+
* symbol: "BTC",
|
|
2848
3102
|
* side: "buy",
|
|
2849
3103
|
* size: 0.0001,
|
|
2850
3104
|
* price: 110000,
|
|
@@ -2852,19 +3106,31 @@ declare class AgentContext {
|
|
|
2852
3106
|
* type: "market",
|
|
2853
3107
|
* });
|
|
2854
3108
|
*
|
|
3109
|
+
* if (result.success && result.data) {
|
|
3110
|
+
* if (isSuggestedTransaction(result)) {
|
|
3111
|
+
* await agent.log(`Order suggested (ID: ${result.data.suggestionId})`);
|
|
3112
|
+
* } else if (isHyperliquidExecuted(result.data)) {
|
|
3113
|
+
* await agent.log(`Order placed: ${result.data.orderId}`);
|
|
3114
|
+
* await agent.log(`Status: ${result.data.status}`);
|
|
3115
|
+
* }
|
|
3116
|
+
* } else {
|
|
3117
|
+
* await agent.log(`Order failed: ${result.errorMessage}`, { error: true });
|
|
3118
|
+
* }
|
|
3119
|
+
*
|
|
2855
3120
|
* // Limit order
|
|
2856
|
-
* const
|
|
2857
|
-
* symbol: "BTC
|
|
3121
|
+
* const limitResult = await agent.platforms.hyperliquid.placeOrder({
|
|
3122
|
+
* symbol: "BTC",
|
|
2858
3123
|
* side: "buy",
|
|
2859
3124
|
* size: 0.0001,
|
|
2860
3125
|
* price: 100000,
|
|
2861
3126
|
* market: "perp",
|
|
2862
3127
|
* type: "limit",
|
|
2863
3128
|
* });
|
|
2864
|
-
*
|
|
2865
|
-
*
|
|
2866
|
-
*
|
|
2867
|
-
*
|
|
3129
|
+
* * await agent.log(`Order suggested: ${result.data.suggestionId}`);
|
|
3130
|
+
* } else {
|
|
3131
|
+
* await agent.log(`Order placed: ${result.data.orderId}`);
|
|
3132
|
+
* await agent.log(`Status: ${result.data.status}`);
|
|
3133
|
+
* }
|
|
2868
3134
|
* } else {
|
|
2869
3135
|
* await agent.log(`Error: ${result.error}`, { error: true });
|
|
2870
3136
|
* }
|
|
@@ -3249,34 +3515,47 @@ declare class AgentContext {
|
|
|
3249
3515
|
* **Input**: `SwidgeQuoteData | SwidgeQuoteData[]` - Complete quote object(s) from agent.swidge.quote()
|
|
3250
3516
|
*
|
|
3251
3517
|
* **Output**: `SwidgeExecuteResponse | SwidgeExecuteResponse[]` (matching input type)
|
|
3252
|
-
* - `success
|
|
3253
|
-
* - `data
|
|
3254
|
-
*
|
|
3518
|
+
* - `success` (boolean): Whether the execution was successful
|
|
3519
|
+
* - `data` (SwidgeExecuteData | SuggestedTransactionData | undefined): Response data
|
|
3520
|
+
* - In auto mode: SwidgeExecuteData with status ("success", "failure", "refund", "delayed") and transaction hashes
|
|
3521
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
3522
|
+
* - `error` (string | undefined): Error message if execution failed
|
|
3523
|
+
* - `errorMessage` (string | undefined): Detailed error message if execution failed
|
|
3255
3524
|
*
|
|
3256
3525
|
* @param quoteData - Complete quote object(s) from agent.swidge.quote()
|
|
3257
3526
|
* @returns Promise resolving to SwidgeExecuteResponse with transaction status
|
|
3258
3527
|
*
|
|
3259
3528
|
* @example
|
|
3260
3529
|
* ```typescript
|
|
3261
|
-
*
|
|
3530
|
+
* import { isSuggestedTransaction, isSwidgeExecuted } from "@circuitorg/agent-sdk";
|
|
3531
|
+
*
|
|
3532
|
+
* // Single execution with type guards
|
|
3262
3533
|
* const quote = await agent.swidge.quote({...});
|
|
3263
3534
|
* if (quote.success && quote.data) {
|
|
3264
3535
|
* const result = await agent.swidge.execute(quote.data);
|
|
3536
|
+
*
|
|
3265
3537
|
* if (result.success && result.data) {
|
|
3266
|
-
*
|
|
3267
|
-
* if (result
|
|
3268
|
-
* await agent.log(`
|
|
3538
|
+
* // Use type guard to check if transaction was suggested
|
|
3539
|
+
* if (isSuggestedTransaction(result)) {
|
|
3540
|
+
* await agent.log(`Swap suggested (ID: ${result.data.suggestionId})`);
|
|
3541
|
+
* } else if (isSwidgeExecuted(result.data)) {
|
|
3542
|
+
* await agent.log(`Swap status: ${result.data.status}`);
|
|
3543
|
+
* if (result.data.status === "success" && result.data.out?.txs) {
|
|
3544
|
+
* await agent.log(`Tx hash: ${result.data.out.txs[0]}`);
|
|
3545
|
+
* }
|
|
3269
3546
|
* }
|
|
3547
|
+
* } else {
|
|
3548
|
+
* await agent.log(`Swap failed: ${result.errorMessage}`, { error: true });
|
|
3270
3549
|
* }
|
|
3271
3550
|
* }
|
|
3272
3551
|
*
|
|
3273
3552
|
* // Bulk execution
|
|
3274
3553
|
* const results = await agent.swidge.execute([quote.data, quote2.data]);
|
|
3275
|
-
* results.
|
|
3276
|
-
* if (result.success && result.data) {
|
|
3554
|
+
* for (const [index, result] of results.entries()) {
|
|
3555
|
+
* if (result.success && result.data && isSwidgeExecuted(result.data)) {
|
|
3277
3556
|
* console.log(`Swap ${index + 1} status: ${result.data.status}`);
|
|
3278
3557
|
* }
|
|
3279
|
-
* }
|
|
3558
|
+
* }
|
|
3280
3559
|
* ```
|
|
3281
3560
|
*/
|
|
3282
3561
|
execute: {
|
|
@@ -3333,6 +3612,41 @@ declare class AgentContext {
|
|
|
3333
3612
|
* ```
|
|
3334
3613
|
*/
|
|
3335
3614
|
transactions(): Promise<TransactionsResponse>;
|
|
3615
|
+
/**
|
|
3616
|
+
* Clear all pending suggested transactions for this session.
|
|
3617
|
+
*
|
|
3618
|
+
* This performs a soft delete by setting the `deletedAt` timestamp on all
|
|
3619
|
+
* unprocessed suggestions. Useful for clearing stale suggestions before
|
|
3620
|
+
* creating new ones or when the agent's strategy has changed.
|
|
3621
|
+
*
|
|
3622
|
+
* **Best Practice**: Call this at the start of your run() function when in
|
|
3623
|
+
* manual mode to ensure you're working with a clean slate.
|
|
3624
|
+
*
|
|
3625
|
+
* **Output**: `ClearSuggestionsResponse`
|
|
3626
|
+
* - `success` (boolean): Whether the operation succeeded
|
|
3627
|
+
* - `error` (string | undefined): Error message on failure
|
|
3628
|
+
* - `errorMessage` (string | undefined): Detailed error message on failure
|
|
3629
|
+
*
|
|
3630
|
+
* @returns Promise resolving to ClearSuggestionsResponse
|
|
3631
|
+
*
|
|
3632
|
+
* @example
|
|
3633
|
+
* ```typescript
|
|
3634
|
+
* async function run(agent: AgentContext): Promise<void> {
|
|
3635
|
+
* // Clear any stale suggestions from previous runs
|
|
3636
|
+
* await agent.clearSuggestedTransactions();
|
|
3637
|
+
*
|
|
3638
|
+
* // Now create fresh suggestions
|
|
3639
|
+
* await agent.signAndSend({...});
|
|
3640
|
+
* await agent.platforms.polymarket.marketOrder({...});
|
|
3641
|
+
* }
|
|
3642
|
+
*
|
|
3643
|
+
* async function unwind(agent: AgentContext): Promise<void> {
|
|
3644
|
+
* // Clear suggestions when stopping
|
|
3645
|
+
* await agent.clearSuggestedTransactions();
|
|
3646
|
+
* }
|
|
3647
|
+
* ```
|
|
3648
|
+
*/
|
|
3649
|
+
clearSuggestedTransactions(): Promise<ClearSuggestionsResponse>;
|
|
3336
3650
|
/**
|
|
3337
3651
|
* Get current live positions for the session.
|
|
3338
3652
|
*
|
|
@@ -3561,4 +3875,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
|
|
|
3561
3875
|
*/
|
|
3562
3876
|
declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
|
|
3563
3877
|
|
|
3564
|
-
export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, type EnrichedPosition, type HyperliquidBalancesResponse, type HyperliquidDeleteOrderResponse, type HyperliquidHistoricalOrdersResponse, type HyperliquidLiquidationsResponse, type HyperliquidOpenOrdersResponse, type HyperliquidOrderFillsResponse, type HyperliquidOrderResponse, type HyperliquidPlaceOrderRequest, type HyperliquidPlaceOrderResponse, type HyperliquidPositionsResponse, type HyperliquidTransferRequest, type HyperliquidTransferResponse, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, SwidgeExecuteRequestSchema, type SwidgeExecuteResponse, SwidgeExecuteResponseWrapperSchema, type SwidgeQuoteRequest, SwidgeQuoteRequestSchema, type SwidgeQuoteResponse, SwidgeQuoteResponseWrapperSchema, type SwidgeQuoteResult, type TransactionsResponse, type UnwindFunctionContract, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
|
|
3878
|
+
export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type ClearSuggestionsResponse, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, EMPTY_DATA, type EnrichedPosition, type EthereumAddress, type EthereumData, type ExecutionMode, type HyperliquidBalancesResponse, type HyperliquidDeleteOrderResponse, type HyperliquidHistoricalOrdersResponse, type HyperliquidLiquidationsResponse, type HyperliquidOpenOrdersResponse, type HyperliquidOrderFillsResponse, type HyperliquidOrderResponse, type HyperliquidPlaceOrderRequest, type HyperliquidPlaceOrderResponse, type HyperliquidPositionsResponse, type HyperliquidTransferRequest, type HyperliquidTransferResponse, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type SuggestedTransactionData, SwidgeExecuteRequestSchema, type SwidgeExecuteResponse, SwidgeExecuteResponseWrapperSchema, type SwidgeQuoteRequest, SwidgeQuoteRequestSchema, type SwidgeQuoteResponse, SwidgeQuoteResponseWrapperSchema, type SwidgeQuoteResult, type TransactionsResponse, type UnwindFunctionContract, getChainIdFromNetwork, isEthereumNetwork, isHyperliquidExecuted, isPolymarketExecuted, isSolanaNetwork, isSuccessResponse, isSuggestedTransaction, isSwidgeExecuted, isTransactionExecuted, type runFunctionContract };
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCircuitEnvironment(){return!("undefined"==typeof process||!process.env||"circuit"!==process.env.CIRCUIT_ENVIRONMENT&&void 0===process.env.AWS_LAMBDA_FUNCTION_NAME&&void 0===process.env.LAMBDA_TASK_ROOT&&void 0===process.env.AWS_EXECUTION_ENV)}constructor(r){this.config=r;const e=this.isCircuitEnvironment(),t=e?"http://transaction-service.agent.internal":"https://agents.circuit.org";this.baseUrl=r.baseUrl||t,console.log("[Circuit SDK] Environment: "+(e?"Circuit (internal)":"Local (public)"),{CIRCUIT_ENVIRONMENT:process.env?.CIRCUIT_ENVIRONMENT??"not set",baseUrl:this.baseUrl}),this.authorizationHeader=r.authorizationHeader}getAgentSlug(){if("undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG)return process.env.CIRCUIT_AGENT_SLUG}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCircuitEnvironment())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json","User-Agent":"circuit-agent-sdk/1.0",Accept:"*/*",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${r}`,o=9e5,n=new AbortController,a=setTimeout(()=>n.abort(),o),i={...e,headers:t,signal:n.signal};console.log("[Circuit SDK] ========== OUTGOING REQUEST =========="),console.log(`[Circuit SDK] ${e.method||"GET"} ${s}`),console.log("[Circuit SDK] Headers:",JSON.stringify(t,null,2)),e.body&&console.log("[Circuit SDK] Body:",e.body),console.log("[Circuit SDK] Environment:",{CIRCUIT_ENVIRONMENT:process.env?.CIRCUIT_ENVIRONMENT??"NOT SET",CIRCUIT_AGENT_SLUG:process.env?.CIRCUIT_AGENT_SLUG??"NOT SET",isCircuitEnvironment:this.isCircuitEnvironment()}),console.log("[Circuit SDK] =====================================");try{const r=await fetch(s,i);if(clearTimeout(a),console.log("[Circuit SDK] ========== RESPONSE =========="),console.log(`[Circuit SDK] Status: ${r.status} ${r.statusText}`),console.log("[Circuit SDK] Response Headers:",Object.fromEntries(r.headers.entries())),!r.ok){const e=await r.text();console.log("[Circuit SDK] Error Body:",e),console.log("[Circuit SDK] ==============================");let t={};try{t=JSON.parse(e)}catch{t={error:e}}const s=t.error||`HTTP ${r.status}: ${r.statusText}`,o=new Error(s);throw o.error=t.error,o.errorMessage=t.error,o.errorDetails=t,o.statusCode=r.status,o}const e=await r.json();return console.log("[Circuit SDK] Success Body:",JSON.stringify(e).slice(0,500)),console.log("[Circuit SDK] =============================="),e}catch(e){if(clearTimeout(a),console.log("[Circuit SDK] ========== REQUEST ERROR =========="),console.log("[Circuit SDK] Error:",e),console.log("[Circuit SDK] ==================================="),e instanceof Error){if("AbortError"===e.name||e.message.includes("aborted")){const e=new Error(`Request timeout after 900s to ${s}`);throw e.error="Request Timeout",e.errorMessage=`Request to ${s} timed out after 900 seconds`,e.errorDetails={url:s,endpoint:r,timeout:o,baseUrl:this.baseUrl},e}if(e.message.includes("fetch failed")||e.message.includes("ECONNREFUSED")||e.message.includes("ENOTFOUND")||e.message.includes("getaddrinfo")||e.message.includes("network")){const t=new Error(`Network error: ${e.message}. URL: ${s}`);throw t.error="Network Error",t.errorMessage=`Failed to connect to ${s}: ${e.message}`,t.errorDetails={url:s,endpoint:r,baseUrl:this.baseUrl,originalError:e.message,isCircuitEnvironment:this.isCircuitEnvironment()},t}}throw e}}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var n=class{client;config;constructor(r){this.config=r,this.client=new e(r)}setBaseUrl(r){this.config.baseUrl=r,this.client=new e(this.config)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=(await this.client.post("/v1/transactions/evm",r)).data,t=(await this.client.post(`/v1/transactions/evm/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=(await this.client.post("/v1/transactions/solana",r)).data,t=(await this.client.post(`/v1/transactions/solana/${e.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:e.id,txHash:t.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return await this.client.post("/v1/swap/quote",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{return await this.client.post("/v1/swap/execute",r)}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},n=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{return await this.client.post("/v1/platforms/polymarket/market-order",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{return await this.client.post("/v1/platforms/hyperliquid/order",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return await this.client.post(`/v1/memory/${r}`,{value:e})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return await this.client.get(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return await this.client.delete(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}};import{existsSync as a,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.t=new n({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}setBaseUrl(r){this.t.setBaseUrl(r)}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,n;const a=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,a,2),n=JSON.stringify(r,a)):(o=String(r),n=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{return await this.t._sendLog([{type:i,message:n}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),m=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p),unwindPositions:h.array(p).optional()}),f=(h.object({status:h.string()}),class{app;runFunction;unwindFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.unwindFunction=r.unwindFunction,this.app.use("*",d()),this.setupRoutes()}defaultUnwindFunction=async(r,e)=>{await r.log(`Unwind requested for session ${r.sessionId} (positions=${e.length}), but no unwindFunction was provided`)};async executeWithJobTracking(r,e,t,s){let o,n=!1;try{const o=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:s});if("unwind"===e){const e=r.unwindPositions??r.currentPositions;await t(o,e)}else await t(o);n=!0}catch(r){o=this.getErrorMessage(r),n=!1,console.error(`Agent ${e} function error:`,o)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,n?"success":"failed",o,s)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const a=new n({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await a._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await a._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/unwind",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.unwindFunction||this.defaultUnwindFunction;return await this.executeWithJobTracking(e,"unwind",s,t),r.json({success:!0,message:"Unwind completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(a(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /unwind"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:this.app.fetch.bind(this.app)}}});import{z as g}from"zod";var w=g.templateLiteral(["ethereum:",g.coerce.number().int().nonnegative()]),E=g.union([g.literal("solana"),w]),v=g.object({address:g.string(),network:E}),S=g.object({from:v,to:v,fromToken:g.string().optional(),toToken:g.string().optional(),amount:g.string(),slippage:g.string().optional()}),D=g.object({network:E,address:g.string(),token:g.string().nullable(),name:g.string().optional(),symbol:g.string().optional(),decimals:g.number().optional(),amount:g.string().optional(),minimumAmount:g.string().optional(),amountFormatted:g.string().optional(),amountUsd:g.string().optional()}),T=g.object({usd:g.string().optional(),percentage:g.string().optional()}),O=g.object({name:g.string(),amount:g.string().optional(),amountFormatted:g.string().optional(),amountUsd:g.string().optional()}),k=(g.object({programId:g.string(),keys:g.array(g.object({pubkey:g.string(),isSigner:g.boolean(),isWritable:g.boolean()})),data:g.union([g.string(),g.instanceof(Buffer)])}),g.object({type:g.literal("evm"),from:g.string().regex(/^0x[a-fA-F0-9]{40}$/),to:g.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:g.number(),value:g.string(),data:g.string().regex(/^0x[a-fA-F0-9]*$/),gas:g.number().nullish(),maxFeePerGas:g.number().nullish(),maxPriorityFeePerGas:g.number().nullish()})),F=g.object({type:g.literal("solana"),serializedTransaction:g.string()}),U=g.object({type:g.literal("transaction"),description:g.string(),transactionDetails:g.union([k,F])}),$=g.object({type:g.literal("signature"),description:g.string(),signatureData:g.string()}),b=g.discriminatedUnion("type",[U,$]),A=g.object({engine:g.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:D,assetReceive:D,priceImpact:T,fees:g.array(O),steps:g.array(b)}),C=A,M=g.object({network:g.string(),txs:g.array(g.string())}),q=g.object({status:g.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:M.optional(),out:M.optional(),lastUpdated:g.number(),error:g.string().optional()}),N={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},I=r=>g.object({success:g.boolean(),data:r.optional(),error:g.string().optional(),errorMessage:g.string().optional(),errorDetails:g.object({message:g.string().optional(),error:g.string().optional(),status:g.number().optional(),statusText:g.string().optional()}).optional()}).passthrough(),K=I(A),P=I(q);export{e as APIClient,f as Agent,y as AgentContext,n as AgentSdk,N as QUOTE_RESULT,C as SwidgeExecuteRequestSchema,P as SwidgeExecuteResponseWrapperSchema,S as SwidgeQuoteRequestSchema,K as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
|
|
1
|
+
import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCircuitEnvironment(){return!("undefined"==typeof process||!process.env||"circuit"!==process.env.CIRCUIT_ENVIRONMENT&&void 0===process.env.AWS_LAMBDA_FUNCTION_NAME&&void 0===process.env.LAMBDA_TASK_ROOT&&void 0===process.env.AWS_EXECUTION_ENV)}getCircuitDevMode(){if("undefined"!=typeof process&&process.env)return process.env.CIRCUIT_DEV_MODE}constructor(r){this.config=r;const e=this.getCircuitDevMode(),t=this.isCircuitEnvironment();let s,o;"local"===e?(s="http://localhost:4001",o="Dev Local"):t?(s="http://transaction-service.agent.internal",o="Circuit (internal)"):(s="https://agents.circuit.org",o="Local (public)"),this.baseUrl=r.baseUrl||s,this.authorizationHeader=r.authorizationHeader}getAgentSlug(){if("undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG)return process.env.CIRCUIT_AGENT_SLUG}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCircuitEnvironment())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return"undefined"!=typeof process&&process.env?.CIRCUIT_DEV_API_KEY&&(r["X-API-Key"]=process.env.CIRCUIT_DEV_API_KEY),r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json","User-Agent":"circuit-agent-sdk/1.0",Accept:"*/*",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${r}`,o=9e5,n=new AbortController,a=setTimeout(()=>n.abort(),o),i={...e,headers:t,signal:n.signal};try{const r=await fetch(s,i);if(clearTimeout(a),!r.ok){const e=await r.text();let t={};try{t=JSON.parse(e)}catch{t={error:e}}const s=t.error||`HTTP ${r.status}: ${r.statusText}`,o=new Error(s);throw o.error=t.error,o.errorMessage=t.error,o.errorDetails=t,o.statusCode=r.status,o}return await r.json()}catch(e){if(clearTimeout(a),e instanceof Error){if("AbortError"===e.name||e.message.includes("aborted")){const e=new Error(`Request timeout after 900s to ${s}`);throw e.error="Request Timeout",e.errorMessage=`Request to ${s} timed out after 900 seconds`,e.errorDetails={url:s,endpoint:r,timeout:o,baseUrl:this.baseUrl},e}if(e.message.includes("fetch failed")||e.message.includes("ECONNREFUSED")||e.message.includes("ENOTFOUND")||e.message.includes("getaddrinfo")||e.message.includes("network")){const t=new Error(`Network error: ${e.message}. URL: ${s}`);throw t.error="Network Error",t.errorMessage=`Failed to connect to ${s}: ${e.message}`,t.errorDetails={url:s,endpoint:r,baseUrl:this.baseUrl,originalError:e.message,isCircuitEnvironment:this.isCircuitEnvironment()},t}}throw e}}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var n=class{client;config;constructor(r){this.config=r,this.client=new e(r)}setBaseUrl(r){this.config.baseUrl=r,this.client=new e(this.config)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message,expiresAt:r.expiresAt??null})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message,expiresAt:r.expiresAt??null});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=(await this.client.post("/v1/transactions/evm",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/evm/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=(await this.client.post("/v1/transactions/solana",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/solana/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return await this.client.post("/v1/swap/quote",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{return await this.client.post("/v1/swap/execute",r)}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},n=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{const e=await this.client.post("/v1/platforms/polymarket/market-order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{const e=await this.client.post("/v1/platforms/hyperliquid/order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return await this.client.post(`/v1/memory/${r}`,{value:e})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return await this.client.get(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return await this.client.delete(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async clearSuggestedTransactions(){try{return await this.client.delete("/v1/sessions/suggestions")}catch(r){const e=r.error,t=r.errorMessage,s=r instanceof Error?r.message:"Failed to clear suggested transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||s}}}};import{existsSync as a,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;executionMode;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.executionMode=r.executionMode??"auto",this.t=new n({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}setBaseUrl(r){this.t.setBaseUrl(r)}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,n;const a=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,a,2),n=JSON.stringify(r,a)):(o=String(r),n=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{return await this.t._sendLog([{type:i,message:n}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async clearSuggestedTransactions(){return this.t.clearSuggestedTransactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),g=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p),unwindPositions:h.array(p).optional(),executionMode:h.enum(["auto","manual"]).default("auto")}),m=(h.object({status:h.string()}),class{app;runFunction;unwindFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.unwindFunction=r.unwindFunction,this.app.use("*",d()),this.setupRoutes()}defaultUnwindFunction=async(r,e)=>{await r.log(`Unwind requested for session ${r.sessionId} (positions=${e.length}), but no unwindFunction was provided`)};async executeWithJobTracking(r,e,t,s){let o,n=!1;try{const o=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,executionMode:r.executionMode,authorizationHeader:s});if("unwind"===e){const e=r.unwindPositions??r.currentPositions;await t(o,e)}else await t(o);n=!0}catch(r){o=this.getErrorMessage(r),n=!1,console.error(`Agent ${e} function error:`,o)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,n?"success":"failed",o,s)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const a=new n({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await a._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await a._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/unwind",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.unwindFunction||this.defaultUnwindFunction;return await this.executeWithJobTracking(e,"unwind",s,t),r.json({success:!0,message:"Unwind completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(a(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /unwind"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:this.app.fetch.bind(this.app)}}});import{z as f}from"zod";f.enum(["auto","manual"]);var w="0x",E=f.object({suggested:f.literal(!0),suggestionId:f.number(),details:f.record(f.string(),f.unknown())});function v(r){return!0===r.success&&"data"in r&&"object"==typeof r.data&&null!==r.data&&"suggested"in r.data&&!0===r.data.suggested}function D(r){return r.success&&void 0!==r.data}function k(r){return"object"==typeof r&&null!==r&&"out"in r&&!("suggested"in r)}function F(r){return"object"==typeof r&&null!==r&&"orderInfo"in r&&!("suggested"in r)}function b(r){return"object"==typeof r&&null!==r&&"orderId"in r&&!("suggested"in r)}function T(r){return"object"==typeof r&&null!==r&&"txHash"in r&&!("suggested"in r)}f.object({success:f.boolean(),error:f.string().optional(),errorMessage:f.string().optional()});import{z as S}from"zod";var O=S.templateLiteral(["ethereum:",S.coerce.number().int().nonnegative()]),M=S.union([S.literal("solana"),O]),A=S.object({address:S.string(),network:M}),$=S.object({from:A,to:A,fromToken:S.string().optional(),toToken:S.string().optional(),amount:S.string(),slippage:S.string().optional()}),U=S.object({network:M,address:S.string(),token:S.string().nullable(),name:S.string().optional(),symbol:S.string().optional(),decimals:S.number().optional(),amount:S.string().optional(),minimumAmount:S.string().optional(),amountFormatted:S.string().optional(),amountUsd:S.string().optional()}),q=S.object({usd:S.string().optional(),percentage:S.string().optional()}),x=S.object({name:S.string(),amount:S.string().optional(),amountFormatted:S.string().optional(),amountUsd:S.string().optional()}),I=(S.object({programId:S.string(),keys:S.array(S.object({pubkey:S.string(),isSigner:S.boolean(),isWritable:S.boolean()})),data:S.union([S.string(),S.instanceof(Buffer)])}),S.object({type:S.literal("evm"),from:S.string().regex(/^0x[a-fA-F0-9]{40}$/),to:S.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:S.number(),value:S.string(),data:S.string().regex(/^0x[a-fA-F0-9]*$/),gas:S.number().nullish(),maxFeePerGas:S.number().nullish(),maxPriorityFeePerGas:S.number().nullish()})),P=S.object({type:S.literal("solana"),serializedTransaction:S.string()}),j=S.object({type:S.literal("transaction"),description:S.string(),transactionDetails:S.union([I,P])}),N=S.object({type:S.literal("signature"),description:S.string(),signatureData:S.string()}),H=S.discriminatedUnion("type",[j,N]),C=S.object({engine:S.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:U,assetReceive:U,priceImpact:q,fees:S.array(x),steps:S.array(H)}),_=C.extend({expiresAt:S.string().datetime().optional().nullable().default(null)}),K=S.object({network:S.string(),txs:S.array(S.string())}),L=S.object({status:S.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:K.optional(),out:K.optional(),lastUpdated:S.number(),error:S.string().optional()}),R={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},G=r=>S.object({success:S.boolean(),data:r.optional(),error:S.string().optional(),errorMessage:S.string().optional(),errorDetails:S.object({message:S.string().optional(),error:S.string().optional(),status:S.number().optional(),statusText:S.string().optional()}).optional()}).passthrough(),z=G(C),W=G(S.union([L,E]));export{e as APIClient,m as Agent,y as AgentContext,n as AgentSdk,w as EMPTY_DATA,R as QUOTE_RESULT,_ as SwidgeExecuteRequestSchema,W as SwidgeExecuteResponseWrapperSchema,$ as SwidgeQuoteRequestSchema,z as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,b as isHyperliquidExecuted,F as isPolymarketExecuted,s as isSolanaNetwork,D as isSuccessResponse,v as isSuggestedTransaction,k as isSwidgeExecuted,T as isTransactionExecuted};
|