@circuitorg/agent-sdk 1.2.3 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +90 -0
  2. package/index.d.ts +1066 -5
  3. package/index.js +1 -1
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -24,6 +24,11 @@ A simplified TypeScript SDK for building automated agents to deploy on Circuit.
24
24
  - [📈 Polymarket Prediction Markets](#-polymarket-prediction-markets)
25
25
  - [Place Market Orders](#place-market-orders)
26
26
  - [Redeem Positions](#redeem-positions)
27
+ - [Hyperliquid Perpetuals Trading](#hyperliquid-perpetuals-trading)
28
+ - [Account Information](#account-information)
29
+ - [Place Orders](#place-orders)
30
+ - [Order Management](#order-management)
31
+ - [Transfer Between Accounts](#transfer-between-accounts)
27
32
  - [📊 Transaction History](#-transaction-history)
28
33
  - [🚀 Sign \& Send Transactions](#-sign--send-transactions)
29
34
  - [Ethereum (any EVM chain)](#ethereum-any-evm-chain)
@@ -328,6 +333,91 @@ async function stop(agent: AgentContext): Promise<void> {
328
333
  }
329
334
  ```
330
335
 
336
+ ## Hyperliquid Perpetuals Trading
337
+
338
+ Trade perpetual futures on Hyperliquid DEX with leverage.
339
+
340
+ ### Account Information
341
+
342
+ ```typescript
343
+ async function run(agent: AgentContext): Promise<void> {
344
+ // Check balances
345
+ const balances = await agent.platforms.hyperliquid.balances();
346
+ if (balances.success && balances.data) {
347
+ await agent.log(`Account value: $${balances.data.perp.accountValue}`);
348
+ await agent.log(`Withdrawable: $${balances.data.perp.withdrawable}`);
349
+ }
350
+
351
+ // View open positions
352
+ const positions = await agent.platforms.hyperliquid.positions();
353
+ if (positions.success && positions.data) {
354
+ for (const pos of positions.data) {
355
+ await agent.log(`${pos.symbol}: ${pos.side} ${pos.size} @ ${pos.entryPrice}`);
356
+ await agent.log(`Unrealized PnL: $${pos.unrealizedPnl}`);
357
+ }
358
+ }
359
+ }
360
+ ```
361
+
362
+ ### Place Orders
363
+
364
+ ```typescript
365
+ async function run(agent: AgentContext): Promise<void> {
366
+ // Market order
367
+ const order = await agent.platforms.hyperliquid.placeOrder({
368
+ symbol: "BTC-USD",
369
+ side: "buy",
370
+ size: 0.0001,
371
+ price: 110000, // Acts as slippage limit for market orders
372
+ market: "perp",
373
+ type: "market"
374
+ });
375
+
376
+ if (order.success && order.data) {
377
+ await agent.log(`Order ${order.data.orderId}: ${order.data.status}`);
378
+ } else {
379
+ await agent.log(order.error, { error: true });
380
+ }
381
+ }
382
+ ```
383
+
384
+ ### Order Management
385
+
386
+ ```typescript
387
+ async function run(agent: AgentContext): Promise<void> {
388
+ // Get open orders
389
+ const openOrders = await agent.platforms.hyperliquid.openOrders();
390
+
391
+ // Get specific order details
392
+ const order = await agent.platforms.hyperliquid.order("12345");
393
+
394
+ // Cancel an order
395
+ const result = await agent.platforms.hyperliquid.deleteOrder("12345", "BTC-USD");
396
+
397
+ // View historical orders
398
+ const history = await agent.platforms.hyperliquid.orders();
399
+
400
+ // Check order fills
401
+ const fills = await agent.platforms.hyperliquid.orderFills();
402
+ }
403
+ ```
404
+
405
+ ### Transfer Between Accounts
406
+
407
+ ```typescript
408
+ async function run(agent: AgentContext): Promise<void> {
409
+ // Transfer USDC from spot to perp account
410
+ const transfer = await agent.platforms.hyperliquid.transfer({
411
+ amount: 1000.0,
412
+ toPerp: true
413
+ });
414
+
415
+ if (transfer.success) {
416
+ await agent.log("Transfer completed");
417
+ }
418
+ }
419
+ ```
420
+
331
421
  ## 📊 Transaction History
332
422
 
333
423
  Get a list of asset changes for all confirmed transactions during your session. This is useful for tracking what assets have moved in and out of the agent's wallet.
package/index.d.ts CHANGED
@@ -701,6 +701,236 @@ type PolymarketRedeemPositionsRequest = z.infer<typeof PolymarketRedeemPositions
701
701
  type PolymarketMarketOrderResponse = z.infer<typeof PolymarketMarketOrderResponseSchema>;
702
702
  type PolymarketRedeemPositionsResponse = z.infer<typeof PolymarketRedeemPositionsResponseSchema>;
703
703
 
704
+ /**
705
+ * Request to place an order on Hyperliquid
706
+ */
707
+ declare const HyperliquidPlaceOrderRequestSchema: z.ZodObject<{
708
+ symbol: z.ZodString;
709
+ side: z.ZodEnum<{
710
+ buy: "buy";
711
+ sell: "sell";
712
+ }>;
713
+ size: z.ZodNumber;
714
+ price: z.ZodNumber;
715
+ market: z.ZodEnum<{
716
+ perp: "perp";
717
+ spot: "spot";
718
+ }>;
719
+ type: z.ZodOptional<z.ZodEnum<{
720
+ market: "market";
721
+ limit: "limit";
722
+ stop: "stop";
723
+ take_profit: "take_profit";
724
+ }>>;
725
+ triggerPrice: z.ZodOptional<z.ZodNumber>;
726
+ reduceOnly: z.ZodOptional<z.ZodBoolean>;
727
+ postOnly: z.ZodOptional<z.ZodBoolean>;
728
+ }, z.core.$strip>;
729
+ /**
730
+ * Request to transfer between spot and perp accounts on Hyperliquid
731
+ */
732
+ declare const HyperliquidTransferRequestSchema: z.ZodObject<{
733
+ amount: z.ZodNumber;
734
+ toPerp: z.ZodBoolean;
735
+ }, z.core.$strip>;
736
+ declare const HyperliquidPlaceOrderResponseSchema: z.ZodObject<{
737
+ success: z.ZodBoolean;
738
+ data: z.ZodOptional<z.ZodObject<{
739
+ orderId: z.ZodString;
740
+ symbol: z.ZodString;
741
+ side: z.ZodEnum<{
742
+ buy: "buy";
743
+ sell: "sell";
744
+ }>;
745
+ price: z.ZodNumber;
746
+ size: z.ZodNumber;
747
+ filled: z.ZodNumber;
748
+ status: z.ZodString;
749
+ market: z.ZodEnum<{
750
+ perp: "perp";
751
+ spot: "spot";
752
+ }>;
753
+ clientOrderId: z.ZodOptional<z.ZodString>;
754
+ }, z.core.$strip>>;
755
+ error: z.ZodOptional<z.ZodString>;
756
+ }, z.core.$strip>;
757
+ declare const HyperliquidOrderResponseSchema: z.ZodObject<{
758
+ success: z.ZodBoolean;
759
+ data: z.ZodOptional<z.ZodObject<{
760
+ orderId: z.ZodString;
761
+ symbol: z.ZodString;
762
+ side: z.ZodEnum<{
763
+ buy: "buy";
764
+ sell: "sell";
765
+ }>;
766
+ price: z.ZodNumber;
767
+ size: z.ZodNumber;
768
+ filled: z.ZodNumber;
769
+ status: z.ZodString;
770
+ market: z.ZodEnum<{
771
+ perp: "perp";
772
+ spot: "spot";
773
+ }>;
774
+ clientOrderId: z.ZodOptional<z.ZodString>;
775
+ }, z.core.$strip>>;
776
+ error: z.ZodOptional<z.ZodString>;
777
+ }, z.core.$strip>;
778
+ declare const HyperliquidDeleteOrderResponseSchema: z.ZodObject<{
779
+ success: z.ZodBoolean;
780
+ data: z.ZodOptional<z.ZodUndefined>;
781
+ error: z.ZodOptional<z.ZodString>;
782
+ }, z.core.$strip>;
783
+ declare const HyperliquidBalancesResponseSchema: z.ZodObject<{
784
+ success: z.ZodBoolean;
785
+ data: z.ZodOptional<z.ZodObject<{
786
+ perp: z.ZodObject<{
787
+ accountValue: z.ZodString;
788
+ totalMarginUsed: z.ZodString;
789
+ withdrawable: z.ZodString;
790
+ }, z.core.$strip>;
791
+ spot: z.ZodArray<z.ZodObject<{
792
+ coin: z.ZodString;
793
+ total: z.ZodString;
794
+ hold: z.ZodString;
795
+ }, z.core.$strip>>;
796
+ }, z.core.$strip>>;
797
+ error: z.ZodOptional<z.ZodString>;
798
+ }, z.core.$strip>;
799
+ declare const HyperliquidPositionsResponseSchema: z.ZodObject<{
800
+ success: z.ZodBoolean;
801
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
802
+ symbol: z.ZodString;
803
+ side: z.ZodEnum<{
804
+ long: "long";
805
+ short: "short";
806
+ }>;
807
+ size: z.ZodString;
808
+ entryPrice: z.ZodString;
809
+ markPrice: z.ZodString;
810
+ liquidationPrice: z.ZodNullable<z.ZodString>;
811
+ unrealizedPnl: z.ZodString;
812
+ leverage: z.ZodString;
813
+ marginUsed: z.ZodString;
814
+ }, z.core.$strip>>>;
815
+ error: z.ZodOptional<z.ZodString>;
816
+ }, z.core.$strip>;
817
+ declare const HyperliquidOpenOrdersResponseSchema: z.ZodObject<{
818
+ success: z.ZodBoolean;
819
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
820
+ orderId: z.ZodString;
821
+ symbol: z.ZodString;
822
+ side: z.ZodEnum<{
823
+ buy: "buy";
824
+ sell: "sell";
825
+ }>;
826
+ price: z.ZodNumber;
827
+ size: z.ZodNumber;
828
+ filled: z.ZodNumber;
829
+ status: z.ZodString;
830
+ market: z.ZodEnum<{
831
+ perp: "perp";
832
+ spot: "spot";
833
+ }>;
834
+ clientOrderId: z.ZodOptional<z.ZodString>;
835
+ }, z.core.$strip>>>;
836
+ error: z.ZodOptional<z.ZodString>;
837
+ }, z.core.$strip>;
838
+ declare const HyperliquidOrderFillsResponseSchema: z.ZodObject<{
839
+ success: z.ZodBoolean;
840
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
841
+ orderId: z.ZodString;
842
+ symbol: z.ZodString;
843
+ side: z.ZodEnum<{
844
+ buy: "buy";
845
+ sell: "sell";
846
+ }>;
847
+ price: z.ZodString;
848
+ size: z.ZodString;
849
+ fee: z.ZodString;
850
+ timestamp: z.ZodNumber;
851
+ isMaker: z.ZodBoolean;
852
+ }, z.core.$strip>>>;
853
+ error: z.ZodOptional<z.ZodString>;
854
+ }, z.core.$strip>;
855
+ declare const HyperliquidHistoricalOrdersResponseSchema: z.ZodObject<{
856
+ success: z.ZodBoolean;
857
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
858
+ orderId: z.ZodString;
859
+ symbol: z.ZodString;
860
+ side: z.ZodEnum<{
861
+ buy: "buy";
862
+ sell: "sell";
863
+ }>;
864
+ price: z.ZodNumber;
865
+ size: z.ZodNumber;
866
+ filled: z.ZodNumber;
867
+ status: z.ZodEnum<{
868
+ filled: "filled";
869
+ open: "open";
870
+ canceled: "canceled";
871
+ triggered: "triggered";
872
+ rejected: "rejected";
873
+ marginCanceled: "marginCanceled";
874
+ liquidatedCanceled: "liquidatedCanceled";
875
+ }>;
876
+ market: z.ZodEnum<{
877
+ perp: "perp";
878
+ spot: "spot";
879
+ }>;
880
+ timestamp: z.ZodNumber;
881
+ statusTimestamp: z.ZodNumber;
882
+ orderType: z.ZodEnum<{
883
+ Market: "Market";
884
+ Limit: "Limit";
885
+ "Stop Market": "Stop Market";
886
+ "Stop Limit": "Stop Limit";
887
+ "Take Profit Market": "Take Profit Market";
888
+ "Take Profit Limit": "Take Profit Limit";
889
+ }>;
890
+ clientOrderId: z.ZodOptional<z.ZodString>;
891
+ }, z.core.$strip>>>;
892
+ error: z.ZodOptional<z.ZodString>;
893
+ }, z.core.$strip>;
894
+ declare const HyperliquidTransferResponseSchema: z.ZodObject<{
895
+ success: z.ZodBoolean;
896
+ data: z.ZodOptional<z.ZodUndefined>;
897
+ error: z.ZodOptional<z.ZodString>;
898
+ }, z.core.$strip>;
899
+ declare const HyperliquidLiquidationsResponseSchema: z.ZodObject<{
900
+ success: z.ZodBoolean;
901
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
902
+ timestamp: z.ZodNumber;
903
+ liquidatedPositions: z.ZodArray<z.ZodObject<{
904
+ symbol: z.ZodString;
905
+ side: z.ZodEnum<{
906
+ long: "long";
907
+ short: "short";
908
+ }>;
909
+ size: z.ZodString;
910
+ }, z.core.$strip>>;
911
+ totalNotional: z.ZodString;
912
+ accountValue: z.ZodString;
913
+ leverageType: z.ZodEnum<{
914
+ Cross: "Cross";
915
+ Isolated: "Isolated";
916
+ }>;
917
+ txHash: z.ZodString;
918
+ }, z.core.$strip>>>;
919
+ error: z.ZodOptional<z.ZodString>;
920
+ }, z.core.$strip>;
921
+ type HyperliquidPlaceOrderRequest = z.infer<typeof HyperliquidPlaceOrderRequestSchema>;
922
+ type HyperliquidTransferRequest = z.infer<typeof HyperliquidTransferRequestSchema>;
923
+ type HyperliquidPlaceOrderResponse = z.infer<typeof HyperliquidPlaceOrderResponseSchema>;
924
+ type HyperliquidOrderResponse = z.infer<typeof HyperliquidOrderResponseSchema>;
925
+ type HyperliquidDeleteOrderResponse = z.infer<typeof HyperliquidDeleteOrderResponseSchema>;
926
+ type HyperliquidBalancesResponse = z.infer<typeof HyperliquidBalancesResponseSchema>;
927
+ type HyperliquidPositionsResponse = z.infer<typeof HyperliquidPositionsResponseSchema>;
928
+ type HyperliquidOpenOrdersResponse = z.infer<typeof HyperliquidOpenOrdersResponseSchema>;
929
+ type HyperliquidOrderFillsResponse = z.infer<typeof HyperliquidOrderFillsResponseSchema>;
930
+ type HyperliquidHistoricalOrdersResponse = z.infer<typeof HyperliquidHistoricalOrdersResponseSchema>;
931
+ type HyperliquidTransferResponse = z.infer<typeof HyperliquidTransferResponseSchema>;
932
+ type HyperliquidLiquidationsResponse = z.infer<typeof HyperliquidLiquidationsResponseSchema>;
933
+
704
934
  /**
705
935
  * Memory type definitions for agent session storage
706
936
  *
@@ -1044,7 +1274,7 @@ declare class AgentSdk {
1044
1274
  * @returns SwidgeExecuteResponse or array of responses (matching input type) with transaction status and details
1045
1275
  * - `success` (boolean): Whether the execution was successful
1046
1276
  * - `data` (SwidgeExecuteData | undefined): Execution result containing:
1047
- * - `status`: "success" | "failure" | "refund" | "delayed" - Final transaction status
1277
+ * - `status`: "success" | "failure" | "refund" | "delayed" | "error" - Final transaction status
1048
1278
  * - `in`: Source transaction details with txs array (transaction hashes)
1049
1279
  * - `out`: Destination transaction details with txs array (transaction hashes)
1050
1280
  * - Additional metadata about the swap/bridge operation
@@ -1432,6 +1662,400 @@ declare class AgentSdk {
1432
1662
  */
1433
1663
  redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
1434
1664
  };
1665
+ /**
1666
+ * 🔄 Hyperliquid: Trade perpetuals on Hyperliquid DEX
1667
+ *
1668
+ * Access perpetuals trading operations including orders, positions, and transfers.
1669
+ * All operations are policy-checked and signed automatically.
1670
+ */
1671
+ hyperliquid: {
1672
+ /**
1673
+ * Place an order on Hyperliquid
1674
+ *
1675
+ * Submit a market, limit, stop, or take-profit order for perpetuals or spot trading.
1676
+ *
1677
+ * **Input**: `HyperliquidPlaceOrderRequest`
1678
+ * - `symbol` (string): Trading pair symbol (e.g., "BTC-USD")
1679
+ * - `side` ("buy" | "sell"): Order side
1680
+ * - `size` (number): Order size
1681
+ * - `price` (number): Order price (for market orders, acts as slippage limit)
1682
+ * - `market` ("perp" | "spot"): Market type
1683
+ * - `type` (string, optional): Order type ("limit", "market", "stop", "take_profit")
1684
+ * - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
1685
+ * - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
1686
+ * - `postOnly` (boolean, optional): Whether this is a post-only order
1687
+ *
1688
+ * **Output**: `HyperliquidPlaceOrderResponse`
1689
+ * - `success` (boolean): Whether the operation was successful
1690
+ * - `data` (HyperliquidOrderInfo | undefined): Order information (only present on success)
1691
+ * - `data.orderId` (string): Order ID
1692
+ * - `data.symbol` (string): Trading pair symbol
1693
+ * - `data.side` ("buy" | "sell"): Order side
1694
+ * - `data.price` (number): Order price
1695
+ * - `data.size` (number): Order size
1696
+ * - `data.filled` (number): Filled amount
1697
+ * - `data.status` (string): Order status
1698
+ * - `data.market` ("perp" | "spot"): Market type
1699
+ * - `data.clientOrderId` (string | undefined): Client order ID
1700
+ * - `error` (string | undefined): Error message (only present on failure)
1701
+ *
1702
+ * @param request - Order parameters
1703
+ * @returns Promise resolving to HyperliquidPlaceOrderResponse
1704
+ *
1705
+ * @example
1706
+ * ```ts
1707
+ * // Market order
1708
+ * const result = await sdk.platforms.hyperliquid.placeOrder({
1709
+ * symbol: "BTC-USD",
1710
+ * side: "buy",
1711
+ * size: 0.0001,
1712
+ * price: 110000,
1713
+ * market: "perp",
1714
+ * type: "market",
1715
+ * });
1716
+ *
1717
+ * // Limit order
1718
+ * const result = await sdk.platforms.hyperliquid.placeOrder({
1719
+ * symbol: "BTC-USD",
1720
+ * side: "buy",
1721
+ * size: 0.0001,
1722
+ * price: 100000,
1723
+ * market: "perp",
1724
+ * type: "limit",
1725
+ * });
1726
+ *
1727
+ * if (result.success && result.data) {
1728
+ * console.log(`Order placed: ${result.data.orderId}`);
1729
+ * console.log(`Status: ${result.data.status}`);
1730
+ * } else {
1731
+ * console.error(`Error: ${result.error}`);
1732
+ * }
1733
+ * ```
1734
+ */
1735
+ placeOrder: (request: HyperliquidPlaceOrderRequest) => Promise<HyperliquidPlaceOrderResponse>;
1736
+ /**
1737
+ * Get order information by order ID
1738
+ *
1739
+ * Retrieve details for a specific order including status, filled amount, and price.
1740
+ *
1741
+ * **Input**: `orderId` (string) - Unique order identifier
1742
+ *
1743
+ * **Output**: `HyperliquidOrderResponse`
1744
+ * - `success` (boolean): Whether the operation was successful
1745
+ * - `data` (HyperliquidOrderInfo | undefined): Order details (only present on success)
1746
+ * - `data.orderId` (string): Order ID
1747
+ * - `data.symbol` (string): Trading pair symbol
1748
+ * - `data.side` ("buy" | "sell"): Order side
1749
+ * - `data.price` (number): Order price
1750
+ * - `data.size` (number): Order size
1751
+ * - `data.filled` (number): Filled amount
1752
+ * - `data.status` (string): Order status
1753
+ * - `data.market` ("perp" | "spot"): Market type
1754
+ * - `data.clientOrderId` (string | undefined): Client order ID
1755
+ * - `error` (string | undefined): Error message (only present on failure)
1756
+ *
1757
+ * @param orderId - Order ID to query
1758
+ * @returns Promise resolving to HyperliquidOrderResponse
1759
+ *
1760
+ * @example
1761
+ * ```ts
1762
+ * const result = await sdk.platforms.hyperliquid.order("12345");
1763
+ * if (result.success && result.data) {
1764
+ * console.log(`Order ${result.data.orderId}: ${result.data.status}`);
1765
+ * console.log(`Filled: ${result.data.filled}/${result.data.size}`);
1766
+ * } else {
1767
+ * console.error(`Error: ${result.error}`);
1768
+ * }
1769
+ * ```
1770
+ */
1771
+ order: (orderId: string) => Promise<HyperliquidOrderResponse>;
1772
+ /**
1773
+ * Cancel an order
1774
+ *
1775
+ * Cancel an open order by order ID and symbol.
1776
+ *
1777
+ * **Input**:
1778
+ * - `orderId` (string): Order ID to cancel
1779
+ * - `symbol` (string): Trading symbol
1780
+ *
1781
+ * **Output**: `HyperliquidDeleteOrderResponse`
1782
+ * - `success` (boolean): Whether the operation was successful
1783
+ * - `error` (string | undefined): Error message (only present on failure)
1784
+ *
1785
+ * Note: This operation returns no data on success (void response).
1786
+ *
1787
+ * @param orderId - Order ID to cancel
1788
+ * @param symbol - Trading symbol
1789
+ * @returns Promise resolving to HyperliquidDeleteOrderResponse
1790
+ *
1791
+ * @example
1792
+ * ```ts
1793
+ * const result = await sdk.platforms.hyperliquid.deleteOrder("12345", "BTC-USD");
1794
+ * if (result.success) {
1795
+ * console.log("Order cancelled successfully");
1796
+ * } else {
1797
+ * console.error(`Error: ${result.error}`);
1798
+ * }
1799
+ * ```
1800
+ */
1801
+ deleteOrder: (orderId: string, symbol: string) => Promise<HyperliquidDeleteOrderResponse>;
1802
+ /**
1803
+ * Get account balances
1804
+ *
1805
+ * Retrieve perp and spot account balances.
1806
+ *
1807
+ * **Output**: `HyperliquidBalancesResponse`
1808
+ * - `success` (boolean): Whether the operation was successful
1809
+ * - `data` (HyperliquidBalances | undefined): Balance data (only present on success)
1810
+ * - `data.perp` (HyperliquidPerpBalance): Perp account balance
1811
+ * - `data.perp.accountValue` (string): Total account value
1812
+ * - `data.perp.totalMarginUsed` (string): Total margin used
1813
+ * - `data.perp.withdrawable` (string): Withdrawable amount
1814
+ * - `data.spot` (HyperliquidSpotBalance[]): Spot token balances
1815
+ * - `data.spot[].coin` (string): Token symbol
1816
+ * - `data.spot[].total` (string): Total balance
1817
+ * - `data.spot[].hold` (string): Amount on hold
1818
+ * - `error` (string | undefined): Error message (only present on failure)
1819
+ *
1820
+ * @returns Promise resolving to HyperliquidBalancesResponse
1821
+ *
1822
+ * @example
1823
+ * ```ts
1824
+ * const result = await sdk.platforms.hyperliquid.balances();
1825
+ * if (result.success && result.data) {
1826
+ * console.log(`Account value: ${result.data.perp.accountValue}`);
1827
+ * console.log(`Withdrawable: ${result.data.perp.withdrawable}`);
1828
+ * for (const balance of result.data.spot) {
1829
+ * console.log(`${balance.coin}: ${balance.total}`);
1830
+ * }
1831
+ * } else {
1832
+ * console.error(`Error: ${result.error}`);
1833
+ * }
1834
+ * ```
1835
+ */
1836
+ balances: () => Promise<HyperliquidBalancesResponse>;
1837
+ /**
1838
+ * Get open positions
1839
+ *
1840
+ * Retrieve all open perpetual positions with PnL and position details.
1841
+ *
1842
+ * **Output**: `HyperliquidPositionsResponse`
1843
+ * - `success` (boolean): Whether the operation was successful
1844
+ * - `data` (HyperliquidPosition[] | undefined): Array of open positions (only present on success)
1845
+ * - `data[].symbol` (string): Trading pair symbol (e.g., "BTC-USD")
1846
+ * - `data[].side` ("long" | "short"): Position side
1847
+ * - `data[].size` (string): Position size
1848
+ * - `data[].entryPrice` (string): Average entry price
1849
+ * - `data[].markPrice` (string): Current mark price
1850
+ * - `data[].liquidationPrice` (string | null): Liquidation price (null if no risk)
1851
+ * - `data[].unrealizedPnl` (string): Unrealized profit/loss
1852
+ * - `data[].leverage` (string): Current leverage
1853
+ * - `data[].marginUsed` (string): Margin allocated to position
1854
+ * - `error` (string | undefined): Error message (only present on failure)
1855
+ *
1856
+ * @returns Promise resolving to HyperliquidPositionsResponse
1857
+ *
1858
+ * @example
1859
+ * ```ts
1860
+ * const result = await sdk.platforms.hyperliquid.positions();
1861
+ * if (result.success && result.data) {
1862
+ * for (const pos of result.data) {
1863
+ * console.log(`${pos.symbol}: ${pos.side} ${pos.size}`);
1864
+ * console.log(`Entry: ${pos.entryPrice}, Mark: ${pos.markPrice}`);
1865
+ * console.log(`Unrealized PnL: ${pos.unrealizedPnl}`);
1866
+ * }
1867
+ * } else {
1868
+ * console.error(`Error: ${result.error}`);
1869
+ * }
1870
+ * ```
1871
+ */
1872
+ positions: () => Promise<HyperliquidPositionsResponse>;
1873
+ /**
1874
+ * Get open orders
1875
+ *
1876
+ * Retrieve all currently open orders.
1877
+ *
1878
+ * **Output**: `HyperliquidOpenOrdersResponse`
1879
+ * - `success` (boolean): Whether the operation was successful
1880
+ * - `data` (HyperliquidOrderInfo[] | undefined): Array of open orders (only present on success)
1881
+ * - `data[].orderId` (string): Order ID
1882
+ * - `data[].symbol` (string): Trading pair symbol
1883
+ * - `data[].side` ("buy" | "sell"): Order side
1884
+ * - `data[].price` (number): Order price
1885
+ * - `data[].size` (number): Order size
1886
+ * - `data[].filled` (number): Filled amount
1887
+ * - `data[].status` (string): Order status
1888
+ * - `data[].market` ("perp" | "spot"): Market type
1889
+ * - `data[].clientOrderId` (string | undefined): Client order ID
1890
+ * - `error` (string | undefined): Error message (only present on failure)
1891
+ *
1892
+ * @returns Promise resolving to HyperliquidOpenOrdersResponse
1893
+ *
1894
+ * @example
1895
+ * ```ts
1896
+ * const result = await sdk.platforms.hyperliquid.openOrders();
1897
+ * if (result.success && result.data) {
1898
+ * console.log(`You have ${result.data.length} open orders`);
1899
+ * for (const order of result.data) {
1900
+ * console.log(`${order.symbol}: ${order.side} ${order.size} @ ${order.price}`);
1901
+ * }
1902
+ * } else {
1903
+ * console.error(`Error: ${result.error}`);
1904
+ * }
1905
+ * ```
1906
+ */
1907
+ openOrders: () => Promise<HyperliquidOpenOrdersResponse>;
1908
+ /**
1909
+ * Get order fill history
1910
+ *
1911
+ * Retrieve order fill history including partial and complete fills.
1912
+ *
1913
+ * **Output**: `HyperliquidOrderFillsResponse`
1914
+ * - `success` (boolean): Whether the operation was successful
1915
+ * - `data` (HyperliquidFill[] | undefined): Array of order fills (only present on success)
1916
+ * - `data[].orderId` (string): Order ID
1917
+ * - `data[].symbol` (string): Trading pair symbol
1918
+ * - `data[].side` ("buy" | "sell"): Fill side
1919
+ * - `data[].price` (string): Fill price
1920
+ * - `data[].size` (string): Fill size
1921
+ * - `data[].fee` (string): Trading fee paid
1922
+ * - `data[].timestamp` (number): Fill timestamp in milliseconds
1923
+ * - `data[].isMaker` (boolean): True if maker, false if taker
1924
+ * - `error` (string | undefined): Error message (only present on failure)
1925
+ *
1926
+ * @returns Promise resolving to HyperliquidOrderFillsResponse
1927
+ *
1928
+ * @example
1929
+ * ```ts
1930
+ * const result = await sdk.platforms.hyperliquid.orderFills();
1931
+ * if (result.success && result.data) {
1932
+ * console.log(`Total fills: ${result.data.length}`);
1933
+ * for (const fill of result.data) {
1934
+ * const fillType = fill.isMaker ? "maker" : "taker";
1935
+ * console.log(`${fill.symbol}: ${fill.size} @ ${fill.price} (${fillType}, fee: ${fill.fee})`);
1936
+ * }
1937
+ * } else {
1938
+ * console.error(`Error: ${result.error}`);
1939
+ * }
1940
+ * ```
1941
+ */
1942
+ orderFills: () => Promise<HyperliquidOrderFillsResponse>;
1943
+ /**
1944
+ * Get historical orders
1945
+ *
1946
+ * Retrieve order history including filled, cancelled, and expired orders.
1947
+ *
1948
+ * **Output**: `HyperliquidHistoricalOrdersResponse`
1949
+ * - `success` (boolean): Whether the operation was successful
1950
+ * - `data` (HyperliquidHistoricalOrder[] | undefined): Array of historical orders (only present on success)
1951
+ * - `data[].orderId` (string): Order ID
1952
+ * - `data[].symbol` (string): Trading pair symbol
1953
+ * - `data[].side` ("buy" | "sell"): Order side
1954
+ * - `data[].price` (number): Order price
1955
+ * - `data[].size` (number): Order size
1956
+ * - `data[].filled` (number): Filled amount
1957
+ * - `data[].status` ("open" | "filled" | "canceled" | "triggered" | "rejected" | "marginCanceled" | "liquidatedCanceled"): Order status
1958
+ * - `data[].market` ("perp" | "spot"): Market type
1959
+ * - `data[].timestamp` (number): Order creation timestamp in milliseconds
1960
+ * - `data[].statusTimestamp` (number): Status update timestamp in milliseconds
1961
+ * - `data[].orderType` ("Market" | "Limit" | "Stop Market" | "Stop Limit" | "Take Profit Market" | "Take Profit Limit"): Order type
1962
+ * - `data[].clientOrderId` (string | undefined): Client order ID
1963
+ * - `error` (string | undefined): Error message (only present on failure)
1964
+ *
1965
+ * @returns Promise resolving to HyperliquidHistoricalOrdersResponse
1966
+ *
1967
+ * @example
1968
+ * ```ts
1969
+ * const result = await sdk.platforms.hyperliquid.orders();
1970
+ * if (result.success && result.data) {
1971
+ * console.log(`Order history: ${result.data.length} orders`);
1972
+ * const filled = result.data.filter(o => o.status === "filled");
1973
+ * console.log(`Filled orders: ${filled.length}`);
1974
+ * } else {
1975
+ * console.error(`Error: ${result.error}`);
1976
+ * }
1977
+ * ```
1978
+ */
1979
+ orders: () => Promise<HyperliquidHistoricalOrdersResponse>;
1980
+ /**
1981
+ * Transfer between spot and perp accounts
1982
+ *
1983
+ * Move funds between your spot wallet and perpetuals trading account.
1984
+ *
1985
+ * **Input**: `HyperliquidTransferRequest`
1986
+ * - `amount` (number): Amount to transfer
1987
+ * - `toPerp` (boolean): True to transfer to perp account, False to transfer to spot
1988
+ *
1989
+ * **Output**: `HyperliquidTransferResponse`
1990
+ * - `success` (boolean): Whether the operation was successful
1991
+ * - `error` (string | undefined): Error message (only present on failure)
1992
+ *
1993
+ * Note: This operation returns no data on success (void response).
1994
+ *
1995
+ * @param request - Transfer parameters
1996
+ * @returns Promise resolving to HyperliquidTransferResponse
1997
+ *
1998
+ * @example
1999
+ * ```ts
2000
+ * // Transfer 1000 USDC to perp account
2001
+ * const result = await sdk.platforms.hyperliquid.transfer({
2002
+ * amount: 1000,
2003
+ * toPerp: true
2004
+ * });
2005
+ *
2006
+ * if (result.success) {
2007
+ * console.log("Transfer completed successfully");
2008
+ * } else {
2009
+ * console.error(`Error: ${result.error}`);
2010
+ * }
2011
+ * ```
2012
+ */
2013
+ transfer: (request: HyperliquidTransferRequest) => Promise<HyperliquidTransferResponse>;
2014
+ /**
2015
+ * Get liquidation events
2016
+ *
2017
+ * Retrieve liquidation events for the account, optionally filtered by start time.
2018
+ *
2019
+ * **Input**: `startTime` (number, optional) - Unix timestamp in milliseconds to filter liquidations from
2020
+ *
2021
+ * **Output**: `HyperliquidLiquidationsResponse`
2022
+ * - `success` (boolean): Whether the operation was successful
2023
+ * - `data` (HyperliquidLiquidation[] | undefined): Array of liquidation events (only present on success)
2024
+ * - `data[].timestamp` (number): Liquidation timestamp in milliseconds
2025
+ * - `data[].liquidatedPositions` (HyperliquidLiquidatedPosition[]): Liquidated positions
2026
+ * - `data[].liquidatedPositions[].symbol` (string): Position symbol (e.g., "BTC-USD")
2027
+ * - `data[].liquidatedPositions[].side` ("long" | "short"): Position side
2028
+ * - `data[].liquidatedPositions[].size` (string): Position size that was liquidated
2029
+ * - `data[].totalNotional` (string): Total notional value liquidated
2030
+ * - `data[].accountValue` (string): Account value at liquidation
2031
+ * - `data[].leverageType` ("Cross" | "Isolated"): Leverage type
2032
+ * - `data[].txHash` (string): Transaction hash
2033
+ * - `error` (string | undefined): Error message (only present on failure)
2034
+ *
2035
+ * @param startTime - Optional start time for filtering (Unix timestamp in milliseconds)
2036
+ * @returns Promise resolving to HyperliquidLiquidationsResponse
2037
+ *
2038
+ * @example
2039
+ * ```ts
2040
+ * // Get all liquidations (defaults to last 30 days)
2041
+ * const all = await sdk.platforms.hyperliquid.liquidations();
2042
+ *
2043
+ * // Get liquidations from last 24h
2044
+ * const yesterday = Date.now() - (24 * 60 * 60 * 1000);
2045
+ * const recent = await sdk.platforms.hyperliquid.liquidations(yesterday);
2046
+ *
2047
+ * if (recent.success && recent.data) {
2048
+ * console.log(`Liquidations in last 24h: ${recent.data.length}`);
2049
+ * for (const liq of recent.data) {
2050
+ * console.log(`Liquidated ${liq.liquidatedPositions.length} positions`);
2051
+ * }
2052
+ * } else {
2053
+ * console.error(`Error: ${recent.error}`);
2054
+ * }
2055
+ * ```
2056
+ */
2057
+ liquidations: (startTime?: number) => Promise<HyperliquidLiquidationsResponse>;
2058
+ };
1435
2059
  };
1436
2060
  /**
1437
2061
  * Handle EVM transaction signing and broadcasting
@@ -1463,6 +2087,46 @@ declare class AgentSdk {
1463
2087
  private handleSwidgeExecute;
1464
2088
  private handlePolymarketMarketOrder;
1465
2089
  private handlePolymarketRedeemPositions;
2090
+ /**
2091
+ * Handle Hyperliquid place order requests
2092
+ */
2093
+ private handleHyperliquidPlaceOrder;
2094
+ /**
2095
+ * Handle Hyperliquid get order requests
2096
+ */
2097
+ private handleHyperliquidGetOrder;
2098
+ /**
2099
+ * Handle Hyperliquid delete order requests
2100
+ */
2101
+ private handleHyperliquidDeleteOrder;
2102
+ /**
2103
+ * Handle Hyperliquid get balances requests
2104
+ */
2105
+ private handleHyperliquidGetBalances;
2106
+ /**
2107
+ * Handle Hyperliquid get positions requests
2108
+ */
2109
+ private handleHyperliquidGetPositions;
2110
+ /**
2111
+ * Handle Hyperliquid get open orders requests
2112
+ */
2113
+ private handleHyperliquidGetOpenOrders;
2114
+ /**
2115
+ * Handle Hyperliquid get order fills requests
2116
+ */
2117
+ private handleHyperliquidGetOrderFills;
2118
+ /**
2119
+ * Handle Hyperliquid get historical orders requests
2120
+ */
2121
+ private handleHyperliquidGetHistoricalOrders;
2122
+ /**
2123
+ * Handle Hyperliquid transfer requests
2124
+ */
2125
+ private handleHyperliquidTransfer;
2126
+ /**
2127
+ * Handle Hyperliquid get liquidations requests
2128
+ */
2129
+ private handleHyperliquidGetLiquidations;
1466
2130
  /**
1467
2131
  * Handle memory set requests
1468
2132
  */
@@ -1703,7 +2367,7 @@ interface CurrentPosition {
1703
2367
  * - **Request metadata**: `sessionId`, `sessionWalletAddress`, `currentPositions`
1704
2368
  * - **Core methods**: `log()`, `signAndSend()`, `signMessage()`
1705
2369
  * - **Memory operations**: `memory.set()`, `memory.get()`, `memory.delete()`, `memory.list()`
1706
- * - **Platform integrations**: `platforms.polymarket.*` for prediction market trading
2370
+ * - **Platform integrations**: `platforms.polymarket.*` for prediction market trading, `platforms.hyperliquid.*` for perpetuals trading
1707
2371
  * - **Cross-chain swaps**: `swidge.quote()`, `swidge.execute()`
1708
2372
  *
1709
2373
  * The agent developer's execution and stop functions receive this object:
@@ -1768,10 +2432,14 @@ interface CurrentPosition {
1768
2432
  * @property memory.delete - Delete a key from session memory
1769
2433
  * @property memory.list - List all keys in session memory
1770
2434
  *
1771
- * @property platforms - Platform integrations (Polymarket, etc.)
2435
+ * @property platforms - Platform integrations (Polymarket, Hyperliquid, etc.)
1772
2436
  * @property platforms.polymarket - Prediction market trading operations
1773
2437
  * @property platforms.polymarket.marketOrder - Execute a buy or sell market order on Polymarket
1774
2438
  * @property platforms.polymarket.redeemPositions - Redeem settled positions and claim winnings
2439
+ * @property platforms.hyperliquid - Perpetuals trading operations on Hyperliquid DEX
2440
+ * @property platforms.hyperliquid.placeOrder - Place an order on Hyperliquid
2441
+ * @property platforms.hyperliquid.balances - Get account balances
2442
+ * @property platforms.hyperliquid.positions - Get open positions
1775
2443
  *
1776
2444
  * @property swidge - Cross-chain swap and bridge operations
1777
2445
  * @property swidge.quote - Get a quote for swapping tokens between networks
@@ -2113,7 +2781,7 @@ declare class AgentContext {
2113
2781
  * Access platform integrations for trading and DeFi operations.
2114
2782
  *
2115
2783
  * Platform integrations provide seamless access to external services like
2116
- * prediction markets, lending protocols, and more.
2784
+ * prediction markets, perpetuals trading, and more.
2117
2785
  */
2118
2786
  readonly platforms: {
2119
2787
  /**
@@ -2205,6 +2873,399 @@ declare class AgentContext {
2205
2873
  */
2206
2874
  redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
2207
2875
  };
2876
+ /**
2877
+ * Access Hyperliquid perpetuals trading operations.
2878
+ *
2879
+ * Trade perpetual contracts on Hyperliquid DEX using your session wallet.
2880
+ */
2881
+ hyperliquid: {
2882
+ /**
2883
+ * Place an order on Hyperliquid
2884
+ *
2885
+ * Submit a market, limit, stop, or take-profit order for perpetuals or spot trading.
2886
+ *
2887
+ * **Input**: `HyperliquidPlaceOrderRequest`
2888
+ * - `symbol` (string): Trading pair symbol (e.g., "BTC-USD")
2889
+ * - `side` ("buy" | "sell"): Order side
2890
+ * - `size` (number): Order size
2891
+ * - `price` (number): Order price (for market orders, acts as slippage limit)
2892
+ * - `market` ("perp" | "spot"): Market type
2893
+ * - `type` (string, optional): Order type ("limit", "market", "stop", "take_profit")
2894
+ * - `triggerPrice` (number, optional): Trigger price for stop/take-profit orders
2895
+ * - `reduceOnly` (boolean, optional): Whether this is a reduce-only order
2896
+ * - `postOnly` (boolean, optional): Whether this is a post-only order
2897
+ *
2898
+ * **Output**: `HyperliquidPlaceOrderResponse`
2899
+ * - `success` (boolean): Whether the operation was successful
2900
+ * - `data` (HyperliquidOrderInfo | undefined): Order information (only present on success)
2901
+ * - `data.orderId` (string): Order ID
2902
+ * - `data.symbol` (string): Trading pair symbol
2903
+ * - `data.side` ("buy" | "sell"): Order side
2904
+ * - `data.price` (number): Order price
2905
+ * - `data.size` (number): Order size
2906
+ * - `data.filled` (number): Filled amount
2907
+ * - `data.status` (string): Order status
2908
+ * - `data.market` ("perp" | "spot"): Market type
2909
+ * - `data.clientOrderId` (string | undefined): Client order ID
2910
+ * - `error` (string | undefined): Error message (only present on failure)
2911
+ *
2912
+ * @param request - Order parameters
2913
+ * @returns Promise resolving to HyperliquidPlaceOrderResponse
2914
+ *
2915
+ * @example
2916
+ * ```ts
2917
+ * // Market order
2918
+ * const result = await agent.platforms.hyperliquid.placeOrder({
2919
+ * symbol: "BTC-USD",
2920
+ * side: "buy",
2921
+ * size: 0.0001,
2922
+ * price: 110000,
2923
+ * market: "perp",
2924
+ * type: "market",
2925
+ * });
2926
+ *
2927
+ * // Limit order
2928
+ * const result = await agent.platforms.hyperliquid.placeOrder({
2929
+ * symbol: "BTC-USD",
2930
+ * side: "buy",
2931
+ * size: 0.0001,
2932
+ * price: 100000,
2933
+ * market: "perp",
2934
+ * type: "limit",
2935
+ * });
2936
+ *
2937
+ * if (result.success && result.data) {
2938
+ * await agent.log(`Order placed: ${result.data.orderId}`);
2939
+ * await agent.log(`Status: ${result.data.status}`);
2940
+ * } else {
2941
+ * await agent.log(`Error: ${result.error}`, { error: true });
2942
+ * }
2943
+ * ```
2944
+ */
2945
+ placeOrder: (request: HyperliquidPlaceOrderRequest) => Promise<HyperliquidPlaceOrderResponse>;
2946
+ /**
2947
+ * Get order information by order ID
2948
+ *
2949
+ * Retrieve details for a specific order including status, filled amount, and price.
2950
+ *
2951
+ * **Input**: `orderId` (string) - Unique order identifier
2952
+ *
2953
+ * **Output**: `HyperliquidOrderResponse`
2954
+ * - `success` (boolean): Whether the operation was successful
2955
+ * - `data` (HyperliquidOrderInfo | undefined): Order details (only present on success)
2956
+ * - `data.orderId` (string): Order ID
2957
+ * - `data.symbol` (string): Trading pair symbol
2958
+ * - `data.side` ("buy" | "sell"): Order side
2959
+ * - `data.price` (number): Order price
2960
+ * - `data.size` (number): Order size
2961
+ * - `data.filled` (number): Filled amount
2962
+ * - `data.status` (string): Order status
2963
+ * - `data.market` ("perp" | "spot"): Market type
2964
+ * - `data.clientOrderId` (string | undefined): Client order ID
2965
+ * - `error` (string | undefined): Error message (only present on failure)
2966
+ *
2967
+ * @param orderId - Order ID to query
2968
+ * @returns Promise resolving to HyperliquidOrderResponse
2969
+ *
2970
+ * @example
2971
+ * ```ts
2972
+ * const result = await agent.platforms.hyperliquid.order("12345");
2973
+ * if (result.success && result.data) {
2974
+ * await agent.log(`Order ${result.data.orderId}: ${result.data.status}`);
2975
+ * await agent.log(`Filled: ${result.data.filled}/${result.data.size}`);
2976
+ * } else {
2977
+ * await agent.log(`Error: ${result.error}`, { error: true });
2978
+ * }
2979
+ * ```
2980
+ */
2981
+ order: (orderId: string) => Promise<HyperliquidOrderResponse>;
2982
+ /**
2983
+ * Cancel an order
2984
+ *
2985
+ * Cancel an open order by order ID and symbol.
2986
+ *
2987
+ * **Input**:
2988
+ * - `orderId` (string): Order ID to cancel
2989
+ * - `symbol` (string): Trading symbol
2990
+ *
2991
+ * **Output**: `HyperliquidDeleteOrderResponse`
2992
+ * - `success` (boolean): Whether the operation was successful
2993
+ * - `error` (string | undefined): Error message (only present on failure)
2994
+ *
2995
+ * Note: This operation returns no data on success (void response).
2996
+ *
2997
+ * @param orderId - Order ID to cancel
2998
+ * @param symbol - Trading symbol
2999
+ * @returns Promise resolving to HyperliquidDeleteOrderResponse
3000
+ *
3001
+ * @example
3002
+ * ```ts
3003
+ * const result = await agent.platforms.hyperliquid.deleteOrder("12345", "BTC-USD");
3004
+ * if (result.success) {
3005
+ * await agent.log("Order cancelled successfully");
3006
+ * } else {
3007
+ * await agent.log(`Error: ${result.error}`, { error: true });
3008
+ * }
3009
+ * ```
3010
+ */
3011
+ deleteOrder: (orderId: string, symbol: string) => Promise<HyperliquidDeleteOrderResponse>;
3012
+ /**
3013
+ * Get account balances
3014
+ *
3015
+ * Retrieve perp and spot account balances.
3016
+ *
3017
+ * **Output**: `HyperliquidBalancesResponse`
3018
+ * - `success` (boolean): Whether the operation was successful
3019
+ * - `data` (HyperliquidBalances | undefined): Balance data (only present on success)
3020
+ * - `data.perp` (HyperliquidPerpBalance): Perp account balance
3021
+ * - `data.perp.accountValue` (string): Total account value
3022
+ * - `data.perp.totalMarginUsed` (string): Total margin used
3023
+ * - `data.perp.withdrawable` (string): Withdrawable amount
3024
+ * - `data.spot` (HyperliquidSpotBalance[]): Spot token balances
3025
+ * - `data.spot[].coin` (string): Token symbol
3026
+ * - `data.spot[].total` (string): Total balance
3027
+ * - `data.spot[].hold` (string): Amount on hold
3028
+ * - `error` (string | undefined): Error message (only present on failure)
3029
+ *
3030
+ * @returns Promise resolving to HyperliquidBalancesResponse
3031
+ *
3032
+ * @example
3033
+ * ```ts
3034
+ * const result = await agent.platforms.hyperliquid.balances();
3035
+ * if (result.success && result.data) {
3036
+ * await agent.log(`Account value: ${result.data.perp.accountValue}`);
3037
+ * await agent.log(`Withdrawable: ${result.data.perp.withdrawable}`);
3038
+ * for (const balance of result.data.spot) {
3039
+ * await agent.log(`${balance.coin}: ${balance.total}`);
3040
+ * }
3041
+ * } else {
3042
+ * await agent.log(`Error: ${result.error}`, { error: true });
3043
+ * }
3044
+ * ```
3045
+ */
3046
+ balances: () => Promise<HyperliquidBalancesResponse>;
3047
+ /**
3048
+ * Get open positions
3049
+ *
3050
+ * Retrieve all open perpetual positions with PnL and position details.
3051
+ *
3052
+ * **Output**: `HyperliquidPositionsResponse`
3053
+ * - `success` (boolean): Whether the operation was successful
3054
+ * - `data` (HyperliquidPosition[] | undefined): Array of open positions (only present on success)
3055
+ * - `data[].symbol` (string): Trading pair symbol (e.g., "BTC-USD")
3056
+ * - `data[].side` ("long" | "short"): Position side
3057
+ * - `data[].size` (string): Position size
3058
+ * - `data[].entryPrice` (string): Average entry price
3059
+ * - `data[].markPrice` (string): Current mark price
3060
+ * - `data[].liquidationPrice` (string | null): Liquidation price (null if no risk)
3061
+ * - `data[].unrealizedPnl` (string): Unrealized profit/loss
3062
+ * - `data[].leverage` (string): Current leverage
3063
+ * - `data[].marginUsed` (string): Margin allocated to position
3064
+ * - `error` (string | undefined): Error message (only present on failure)
3065
+ *
3066
+ * @returns Promise resolving to HyperliquidPositionsResponse
3067
+ *
3068
+ * @example
3069
+ * ```ts
3070
+ * const result = await agent.platforms.hyperliquid.positions();
3071
+ * if (result.success && result.data) {
3072
+ * for (const pos of result.data) {
3073
+ * await agent.log(`${pos.symbol}: ${pos.side} ${pos.size}`);
3074
+ * await agent.log(`Entry: ${pos.entryPrice}, Mark: ${pos.markPrice}`);
3075
+ * await agent.log(`Unrealized PnL: ${pos.unrealizedPnl}`);
3076
+ * }
3077
+ * } else {
3078
+ * await agent.log(`Error: ${result.error}`, { error: true });
3079
+ * }
3080
+ * ```
3081
+ */
3082
+ positions: () => Promise<HyperliquidPositionsResponse>;
3083
+ /**
3084
+ * Get open orders
3085
+ *
3086
+ * Retrieve all currently open orders.
3087
+ *
3088
+ * **Output**: `HyperliquidOpenOrdersResponse`
3089
+ * - `success` (boolean): Whether the operation was successful
3090
+ * - `data` (HyperliquidOrderInfo[] | undefined): Array of open orders (only present on success)
3091
+ * - `data[].orderId` (string): Order ID
3092
+ * - `data[].symbol` (string): Trading pair symbol
3093
+ * - `data[].side` ("buy" | "sell"): Order side
3094
+ * - `data[].price` (number): Order price
3095
+ * - `data[].size` (number): Order size
3096
+ * - `data[].filled` (number): Filled amount
3097
+ * - `data[].status` (string): Order status
3098
+ * - `data[].market` ("perp" | "spot"): Market type
3099
+ * - `data[].clientOrderId` (string | undefined): Client order ID
3100
+ * - `error` (string | undefined): Error message (only present on failure)
3101
+ *
3102
+ * @returns Promise resolving to HyperliquidOpenOrdersResponse
3103
+ *
3104
+ * @example
3105
+ * ```ts
3106
+ * const result = await agent.platforms.hyperliquid.openOrders();
3107
+ * if (result.success && result.data) {
3108
+ * await agent.log(`You have ${result.data.length} open orders`);
3109
+ * for (const order of result.data) {
3110
+ * await agent.log(`${order.symbol}: ${order.side} ${order.size} @ ${order.price}`);
3111
+ * }
3112
+ * } else {
3113
+ * await agent.log(`Error: ${result.error}`, { error: true });
3114
+ * }
3115
+ * ```
3116
+ */
3117
+ openOrders: () => Promise<HyperliquidOpenOrdersResponse>;
3118
+ /**
3119
+ * Get order fill history
3120
+ *
3121
+ * Retrieve order fill history including partial and complete fills.
3122
+ *
3123
+ * **Output**: `HyperliquidOrderFillsResponse`
3124
+ * - `success` (boolean): Whether the operation was successful
3125
+ * - `data` (HyperliquidFill[] | undefined): Array of order fills (only present on success)
3126
+ * - `data[].orderId` (string): Order ID
3127
+ * - `data[].symbol` (string): Trading pair symbol
3128
+ * - `data[].side` ("buy" | "sell"): Fill side
3129
+ * - `data[].price` (string): Fill price
3130
+ * - `data[].size` (string): Fill size
3131
+ * - `data[].fee` (string): Trading fee paid
3132
+ * - `data[].timestamp` (number): Fill timestamp in milliseconds
3133
+ * - `data[].isMaker` (boolean): True if maker, false if taker
3134
+ * - `error` (string | undefined): Error message (only present on failure)
3135
+ *
3136
+ * @returns Promise resolving to HyperliquidOrderFillsResponse
3137
+ *
3138
+ * @example
3139
+ * ```ts
3140
+ * const result = await agent.platforms.hyperliquid.orderFills();
3141
+ * if (result.success && result.data) {
3142
+ * await agent.log(`Total fills: ${result.data.length}`);
3143
+ * for (const fill of result.data) {
3144
+ * const fillType = fill.isMaker ? "maker" : "taker";
3145
+ * await agent.log(`${fill.symbol}: ${fill.size} @ ${fill.price} (${fillType}, fee: ${fill.fee})`);
3146
+ * }
3147
+ * } else {
3148
+ * await agent.log(`Error: ${result.error}`, { error: true });
3149
+ * }
3150
+ * ```
3151
+ */
3152
+ orderFills: () => Promise<HyperliquidOrderFillsResponse>;
3153
+ /**
3154
+ * Get historical orders
3155
+ *
3156
+ * Retrieve order history including filled, cancelled, and expired orders.
3157
+ *
3158
+ * **Output**: `HyperliquidHistoricalOrdersResponse`
3159
+ * - `success` (boolean): Whether the operation was successful
3160
+ * - `data` (HyperliquidHistoricalOrder[] | undefined): Array of historical orders (only present on success)
3161
+ * - `data[].orderId` (string): Order ID
3162
+ * - `data[].symbol` (string): Trading pair symbol
3163
+ * - `data[].side` ("buy" | "sell"): Order side
3164
+ * - `data[].price` (number): Order price
3165
+ * - `data[].size` (number): Order size
3166
+ * - `data[].filled` (number): Filled amount
3167
+ * - `data[].status` ("open" | "filled" | "canceled" | "triggered" | "rejected" | "marginCanceled" | "liquidatedCanceled"): Order status
3168
+ * - `data[].market` ("perp" | "spot"): Market type
3169
+ * - `data[].timestamp` (number): Order creation timestamp in milliseconds
3170
+ * - `data[].statusTimestamp` (number): Status update timestamp in milliseconds
3171
+ * - `data[].orderType` ("Market" | "Limit" | "Stop Market" | "Stop Limit" | "Take Profit Market" | "Take Profit Limit"): Order type
3172
+ * - `data[].clientOrderId` (string | undefined): Client order ID
3173
+ * - `error` (string | undefined): Error message (only present on failure)
3174
+ *
3175
+ * @returns Promise resolving to HyperliquidHistoricalOrdersResponse
3176
+ *
3177
+ * @example
3178
+ * ```ts
3179
+ * const result = await agent.platforms.hyperliquid.orders();
3180
+ * if (result.success && result.data) {
3181
+ * await agent.log(`Order history: ${result.data.length} orders`);
3182
+ * const filled = result.data.filter(o => o.status === "filled");
3183
+ * await agent.log(`Filled orders: ${filled.length}`);
3184
+ * } else {
3185
+ * await agent.log(`Error: ${result.error}`, { error: true });
3186
+ * }
3187
+ * ```
3188
+ */
3189
+ orders: () => Promise<HyperliquidHistoricalOrdersResponse>;
3190
+ /**
3191
+ * Transfer between spot and perp accounts
3192
+ *
3193
+ * Move funds between your spot wallet and perpetuals trading account.
3194
+ *
3195
+ * **Input**: `HyperliquidTransferRequest`
3196
+ * - `amount` (number): Amount to transfer
3197
+ * - `toPerp` (boolean): True to transfer to perp account, False to transfer to spot
3198
+ *
3199
+ * **Output**: `HyperliquidTransferResponse`
3200
+ * - `success` (boolean): Whether the operation was successful
3201
+ * - `error` (string | undefined): Error message (only present on failure)
3202
+ *
3203
+ * Note: This operation returns no data on success (void response).
3204
+ *
3205
+ * @param request - Transfer parameters
3206
+ * @returns Promise resolving to HyperliquidTransferResponse
3207
+ *
3208
+ * @example
3209
+ * ```ts
3210
+ * // Transfer 1000 USDC to perp account
3211
+ * const result = await agent.platforms.hyperliquid.transfer({
3212
+ * amount: 1000,
3213
+ * toPerp: true
3214
+ * });
3215
+ *
3216
+ * if (result.success) {
3217
+ * await agent.log("Transfer completed successfully");
3218
+ * } else {
3219
+ * await agent.log(`Error: ${result.error}`, { error: true });
3220
+ * }
3221
+ * ```
3222
+ */
3223
+ transfer: (request: HyperliquidTransferRequest) => Promise<HyperliquidTransferResponse>;
3224
+ /**
3225
+ * Get liquidation events
3226
+ *
3227
+ * Retrieve liquidation events for the account, optionally filtered by start time.
3228
+ *
3229
+ * **Input**: `startTime` (number, optional) - Unix timestamp in milliseconds to filter liquidations from
3230
+ *
3231
+ * **Output**: `HyperliquidLiquidationsResponse`
3232
+ * - `success` (boolean): Whether the operation was successful
3233
+ * - `data` (HyperliquidLiquidation[] | undefined): Array of liquidation events (only present on success)
3234
+ * - `data[].timestamp` (number): Liquidation timestamp in milliseconds
3235
+ * - `data[].liquidatedPositions` (HyperliquidLiquidatedPosition[]): Liquidated positions
3236
+ * - `data[].liquidatedPositions[].symbol` (string): Position symbol (e.g., "BTC-USD")
3237
+ * - `data[].liquidatedPositions[].side` ("long" | "short"): Position side
3238
+ * - `data[].liquidatedPositions[].size` (string): Position size that was liquidated
3239
+ * - `data[].totalNotional` (string): Total notional value liquidated
3240
+ * - `data[].accountValue` (string): Account value at liquidation
3241
+ * - `data[].leverageType` ("Cross" | "Isolated"): Leverage type
3242
+ * - `data[].txHash` (string): Transaction hash
3243
+ * - `error` (string | undefined): Error message (only present on failure)
3244
+ *
3245
+ * @param startTime - Optional start time for filtering (Unix timestamp in milliseconds)
3246
+ * @returns Promise resolving to HyperliquidLiquidationsResponse
3247
+ *
3248
+ * @example
3249
+ * ```ts
3250
+ * // Get all liquidations (defaults to last 30 days)
3251
+ * const all = await agent.platforms.hyperliquid.liquidations();
3252
+ *
3253
+ * // Get liquidations from last 24h
3254
+ * const yesterday = Date.now() - (24 * 60 * 60 * 1000);
3255
+ * const recent = await agent.platforms.hyperliquid.liquidations(yesterday);
3256
+ *
3257
+ * if (recent.success && recent.data) {
3258
+ * await agent.log(`Liquidations in last 24h: ${recent.data.length}`);
3259
+ * for (const liq of recent.data) {
3260
+ * await agent.log(`Liquidated ${liq.liquidatedPositions.length} positions`);
3261
+ * }
3262
+ * } else {
3263
+ * await agent.log(`Error: ${recent.error}`, { error: true });
3264
+ * }
3265
+ * ```
3266
+ */
3267
+ liquidations: (startTime?: number) => Promise<HyperliquidLiquidationsResponse>;
3268
+ };
2208
3269
  };
2209
3270
  /**
2210
3271
  * Access cross-chain swap and bridge operations.
@@ -2560,4 +3621,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
2560
3621
  */
2561
3622
  declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
2562
3623
 
2563
- export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, type EnrichedPosition, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, type TransactionsResponse, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
3624
+ export { APIClient, Agent, AgentContext, AgentSdk, type AssetChange, type CurrentPosition, type CurrentPositionsData, type CurrentPositionsResponse, type EnrichedPosition, type HyperliquidBalancesResponse, type HyperliquidDeleteOrderResponse, type HyperliquidHistoricalOrdersResponse, type HyperliquidLiquidationsResponse, type HyperliquidOpenOrdersResponse, type HyperliquidOrderFillsResponse, type HyperliquidOrderResponse, type HyperliquidPlaceOrderRequest, type HyperliquidPlaceOrderResponse, type HyperliquidPositionsResponse, type HyperliquidTransferRequest, type HyperliquidTransferResponse, type LogResponse, type MemoryDeleteResponse, type MemoryGetResponse, type MemoryListResponse, type MemorySetResponse, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketRedeemPositionsRequest, type PolymarketRedeemPositionsResponse, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, type TransactionsResponse, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork, type runFunctionContract };
package/index.js CHANGED
@@ -1 +1 @@
1
- import{loadAuthFromFileSystem as e}from"./chunk-4I3A6QAK.js";var r=class{config;baseUrl;authorizationHeader;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){if(this.isCloudflareWorker()){if(void 0!==globalThis.AGENTS_TO_API_PROXY)return!0;if(void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)return!0}return!1}constructor(e){this.config=e,this.baseUrl=e.baseUrl||"https://agents.circuit.org",this.authorizationHeader=e.authorizationHeader}getAgentSlug(){return"undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG?process.env.CIRCUIT_AGENT_SLUG:void 0!==globalThis.CIRCUIT_AGENT_SLUG?globalThis.CIRCUIT_AGENT_SLUG:void 0}getAuthHeaders(){const e={};e["X-Session-Id"]=this.config.sessionId.toString();const r=this.getAgentSlug();if(r&&(e["X-Agent-Slug"]=r),this.isCloudflareWorker())return e;if(this.authorizationHeader)return e.Authorization=this.authorizationHeader,e;try{const r=this.loadAuthConfig();r?.sessionToken&&(e.Authorization=`Bearer ${r.sessionToken}`)}catch{}return e}loadAuthConfig(){try{return e()}catch{}}async makeRequest(e,r={}){const t={...{"Content-Type":"application/json",...this.getAuthHeaders()},...r.headers};let s;if(this.hasServiceBinding()){let o;if(void 0!==globalThis.AGENTS_TO_API_PROXY)o=globalThis.AGENTS_TO_API_PROXY;else{if(void 0===globalThis.__AGENT_ENV__||!globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)throw new Error("Service binding detected but not accessible");o=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}const a={...r,headers:t},n=`https://agents-to-api-proxy.circuit-0bc.workers.dev${e}`;s=await o.fetch(n,a)}else{const o=`${this.baseUrl}${e}`,a={...r,headers:t};s=await fetch(o,a)}if(!s.ok){const e=await s.json().catch(()=>({})),r=e.message||e.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(r);throw t.error=e.error,t.errorMessage=e.message,t.errorDetails=e,t.statusCode=s.status,t}return await s.json()}async get(e){return this.makeRequest(e,{method:"GET"})}async post(e,r){return this.makeRequest(e,{method:"POST",body:r?JSON.stringify(r):void 0})}async delete(e){return this.makeRequest(e,{method:"DELETE"})}};function t(e){return e.startsWith("ethereum:")}function s(e){return"solana"===e}function o(e){return Number(e.split(":")[1])}var a=class{client;config;constructor(e){this.config=e,this.client=new r(e)}async _sendLog(e){await this.client.post("/v1/logs",e)}async signAndSend(e){try{if(t(e.network)){const r=o(e.network);if("toAddress"in e.request)return await this.handleEvmTransaction({chainId:r,toAddress:e.request.toAddress,data:e.request.data,valueWei:e.request.value,message:e.message})}if(s(e.network)&&"hexTransaction"in e.request)return await this.handleSolanaTransaction({hexTransaction:e.request.hexTransaction,message:e.message});const r=`Unsupported network: ${e.network}`;return{success:!1,error:"Unsupported Network",errorMessage:r,errorDetails:{message:r}}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{};return r||t?{success:!1,error:r,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:e instanceof Error?e.message:"Unknown error",errorDetails:{}}}}async signMessage(e){try{if(t(e.network))return await this.handleEvmSignMessage(e);const r=`Unsupported network: ${e.network}`;return{success:!1,error:"Unsupported Network",errorMessage:r,errorDetails:{message:r}}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{};return r||t?{success:!1,error:r,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:e instanceof Error?e.message:"Unknown error",errorDetails:{}}}}swidge={quote:async e=>this.handleSwidgeQuote(e),execute:function(e){return this.handleSwidgeExecute(e)}.bind(this)};memory={set:async(e,r)=>this.handleMemorySet(e,r),get:async e=>this.handleMemoryGet(e),delete:async e=>this.handleMemoryDelete(e),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async e=>this.handlePolymarketMarketOrder(e),redeemPositions:async e=>this.handlePolymarketRedeemPositions(e||{tokenIds:[]})}};async handleEvmTransaction(e){try{const r=await this.client.post("/v1/transactions/evm",e),t=await this.client.post(`/v1/transactions/evm/${r.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:r.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{};return r||t?{success:!1,error:r,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:e instanceof Error?e.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(e){try{const r=await this.client.post("/v1/transactions/solana",e),t=await this.client.post(`/v1/transactions/solana/${r.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:r.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{};return r||t?{success:!1,error:r,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:e instanceof Error?e.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(e){try{return{success:!0,data:await this.client.post("/v1/messages/evm",{messageType:e.request.messageType,data:e.request.data,chainId:e.request.chainId})}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{};return r||t?{success:!1,error:r,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:e instanceof Error?e.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(e){try{return await this.client.post(`/v1/jobs/${e.jobId}/status`,e)}catch(e){return{status:400,message:`Failed to update job status: ${e instanceof Error?e.message:"Unknown error"}`}}}async handleSwidgeQuote(e){try{return{success:!0,data:await this.client.post("/v1/swidge/quote",e)}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to get swidge quote";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(e){try{const r=await this.client.post("/v1/swidge/execute",e);if(Array.isArray(r))return r.map(e=>{const r="success"===e.status;return{success:r,data:e,error:r?void 0:e.error}});const t="success"===r.status;return{success:t,data:r,error:t?void 0:r.error}}catch(r){const t=r.error,s=r.errorMessage,o=r.errorDetails||{},a=r instanceof Error?r.message:"Failed to execute swidge swap";return Array.isArray(e)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}}}async handlePolymarketMarketOrder(e){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/market-order",e)}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to execute polymarket market order";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(e){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/redeem-positions",e)}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to redeem polymarket positions";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemorySet(e,r){try{return{success:!0,data:await this.client.post(`/v1/memory/${e}`,{value:r})}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to set memory";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(e){try{return{success:!0,data:await this.client.get(`/v1/memory/${e}`)}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to get memory";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(e){try{return{success:!0,data:await this.client.delete(`/v1/memory/${e}`)}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to delete memory";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return{success:!0,data:await this.client.get("/v1/memory/list")}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to list memory keys";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return{success:!0,data:await this.client.get("/v1/transactions/ledger")}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to fetch transactions";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return{success:!0,data:await this.client.get("/v1/positions/current")}}catch(e){const r=e.error,t=e.errorMessage,s=e.errorDetails||{},o=e instanceof Error?e.message:"Failed to fetch current positions";return{success:!1,error:r||"SDK Error",errorMessage:t||o,errorDetails:s}}}};import{existsSync as n,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var m=class{sessionId;sessionWalletAddress;currentPositions;t;constructor(e){this.sessionId=e.sessionId,this.sessionWalletAddress=e.sessionWalletAddress,this.currentPositions=e.currentPositions,this.t=new a({sessionId:e.sessionId,baseUrl:e.baseUrl,authorizationHeader:e.authorizationHeader})}async log(e,r){const{error:t=!1,debug:s=!1}=r||{};let o,a;const n=(e,r)=>{if("bigint"==typeof r)return r.toString();if("function"==typeof r)return`[Function: ${r.name||"anonymous"}]`;if(void 0===r)return"[undefined]";if(null===r)return null;if("object"==typeof r&&!Array.isArray(r)&&r.toString!==Object.prototype.toString)try{const e=r.toString();if("[object Object]"!==e)return e}catch(e){}return r};if("object"==typeof e&&null!==e?(o=JSON.stringify(e,n,2),a=JSON.stringify(e,n)):(o=String(e),a=String(e)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{const e=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,shortMessage:e}]),{success:!0}}catch(e){const r=e instanceof Error?e.message:"Failed to send log";return console.error(`Failed to send log to backend: ${r}`),{success:!1,error:"Log Error",errorMessage:r,errorDetails:{message:r,type:e instanceof Error?e.constructor.name:"UnknownError"}}}}async signAndSend(e){return this.t.signAndSend(e)}async signMessage(e){return this.t.signMessage(e)}memory={set:async(e,r)=>this.t.memory.set(e,r),get:async e=>this.t.memory.get(e),delete:async e=>this.t.memory.delete(e),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async e=>this.t.platforms.polymarket.marketOrder(e),redeemPositions:async e=>this.t.platforms.polymarket.redeemPositions(e)}};swidge={quote:async e=>this.t.swidge.quote(e),execute:function(e){return this.t.swidge.execute(e)}.bind(this)};async transactions(){return this.t.transactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},g=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),y=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(g)}),p=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(e){this.app=new l,this.runFunction=e.runFunction,this.stopFunction=e.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async e=>{await e.log(`Agent stopped for session ${e.sessionId}`)};async executeWithJobTracking(e,r,t){let s,o=!1;try{const s=new m({sessionId:e.sessionId,sessionWalletAddress:e.sessionWalletAddress,currentPositions:e.currentPositions,authorizationHeader:t});await r(s),o=!0}catch(e){s=this.getErrorMessage(e),o=!1,console.error("Agent function error:",s)}finally{e.jobId&&await this.updateJobStatus(e.sessionId,e.jobId,o?"success":"failed",s,t)}}getErrorMessage(e){if(null==e)return"Unknown error";try{const r=e?.constructor?.name||"Error";let t="";t=e instanceof Error&&e.message||String(e),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${r}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(e,r,t,s,o){const n=new a({sessionId:e,authorizationHeader:o});for(let e=1;e<=3;e++)try{return void await n._updateJobStatus({jobId:r,status:t,errorMessage:s})}catch(r){console.error(`Status update attempt ${e}/3 failed:`,r),e<3&&await new Promise(r=>setTimeout(r,100*2**(e-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await n._updateJobStatus({jobId:r,status:t,errorMessage:void 0})}catch(e){console.error(`CRITICAL: Failed to update job ${r} status. Likely API connectivity issue:`,e)}else console.error(`CRITICAL: Failed to update job ${r} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",y),async e=>{const r=e.req.valid("json"),t=e.req.header("Authorization");return await this.executeWithJobTracking(r,this.runFunction,t),e.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",y),async e=>{const r=e.req.valid("json"),t=e.req.header("Authorization");return await this.executeWithJobTracking(r,this.runFunction,t),e.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",y),async e=>{const r=e.req.valid("json"),t=e.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(r,s,t),e.json({success:!0,message:"Stop completed"})}),this.app.get("/health",async e=>{try{const r=await this.healthCheckFunction();return e.json(r)}catch(r){return console.error("Agent health check error:",r),e.json({status:"unhealthy",error:r instanceof Error?r.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const e=c(process.cwd(),"package.json");if(n(e)){const r=JSON.parse(i(e,"utf-8"));if(r.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(r.circuit.port,10)}}catch(e){console.log("Could not read package.json for port configuration")}return null}async run(e){if("undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare)return this.getExport();const r=globalThis.Bun?.env,t=process.env.AGENT_PORT||r?.AGENT_PORT,s=this.getPortFromPackageJson();let o=e;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${e||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${r?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:e}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /stop"),e({fetch:this.app.fetch,port:o})}catch(e){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:async(e,r,t)=>(r&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=r),this.app.fetch(e,r,t))}}});import{z as f}from"zod";var w=f.templateLiteral(["ethereum:",f.coerce.number().int().nonnegative()]),v=f.union([f.literal("solana"),w]),E=f.object({address:f.string(),network:v}),T=(f.object({from:E,to:E,fromToken:f.string().optional(),toToken:f.string().optional(),amount:f.string(),slippage:f.string().optional()}),f.object({network:v,address:f.string(),token:f.string().nullable(),name:f.string().optional(),symbol:f.string().optional(),decimals:f.number().optional(),amount:f.string().optional(),minimumAmount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()})),b=f.object({usd:f.string().optional(),percentage:f.string().optional()}),k=f.object({name:f.string(),amount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()}),D=f.object({programId:f.string(),keys:f.array(f.object({pubkey:f.string(),isSigner:f.boolean(),isWritable:f.boolean()})),data:f.union([f.string(),f.instanceof(Buffer)])}),S=f.object({type:f.literal("evm"),from:f.string().regex(/^0x[a-fA-F0-9]{40}$/),to:f.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:f.number(),value:f.number(),data:f.string().regex(/^0x[a-fA-F0-9]*$/),gas:f.number().nullish(),maxFeePerGas:f.number().nullish(),maxPriorityFeePerGas:f.number().nullish()}),A=f.object({type:f.literal("solana"),instructions:f.array(D),addressLookupTableAddresses:f.array(f.string())}),M=f.object({type:f.literal("transaction"),description:f.string(),transactionDetails:f.union([S,A]),metadata:f.record(f.string(),f.string())}),F=f.object({type:f.literal("signature"),description:f.string(),signatureData:f.string(),metadata:f.record(f.string(),f.string())}),$=f.discriminatedUnion("type",[M,F]),O=f.object({engine:f.literal("relay"),assetSend:T,assetReceive:T,priceImpact:b,fees:f.array(k),steps:f.array($)}),U=f.object({network:f.string(),txs:f.array(f.string())}),x=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:U,out:U,lastUpdated:f.number(),error:f.string().optional()}),I={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"},P=e=>f.object({success:f.boolean(),data:e.optional(),error:f.string().optional(),errorMessage:f.string().optional(),errorDetails:f.object({message:f.string().optional(),error:f.string().optional(),status:f.number().optional(),statusText:f.string().optional()}).optional()});P(O),P(x);export{r as APIClient,p as Agent,m as AgentContext,a as AgentSdk,I as QUOTE_RESULT,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
1
+ import{loadAuthFromFileSystem as r}from"./chunk-4I3A6QAK.js";var e=class{config;baseUrl;authorizationHeader;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){if(this.isCloudflareWorker()){if(void 0!==globalThis.AGENTS_TO_API_PROXY)return!0;if(void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)return!0}return!1}constructor(r){this.config=r,this.baseUrl=r.baseUrl||"https://agents.circuit.org",this.authorizationHeader=r.authorizationHeader}getAgentSlug(){return"undefined"!=typeof process&&process.env?.CIRCUIT_AGENT_SLUG?process.env.CIRCUIT_AGENT_SLUG:void 0!==globalThis.CIRCUIT_AGENT_SLUG?globalThis.CIRCUIT_AGENT_SLUG:void 0}getAuthHeaders(){const r={};r["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(r["X-Agent-Slug"]=e),this.isCloudflareWorker())return r;if(this.authorizationHeader)return r.Authorization=this.authorizationHeader,r;try{const e=this.loadAuthConfig();e?.sessionToken&&(r.Authorization=`Bearer ${e.sessionToken}`)}catch{}return r}loadAuthConfig(){try{return r()}catch{}}async makeRequest(r,e={}){const t={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let s;if(this.hasServiceBinding()){let o;if(void 0!==globalThis.AGENTS_TO_API_PROXY)o=globalThis.AGENTS_TO_API_PROXY;else{if(void 0===globalThis.__AGENT_ENV__||!globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)throw new Error("Service binding detected but not accessible");o=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}const a={...e,headers:t},n=`https://agents-to-api-proxy.circuit-0bc.workers.dev${r}`;s=await o.fetch(n,a)}else{const o=`${this.baseUrl}${r}`,a={...e,headers:t};s=await fetch(o,a)}if(!s.ok){const r=await s.json().catch(()=>({})),e=r.message||r.error||`HTTP ${s.status}: ${s.statusText}`,t=new Error(e);throw t.error=r.error,t.errorMessage=r.message,t.errorDetails=r,t.statusCode=s.status,t}return await s.json()}async get(r){return this.makeRequest(r,{method:"GET"})}async post(r,e){return this.makeRequest(r,{method:"POST",body:e?JSON.stringify(e):void 0})}async delete(r){return this.makeRequest(r,{method:"DELETE"})}};function t(r){return r.startsWith("ethereum:")}function s(r){return"solana"===r}function o(r){return Number(r.split(":")[1])}var a=class{client;config;constructor(r){this.config=r,this.client=new e(r)}async _sendLog(r){await this.client.post("/v1/logs",r)}async signAndSend(r){try{if(t(r.network)){const e=o(r.network);if("toAddress"in r.request)return await this.handleEvmTransaction({chainId:e,toAddress:r.request.toAddress,data:r.request.data,valueWei:r.request.value,message:r.message})}if(s(r.network)&&"hexTransaction"in r.request)return await this.handleSolanaTransaction({hexTransaction:r.request.hexTransaction,message:r.message});const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async signMessage(r){try{if(t(r.network))return await this.handleEvmSignMessage(r);const e=`Unsupported network: ${r.network}`;return{success:!1,error:"Unsupported Network",errorMessage:e,errorDetails:{message:e}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}swidge={quote:async r=>this.handleSwidgeQuote(r),execute:function(r){return this.handleSwidgeExecute(r)}.bind(this)};memory={set:async(r,e)=>this.handleMemorySet(r,e),get:async r=>this.handleMemoryGet(r),delete:async r=>this.handleMemoryDelete(r),list:async()=>this.handleMemoryList()};platforms={polymarket:{marketOrder:async r=>this.handlePolymarketMarketOrder(r),redeemPositions:async r=>this.handlePolymarketRedeemPositions(r||{tokenIds:[]})},hyperliquid:{placeOrder:async r=>this.handleHyperliquidPlaceOrder(r),order:async r=>this.handleHyperliquidGetOrder(r),deleteOrder:async(r,e)=>this.handleHyperliquidDeleteOrder(r,e),balances:async()=>this.handleHyperliquidGetBalances(),positions:async()=>this.handleHyperliquidGetPositions(),openOrders:async()=>this.handleHyperliquidGetOpenOrders(),orderFills:async()=>this.handleHyperliquidGetOrderFills(),orders:async()=>this.handleHyperliquidGetHistoricalOrders(),transfer:async r=>this.handleHyperliquidTransfer(r),liquidations:async r=>this.handleHyperliquidGetLiquidations(r)}};async handleEvmTransaction(r){try{const e=await this.client.post("/v1/transactions/evm",r),t=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleSolanaTransaction(r){try{const e=await this.client.post("/v1/transactions/solana",r),t=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{success:!0,data:{internalTransactionId:e.internalTransactionId,txHash:t.txHash,transactionUrl:t.transactionUrl}}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async handleEvmSignMessage(r){try{return{success:!0,data:await this.client.post("/v1/messages/evm",{messageType:r.request.messageType,data:r.request.data,chainId:r.request.chainId})}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{};return e||t?{success:!1,error:e,errorMessage:t,errorDetails:s}:{success:!1,error:"SDK Error",errorMessage:r instanceof Error?r.message:"Unknown error",errorDetails:{}}}}async _updateJobStatus(r){try{return await this.client.post(`/v1/jobs/${r.jobId}/status`,r)}catch(r){return{status:400,message:`Failed to update job status: ${r instanceof Error?r.message:"Unknown error"}`}}}async handleSwidgeQuote(r){try{return{success:!0,data:await this.client.post("/v1/swidge/quote",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get swidge quote";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleSwidgeExecute(r){try{const e=await this.client.post("/v1/swidge/execute",r);if(Array.isArray(e))return e.map(r=>{const e="success"===r.status;return{success:e,data:r,error:e?void 0:r.error}});const t="success"===e.status;return{success:t,data:e,error:t?void 0:e.error}}catch(e){const t=e.error,s=e.errorMessage,o=e.errorDetails||{},a=e instanceof Error?e.message:"Failed to execute swidge swap";return Array.isArray(r)?[{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}]:{success:!1,error:t||"SDK Error",errorMessage:s||a,errorDetails:o}}}async handlePolymarketMarketOrder(r){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/market-order",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to execute polymarket market order";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handlePolymarketRedeemPositions(r){try{return{success:!0,data:await this.client.post("/v1/platforms/polymarket/redeem-positions",r)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to redeem polymarket positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleHyperliquidPlaceOrder(r){try{return await this.client.post("/v1/platforms/hyperliquid/order",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to place order";return{success:!1,error:e||t}}}async handleHyperliquidGetOrder(r){try{return await this.client.get(`/v1/platforms/hyperliquid/order/${r}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order";return{success:!1,error:e||t}}}async handleHyperliquidDeleteOrder(r,e){try{return await this.client.delete(`/v1/platforms/hyperliquid/order/${r}/${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to delete order";return{success:!1,error:e||t}}}async handleHyperliquidGetBalances(){try{return await this.client.get("/v1/platforms/hyperliquid/balances")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get balances";return{success:!1,error:e||t}}}async handleHyperliquidGetPositions(){try{return await this.client.get("/v1/platforms/hyperliquid/positions")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get positions";return{success:!1,error:e||t}}}async handleHyperliquidGetOpenOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get open orders";return{success:!1,error:e||t}}}async handleHyperliquidGetOrderFills(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/fill-history")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get order fills";return{success:!1,error:e||t}}}async handleHyperliquidGetHistoricalOrders(){try{return await this.client.get("/v1/platforms/hyperliquid/orders/historical")}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get historical orders";return{success:!1,error:e||t}}}async handleHyperliquidTransfer(r){try{return await this.client.post("/v1/platforms/hyperliquid/transfer",r)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to transfer";return{success:!1,error:e||t}}}async handleHyperliquidGetLiquidations(r){try{const e=r?`?startTime=${r}`:"";return await this.client.get(`/v1/platforms/hyperliquid/liquidations${e}`)}catch(r){const e=r.error,t=r instanceof Error?r.message:"Failed to get liquidations";return{success:!1,error:e||t}}}async handleMemorySet(r,e){try{return{success:!0,data:await this.client.post(`/v1/memory/${r}`,{value:e})}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to set memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryGet(r){try{return{success:!0,data:await this.client.get(`/v1/memory/${r}`)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to get memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryDelete(r){try{return{success:!0,data:await this.client.delete(`/v1/memory/${r}`)}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to delete memory";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async handleMemoryList(){try{return{success:!0,data:await this.client.get("/v1/memory/list")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to list memory keys";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async transactions(){try{return{success:!0,data:await this.client.get("/v1/transactions/ledger")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch transactions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}async getCurrentPositions(){try{return{success:!0,data:await this.client.get("/v1/positions/current")}}catch(r){const e=r.error,t=r.errorMessage,s=r.errorDetails||{},o=r instanceof Error?r.message:"Failed to fetch current positions";return{success:!1,error:e||"SDK Error",errorMessage:t||o,errorDetails:s}}}};import{existsSync as n,readFileSync as i}from"fs";import{join as c}from"path";import{zValidator as u}from"@hono/zod-validator";import{Hono as l}from"hono";import{cors as d}from"hono/cors";import*as h from"zod";var y=class{sessionId;sessionWalletAddress;currentPositions;t;constructor(r){this.sessionId=r.sessionId,this.sessionWalletAddress=r.sessionWalletAddress,this.currentPositions=r.currentPositions,this.t=new a({sessionId:r.sessionId,baseUrl:r.baseUrl,authorizationHeader:r.authorizationHeader})}async log(r,e){const{error:t=!1,debug:s=!1}=e||{};let o,a;const n=(r,e)=>{if("bigint"==typeof e)return e.toString();if("function"==typeof e)return`[Function: ${e.name||"anonymous"}]`;if(void 0===e)return"[undefined]";if(null===e)return null;if("object"==typeof e&&!Array.isArray(e)&&e.toString!==Object.prototype.toString)try{const r=e.toString();if("[object Object]"!==r)return r}catch(r){}return e};if("object"==typeof r&&null!==r?(o=JSON.stringify(r,n,2),a=JSON.stringify(r,n)):(o=String(r),a=String(r)),t?console.error(o):console.log(o),s)return{success:!0};const i=t?"error":"observe";try{const r=a.length>250?a.slice(0,250):a;return await this.t._sendLog([{type:i,shortMessage:r}]),{success:!0}}catch(r){const e=r instanceof Error?r.message:"Failed to send log";return console.error(`Failed to send log to backend: ${e}`),{success:!1,error:"Log Error",errorMessage:e,errorDetails:{message:e,type:r instanceof Error?r.constructor.name:"UnknownError"}}}}async signAndSend(r){return this.t.signAndSend(r)}async signMessage(r){return this.t.signMessage(r)}memory={set:async(r,e)=>this.t.memory.set(r,e),get:async r=>this.t.memory.get(r),delete:async r=>this.t.memory.delete(r),list:async()=>this.t.memory.list()};platforms={polymarket:{marketOrder:async r=>this.t.platforms.polymarket.marketOrder(r),redeemPositions:async r=>this.t.platforms.polymarket.redeemPositions(r)},hyperliquid:{placeOrder:async r=>this.t.platforms.hyperliquid.placeOrder(r),order:async r=>this.t.platforms.hyperliquid.order(r),deleteOrder:async(r,e)=>this.t.platforms.hyperliquid.deleteOrder(r,e),balances:async()=>this.t.platforms.hyperliquid.balances(),positions:async()=>this.t.platforms.hyperliquid.positions(),openOrders:async()=>this.t.platforms.hyperliquid.openOrders(),orderFills:async()=>this.t.platforms.hyperliquid.orderFills(),orders:async()=>this.t.platforms.hyperliquid.orders(),transfer:async r=>this.t.platforms.hyperliquid.transfer(r),liquidations:async r=>this.t.platforms.hyperliquid.liquidations(r)}};swidge={quote:async r=>this.t.swidge.quote(r),execute:function(r){return this.t.swidge.execute(r)}.bind(this)};async transactions(){return this.t.transactions()}async getCurrentPositions(){return this.t.getCurrentPositions()}},p=h.object({network:h.string(),assetAddress:h.string(),tokenId:h.string().nullable(),avgUnitCost:h.string(),currentQty:h.string()}),m=h.object({sessionId:h.number(),sessionWalletAddress:h.string(),jobId:h.string().optional(),currentPositions:h.array(p)}),g=(h.object({status:h.string()}),class{app;runFunction;stopFunction;healthCheckFunction=async()=>({status:"healthy",timestamp:(new Date).toISOString()});constructor(r){this.app=new l,this.runFunction=r.runFunction,this.stopFunction=r.stopFunction,this.app.use("*",d()),this.setupRoutes()}defaultStopFunction=async r=>{await r.log(`Agent stopped for session ${r.sessionId}`)};async executeWithJobTracking(r,e,t){let s,o=!1;try{const s=new y({sessionId:r.sessionId,sessionWalletAddress:r.sessionWalletAddress,currentPositions:r.currentPositions,authorizationHeader:t});await e(s),o=!0}catch(r){s=this.getErrorMessage(r),o=!1,console.error("Agent function error:",s)}finally{r.jobId&&await this.updateJobStatus(r.sessionId,r.jobId,o?"success":"failed",s,t)}}getErrorMessage(r){if(null==r)return"Unknown error";try{const e=r?.constructor?.name||"Error";let t="";t=r instanceof Error&&r.message||String(r),t=t.replace(/[^\x20-\x7E\n\t]/g,"");const s=`${e}: ${t}`;return s.length>1e3?`${s.substring(0,997)}...`:s}catch{return"Unknown error (message extraction failed)"}}async updateJobStatus(r,e,t,s,o){const n=new a({sessionId:r,authorizationHeader:o});for(let r=1;r<=3;r++)try{return void await n._updateJobStatus({jobId:e,status:t,errorMessage:s})}catch(e){console.error(`Status update attempt ${r}/3 failed:`,e),r<3&&await new Promise(e=>setTimeout(e,100*2**(r-1)))}if("failed"===t)try{return console.warn(`Issue updating job status to '${t}' with error message, attempting to update status without error message`),void await n._updateJobStatus({jobId:e,status:t,errorMessage:void 0})}catch(r){console.error(`CRITICAL: Failed to update job ${e} status. Likely API connectivity issue:`,r)}else console.error(`CRITICAL: Failed to update job ${e} status to success after 3 attempts`)}setupRoutes(){this.app.post("/run",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/execute",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization");return await this.executeWithJobTracking(e,this.runFunction,t),r.json({success:!0,message:"Execution completed"})}),this.app.post("/stop",u("json",m),async r=>{const e=r.req.valid("json"),t=r.req.header("Authorization"),s=this.stopFunction||this.defaultStopFunction;return await this.executeWithJobTracking(e,s,t),r.json({success:!0,message:"Stop completed"})}),this.app.get("/health",async r=>{try{const e=await this.healthCheckFunction();return r.json(e)}catch(e){return console.error("Agent health check error:",e),r.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const r=c(process.cwd(),"package.json");if(n(r)){const e=JSON.parse(i(r,"utf-8"));if(e.circuit?.port)return console.log("⚠️ Warning: circuit.port in package.json is deprecated. Use AGENT_PORT environment variable instead."),Number.parseInt(e.circuit.port,10)}}catch(r){console.log("Could not read package.json for port configuration")}return null}async run(r){if("undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare)return this.getExport();const e=globalThis.Bun?.env,t=process.env.AGENT_PORT||e?.AGENT_PORT,s=this.getPortFromPackageJson();let o=r;!o&&t&&(o=Number.parseInt(t,10)),!o&&s&&(o=s),o||(o=3e3),console.log("🔧 Agent configuration:"),console.log(` Explicit port parameter: ${r||"not set"}`),console.log(` process.env.AGENT_PORT: ${process.env.AGENT_PORT||"not set"}`),console.log(` Bun.env.AGENT_PORT: ${e?.AGENT_PORT||"not set"}`),console.log(` package.json circuit.port: ${s||"not set"} (deprecated)`),console.log(` Final port: ${o}`);try{const{serve:r}=await import("@hono/node-server");console.log(`🚀 Server is running on port ${o}`),console.log("📍 Available endpoints: GET /health, POST /run, POST /execute (backward compat), POST /stop"),r({fetch:this.app.fetch,port:o})}catch(r){console.error("Failed to start local server. @hono/node-server is not available."),console.error("For local development, install @hono/node-server: npm install @hono/node-server"),process.exit(1)}}getExport(){return{fetch:async(r,e,t)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(r,e,t))}}});import{z as f}from"zod";var w=f.templateLiteral(["ethereum:",f.coerce.number().int().nonnegative()]),v=f.union([f.literal("solana"),w]),E=f.object({address:f.string(),network:v}),b=(f.object({from:E,to:E,fromToken:f.string().optional(),toToken:f.string().optional(),amount:f.string(),slippage:f.string().optional()}),f.object({network:v,address:f.string(),token:f.string().nullable(),name:f.string().optional(),symbol:f.string().optional(),decimals:f.number().optional(),amount:f.string().optional(),minimumAmount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()})),T=f.object({usd:f.string().optional(),percentage:f.string().optional()}),k=f.object({name:f.string(),amount:f.string().optional(),amountFormatted:f.string().optional(),amountUsd:f.string().optional()}),D=f.object({programId:f.string(),keys:f.array(f.object({pubkey:f.string(),isSigner:f.boolean(),isWritable:f.boolean()})),data:f.union([f.string(),f.instanceof(Buffer)])}),F=f.object({type:f.literal("evm"),from:f.string().regex(/^0x[a-fA-F0-9]{40}$/),to:f.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:f.number(),value:f.number(),data:f.string().regex(/^0x[a-fA-F0-9]*$/),gas:f.number().nullish(),maxFeePerGas:f.number().nullish(),maxPriorityFeePerGas:f.number().nullish()}),S=f.object({type:f.literal("solana"),instructions:f.array(D),addressLookupTableAddresses:f.array(f.string())}),O=f.object({type:f.literal("transaction"),description:f.string(),transactionDetails:f.union([F,S]),metadata:f.record(f.string(),f.string())}),A=f.object({type:f.literal("signature"),description:f.string(),signatureData:f.string(),metadata:f.record(f.string(),f.string())}),M=f.discriminatedUnion("type",[O,A]),$=f.object({engine:f.literal("relay"),assetSend:b,assetReceive:b,priceImpact:T,fees:f.array(k),steps:f.array(M)}),q=f.object({network:f.string(),txs:f.array(f.string())}),P=f.object({status:f.union([f.literal("success"),f.literal("failure"),f.literal("refund"),f.literal("delayed")]),in:q,out:q,lastUpdated:f.number(),error:f.string().optional()}),U={FOUND:"QUOTE_FOUND",NO_QUOTE_PROVIDED:"No quote provided",WALLET_NOT_FOUND:"Wallet not found",WALLET_MISMATCH:"From wallet does not match session wallet",PRICE_IMPACT_TOO_HIGH:"Failed to get quote. Error: Price impact is too high",NO_ROUTES_FOUND:"Failed to get quote. Error: no routes found",AMOUNT_TOO_SMALL:"Failed to get quote. APIError: Swap output amount is too small to cover fees required to execute swap"},x=r=>f.object({success:f.boolean(),data:r.optional(),error:f.string().optional(),errorMessage:f.string().optional(),errorDetails:f.object({message:f.string().optional(),error:f.string().optional(),status:f.number().optional(),statusText:f.string().optional()}).optional()});x($),x(P);export{e as APIClient,g as Agent,y as AgentContext,a as AgentSdk,U as QUOTE_RESULT,o as getChainIdFromNetwork,t as isEthereumNetwork,s as isSolanaNetwork};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.2.3",
3
+ "version": "1.2.4",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",