@circuitorg/agent-sdk 1.3.9 → 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 +5 -19
- 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,11 +18,6 @@ type SignAndSendRequest = {
|
|
|
18
18
|
network: Network;
|
|
19
19
|
/** Optional short message to be attached to the transaction for observability */
|
|
20
20
|
message?: string;
|
|
21
|
-
/**
|
|
22
|
-
* When true, forces immediate execution even if session is in manual mode.
|
|
23
|
-
* @default false
|
|
24
|
-
*/
|
|
25
|
-
bypassManualApproval?: boolean;
|
|
26
21
|
/**
|
|
27
22
|
* ISO 8601 timestamp for when the suggestion expires (only used in manual mode).
|
|
28
23
|
* If not provided, the suggestion never expires.
|
|
@@ -479,7 +474,6 @@ declare const SwidgeExecuteRequestSchema: z$1.ZodObject<{
|
|
|
479
474
|
description: z$1.ZodString;
|
|
480
475
|
signatureData: z$1.ZodString;
|
|
481
476
|
}, z$1.core.$strip>], "type">>;
|
|
482
|
-
bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
|
|
483
477
|
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
484
478
|
}, z$1.core.$strip>;
|
|
485
479
|
/**
|
|
@@ -615,7 +609,6 @@ declare const PolymarketMarketOrderRequestSchema: z$1.ZodObject<{
|
|
|
615
609
|
BUY: "BUY";
|
|
616
610
|
SELL: "SELL";
|
|
617
611
|
}>;
|
|
618
|
-
bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
|
|
619
612
|
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
620
613
|
}, z$1.core.$strip>;
|
|
621
614
|
declare const PolymarketRedeemPositionsRequestSchema: z$1.ZodObject<{
|
|
@@ -716,7 +709,6 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
|
|
|
716
709
|
triggerPrice: z$1.ZodOptional<z$1.ZodNumber>;
|
|
717
710
|
reduceOnly: z$1.ZodOptional<z$1.ZodBoolean>;
|
|
718
711
|
postOnly: z$1.ZodOptional<z$1.ZodBoolean>;
|
|
719
|
-
bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
|
|
720
712
|
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
721
713
|
}, z$1.core.$strip>;
|
|
722
714
|
/**
|
|
@@ -725,7 +717,6 @@ declare const HyperliquidPlaceOrderRequestSchema: z$1.ZodObject<{
|
|
|
725
717
|
declare const HyperliquidTransferRequestSchema: z$1.ZodObject<{
|
|
726
718
|
amount: z$1.ZodNumber;
|
|
727
719
|
toPerp: z$1.ZodBoolean;
|
|
728
|
-
bypassManualApproval: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
|
|
729
720
|
expiresAt: z$1.ZodDefault<z$1.ZodNullable<z$1.ZodOptional<z$1.ZodString>>>;
|
|
730
721
|
}, z$1.core.$strip>;
|
|
731
722
|
/**
|
|
@@ -975,9 +966,8 @@ type MemoryListResponse = z$1.infer<typeof MemoryListResponseSchema>;
|
|
|
975
966
|
* Execution mode for agent sessions
|
|
976
967
|
* - "auto": Transactions execute immediately (default behavior)
|
|
977
968
|
* - "manual": Transactions are stored as suggestions for user approval
|
|
978
|
-
* - "hybrid": Reserved for future use
|
|
979
969
|
*/
|
|
980
|
-
type ExecutionMode = "auto" | "manual"
|
|
970
|
+
type ExecutionMode = "auto" | "manual";
|
|
981
971
|
/**
|
|
982
972
|
* Empty data constant for Ethereum transactions.
|
|
983
973
|
* Use this for simple transfers without any contract interaction.
|
|
@@ -2601,7 +2591,6 @@ declare class AgentContext {
|
|
|
2601
2591
|
* Execution mode for this session.
|
|
2602
2592
|
* - "auto": Transactions execute immediately (default behavior)
|
|
2603
2593
|
* - "manual": Transactions are stored as suggestions for user approval
|
|
2604
|
-
* - "hybrid": Reserved for future use
|
|
2605
2594
|
*/
|
|
2606
2595
|
readonly executionMode: ExecutionMode;
|
|
2607
2596
|
/** Internal SDK instance */
|
|
@@ -2723,7 +2712,6 @@ declare class AgentContext {
|
|
|
2723
2712
|
* **Input**: `SignAndSendRequest`
|
|
2724
2713
|
* - `network` (string): "solana" or "ethereum:chainId" (e.g., "ethereum:1", "ethereum:42161")
|
|
2725
2714
|
* - `message` (string | undefined): Optional context message
|
|
2726
|
-
* - `bypassManualApproval` (boolean | undefined): Force execution even in manual mode
|
|
2727
2715
|
* - `expiresAt` (string | null | undefined): ISO 8601 timestamp for suggestion expiry
|
|
2728
2716
|
* - `request` (object): Transaction payload
|
|
2729
2717
|
* - For Ethereum:
|
|
@@ -2742,7 +2730,7 @@ declare class AgentContext {
|
|
|
2742
2730
|
* - `success` (boolean): Whether the operation succeeded
|
|
2743
2731
|
* - `data` (SignAndSendData | SuggestedTransactionData | undefined): Response data
|
|
2744
2732
|
* - In auto mode: SignAndSendData with txHash, transactionUrl, etc.
|
|
2745
|
-
* - In manual mode
|
|
2733
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
2746
2734
|
* - `error` (string | undefined): Error message on failure
|
|
2747
2735
|
* - `errorMessage` (string | undefined): Detailed error message on failure
|
|
2748
2736
|
* - `errorDetails` (object | undefined): Detailed error info
|
|
@@ -2989,14 +2977,13 @@ declare class AgentContext {
|
|
|
2989
2977
|
* - `tokenId` (string): Market token ID for the position
|
|
2990
2978
|
* - `size` (number): For BUY: USD amount to spend. For SELL: Number of shares to sell
|
|
2991
2979
|
* - `side` ("BUY" | "SELL"): Order side
|
|
2992
|
-
* - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
|
|
2993
2980
|
* - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
|
|
2994
2981
|
*
|
|
2995
2982
|
* **Output**: `PolymarketMarketOrderResponse`
|
|
2996
2983
|
* - `success` (boolean): Whether the operation was successful
|
|
2997
2984
|
* - `data` (PolymarketMarketOrderData | SuggestedTransactionData | undefined): Response data
|
|
2998
2985
|
* - In auto mode: PolymarketMarketOrderData with orderInfo (orderId, side, priceUsd, txHashes)
|
|
2999
|
-
* - In manual mode
|
|
2986
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
3000
2987
|
* - `error` (string | undefined): Error message on failure
|
|
3001
2988
|
* - `errorMessage` (string | undefined): Detailed error message on failure
|
|
3002
2989
|
*
|
|
@@ -3092,14 +3079,13 @@ declare class AgentContext {
|
|
|
3092
3079
|
* - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
|
|
3093
3080
|
* - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
|
|
3094
3081
|
* - `postOnly` (boolean, optional): Whether this is a post-only order
|
|
3095
|
-
* - `bypassManualApproval` (boolean, optional): Force execution even in manual mode
|
|
3096
3082
|
* - `expiresAt` (string | null, optional): ISO 8601 timestamp for suggestion expiry
|
|
3097
3083
|
*
|
|
3098
3084
|
* **Output**: `HyperliquidPlaceOrderResponse`
|
|
3099
3085
|
* - `success` (boolean): Whether the operation was successful
|
|
3100
3086
|
* - `data` (HyperliquidOrderInfo | SuggestedTransactionData | undefined): Response data
|
|
3101
3087
|
* - In auto mode: HyperliquidOrderInfo with orderId, symbol, side, price, size, filled, status, market, clientOrderId
|
|
3102
|
-
* - In manual mode
|
|
3088
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
3103
3089
|
* - `error` (string | undefined): Error message (only present on failure)
|
|
3104
3090
|
* - `errorMessage` (string | undefined): Detailed error message (only present on failure)
|
|
3105
3091
|
*
|
|
@@ -3532,7 +3518,7 @@ declare class AgentContext {
|
|
|
3532
3518
|
* - `success` (boolean): Whether the execution was successful
|
|
3533
3519
|
* - `data` (SwidgeExecuteData | SuggestedTransactionData | undefined): Response data
|
|
3534
3520
|
* - In auto mode: SwidgeExecuteData with status ("success", "failure", "refund", "delayed") and transaction hashes
|
|
3535
|
-
* - In manual mode
|
|
3521
|
+
* - In manual mode: SuggestedTransactionData with suggestionId and details
|
|
3536
3522
|
* - `error` (string | undefined): Error message if execution failed
|
|
3537
3523
|
* - `errorMessage` (string | undefined): Detailed error message if execution failed
|
|
3538
3524
|
*
|
package/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCircuitEnvironment(){return!("undefined"==typeof process||!process.env||"circuit"!==process.env.CIRCUIT_ENVIRONMENT&&void 0===process.env.AWS_LAMBDA_FUNCTION_NAME&&void 0===process.env.LAMBDA_TASK_ROOT&&void 0===process.env.AWS_EXECUTION_ENV)}getCircuitDevMode(){if("undefined"!=typeof process&&process.env)return process.env.CIRCUIT_DEV_MODE}constructor(r){this.config=r;const e=this.getCircuitDevMode(),t=this.isCircuitEnvironment();let s,o;"local"===e?(s="http://localhost:4001",o="Dev Local"):t?(s="http://transaction-service.agent.internal",o="Circuit (internal)"):(s="https://agents.circuit.org",o="Local (public)"),this.baseUrl=r.baseUrl||s,this.authorizationHeader=r.authorizationHeader}getAgentSlug(){if("undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG)return process.env.CIRCUIT_AGENT_SLUG}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCircuitEnvironment())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return"undefined"!=typeof process&&process.env?.CIRCUIT_DEV_API_KEY&&(r["X-API-Key"]=process.env.CIRCUIT_DEV_API_KEY),r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json","User-Agent":"circuit-agent-sdk/1.0",Accept:"*/*",...this.getAuthHeaders()},...e.headers},s=`${this.baseUrl}${r}`,o=9e5,n=new AbortController,a=setTimeout(()=>n.abort(),o),i={...e,headers:t,signal:n.signal};try{const r=await fetch(s,i);if(clearTimeout(a),!r.ok){const e=await r.text();let t={};try{t=JSON.parse(e)}catch{t={error:e}}const s=t.error||`HTTP ${r.status}: ${r.statusText}`,o=new Error(s);throw o.error=t.error,o.errorMessage=t.error,o.errorDetails=t,o.statusCode=r.status,o}return await r.json()}catch(e){if(clearTimeout(a),e instanceof Error){if("AbortError"===e.name||e.message.includes("aborted")){const e=new Error(`Request timeout after 900s to ${s}`);throw e.error="Request Timeout",e.errorMessage=`Request to ${s} timed out after 900 seconds`,e.errorDetails={url:s,endpoint:r,timeout:o,baseUrl:this.baseUrl},e}if(e.message.includes("fetch failed")||e.message.includes("ECONNREFUSED")||e.message.includes("ENOTFOUND")||e.message.includes("getaddrinfo")||e.message.includes("network")){const t=new Error(`Network error: ${e.message}. URL: ${s}`);throw t.error="Network Error",t.errorMessage=`Failed to connect to ${s}: ${e.message}`,t.errorDetails={url:s,endpoint:r,baseUrl:this.baseUrl,originalError:e.message,isCircuitEnvironment:this.isCircuitEnvironment()},t}}throw e}}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var n=class{client;config;constructor(r){this.config=r,this.client=new e(r)}setBaseUrl(r){this.config.baseUrl=r,this.client=new e(this.config)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message,bypassManualApproval:r.bypassManualApproval??!1,expiresAt:r.expiresAt??null})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message,bypassManualApproval:r.bypassManualApproval??!1,expiresAt:r.expiresAt??null});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=(await this.client.post("/v1/transactions/evm",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/evm/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=(await this.client.post("/v1/transactions/solana",r)).data;if("suggested"in e&&!0===e.suggested)return{success:!0,data:{suggested:!0,suggestionId:e.suggestionId,details:e.details}};const t=e,s=(await this.client.post(`/v1/transactions/solana/${t.id}/broadcast`)).data;return{success:!0,data:{internalTransactionId:t.id,txHash:s.transactionHash,transactionUrl:void 0}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return await this.client.post("/v1/swap/quote",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{return await this.client.post("/v1/swap/execute",r)}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},n=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||n,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{const e=await this.client.post("/v1/platforms/polymarket/market-order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{const e=await this.client.post("/v1/platforms/hyperliquid/order",r);return e.success&&e.data&&"suggested"in e.data&&e.data.suggested,e}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return await this.client.post(`/v1/memory/${r}`,{value:e})}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return await this.client.get(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return await this.client.delete(`/v1/memory/${r}`)}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return await this.client.get("/v1/memory/list")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return await this.client.get("/v1/transactions/ledger")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return await this.client.get("/v1/positions/current")}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async clearSuggestedTransactions(){try{return await this.client.delete("/v1/sessions/suggestions")}catch(r){const e=r.error,t=r.errorMessage,s=r instanceof Error?r.message:"Failed to clear suggested transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||s}}}};import{existsSync as a,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;executionMode;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.executionMode=r.executionMode??"auto",this.t=new n({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}setBaseUrl(r){this.t.setBaseUrl(r)}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,n;const a=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,a,2),n=JSON.stringify(r,a)):(o=String(r),n=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{return await this.t._sendLog([{type:i,message:n}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async clearSuggestedTransactions(){return this.t.clearSuggestedTransactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),g=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p),unwindPositions:h.array(p).optional(),executionMode:h.enum(["auto","manual","hybrid"]).default("auto")}),m=(h.object({status:h.string()}),class{app;runFunction;unwindFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.unwindFunction=r.unwindFunction,this.app.use("*",d()),this.setupRoutes()}defaultUnwindFunction=async(r,e)=>{await r.log(`Unwind requested for session ${r.sessionId} (positions=${e.length}), but no unwindFunction was provided`)};async executeWithJobTracking(r,e,t,s){let o,n=!1;try{const o=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,executionMode:r.executionMode,authorizationHeader:s});if("unwind"===e){const e=r.unwindPositions??r.currentPositions;await t(o,e)}else await t(o);n=!0}catch(r){o=this.getErrorMessage(r),n=!1,console.error(`Agent ${e} function error:`,o)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,n?"success":"failed",o,s)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const a=new n({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await a._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await a._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,"run",this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/unwind",u("json",g),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.unwindFunction||this.defaultUnwindFunction;return await this.executeWithJobTracking(e,"unwind",s,t),r.json({success:!0,message:"Unwind completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(a(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /unwind"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:this.app.fetch.bind(this.app)}}});import{z as f}from"zod";f.enum(["auto","manual","hybrid"]);var w="0x",E=(f.object({bypassManualApproval:f.boolean().optional().default(!1),expiresAt:f.string().datetime().optional().nullable().default(null)}),f.object({suggested:f.literal(!0),suggestionId:f.number(),details:f.record(f.string(),f.unknown())}));function v(r){return!0===r.success&&"data"in r&&"object"==typeof r.data&&null!==r.data&&"suggested"in r.data&&!0===r.data.suggested}function D(r){return r.success&&void 0!==r.data}function b(r){return"object"==typeof r&&null!==r&&"out"in r&&!("suggested"in r)}function k(r){return"object"==typeof r&&null!==r&&"orderInfo"in r&&!("suggested"in r)}function F(r){return"object"==typeof r&&null!==r&&"orderId"in r&&!("suggested"in r)}function T(r){return"object"==typeof r&&null!==r&&"txHash"in r&&!("suggested"in r)}f.object({success:f.boolean(),error:f.string().optional(),errorMessage:f.string().optional()});import{z as A}from"zod";var M=A.templateLiteral(["ethereum:",A.coerce.number().int().nonnegative()]),S=A.union([A.literal("solana"),M]),O=A.object({address:A.string(),network:S}),$=A.object({from:O,to:O,fromToken:A.string().optional(),toToken:A.string().optional(),amount:A.string(),slippage:A.string().optional()}),U=A.object({network:S,address:A.string(),token:A.string().nullable(),name:A.string().optional(),symbol:A.string().optional(),decimals:A.number().optional(),amount:A.string().optional(),minimumAmount:A.string().optional(),amountFormatted:A.string().optional(),amountUsd:A.string().optional()}),q=A.object({usd:A.string().optional(),percentage:A.string().optional()}),x=A.object({name:A.string(),amount:A.string().optional(),amountFormatted:A.string().optional(),amountUsd:A.string().optional()}),I=(A.object({programId:A.string(),keys:A.array(A.object({pubkey:A.string(),isSigner:A.boolean(),isWritable:A.boolean()})),data:A.union([A.string(),A.instanceof(Buffer)])}),A.object({type:A.literal("evm"),from:A.string().regex(/^0x[a-fA-F0-9]{40}$/),to:A.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:A.number(),value:A.string(),data:A.string().regex(/^0x[a-fA-F0-9]*$/),gas:A.number().nullish(),maxFeePerGas:A.number().nullish(),maxPriorityFeePerGas:A.number().nullish()})),P=A.object({type:A.literal("solana"),serializedTransaction:A.string()}),j=A.object({type:A.literal("transaction"),description:A.string(),transactionDetails:A.union([I,P])}),N=A.object({type:A.literal("signature"),description:A.string(),signatureData:A.string()}),H=A.discriminatedUnion("type",[j,N]),C=A.object({engine:A.string().describe("Swap engine. Expected: 'relay', 'lifi'"),assetSend:U,assetReceive:U,priceImpact:q,fees:A.array(x),steps:A.array(H)}),_=C.extend({bypassManualApproval:A.boolean().optional().default(!1),expiresAt:A.string().datetime().optional().nullable().default(null)}),K=A.object({network:A.string(),txs:A.array(A.string())}),L=A.object({status:A.string().describe("Expected: 'success', 'failure', 'refund', 'delayed'"),in:K.optional(),out:K.optional(),lastUpdated:A.number(),error:A.string().optional()}),R={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},G=r=>A.object({success:A.boolean(),data:r.optional(),error:A.string().optional(),errorMessage:A.string().optional(),errorDetails:A.object({message:A.string().optional(),error:A.string().optional(),status:A.number().optional(),statusText:A.string().optional()}).optional()}).passthrough(),z=G(C),W=G(A.union([L,E]));export{e as APIClient,m as Agent,y as AgentContext,n as AgentSdk,w as EMPTY_DATA,R as QUOTE_RESULT,_ as SwidgeExecuteRequestSchema,W as SwidgeExecuteResponseWrapperSchema,$ as SwidgeQuoteRequestSchema,z as SwidgeQuoteResponseWrapperSchema,o as getChainIdFromNetwork,t as isEthereumNetwork,F as isHyperliquidExecuted,k as isPolymarketExecuted,s as isSolanaNetwork,D as isSuccessResponse,v as isSuggestedTransaction,b as isSwidgeExecuted,T as isTransactionExecuted};
|
|
1
|
+
import{loadAuthFromFileSystem as 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};
|