@circuitorg/agent-sdk 1.1.4 → 1.1.7

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 +242 -2
  2. package/index.d.ts +340 -2
  3. package/index.js +1 -1
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -2,16 +2,17 @@
2
2
 
3
3
  > **Clean, type-safe TypeScript SDK for building cross-chain agents on the circuit platform**
4
4
 
5
- A TypeScript SDK for building automated agents to deploy on Circuit. Features a simple API surface with just **3 main methods** and full type safety.
5
+ A TypeScript SDK for building automated agents to deploy on Circuit. Features a simple API surface with just **2 core methods** plus **platform integrations** with full type safety.
6
6
 
7
7
  > **💡 Best used with [Circuit Agents CLI](https://github.com/circuitorg/agents-cli)** - Deploy, manage, and test your agents with ease
8
8
 
9
9
  ## ✨ Features
10
10
 
11
- - **🎯 Simple API**: Only 3 main methods - `sendLog()`, `signAndSend()`, and `swidge.*` (swap/bridge)
11
+ - **🎯 Simple API**: 2 core methods (`sendLog()`, `signAndSend()`) + platform integrations
12
12
  - **🔒 Type Safety**: Network parameter determines valid request shapes automatically
13
13
  - **🚀 Cross-Chain**: Unified interface for EVM and Solana networks
14
14
  - **🌉 Cross-Chain Swaps**: Built-in Swidge integration for seamless token swaps and bridges
15
+ - **📈 Polymarket Integration**: Trade prediction markets with `sdk.polymarket.*` methods
15
16
 
16
17
  ## 🚀 Quick Start
17
18
  ### Install the SDK
@@ -327,6 +328,245 @@ Pass the entire `quote.data` object returned from `quote()` - the SDK handles al
327
328
  - `"delayed"` - Transaction is taking longer than expected but still processing
328
329
 
329
330
 
331
+ ## 📈 Polymarket Prediction Markets
332
+
333
+ The SDK includes built-in Polymarket integration for trading prediction markets on Polygon.
334
+
335
+ ### 4. Polymarket Trading
336
+
337
+ #### Get Positions
338
+
339
+ Fetch all current positions for the session wallet:
340
+
341
+ ```typescript
342
+ const positions = await sdk.polymarket.positions();
343
+
344
+ if (positions.success && positions.data) {
345
+ console.log(`Total value: $${positions.data.totalValue}`);
346
+
347
+ for (const position of positions.data.positions) {
348
+ console.log(`${position.question} (${position.outcome})`);
349
+ console.log(` Shares: ${position.formattedShares}`);
350
+ console.log(` Value: $${position.valueUsd}`);
351
+ console.log(` P&L: $${position.pnlUsd} (${position.pnlPercent}%)`);
352
+ }
353
+ }
354
+ ```
355
+
356
+ #### Place Market Orders
357
+
358
+ Execute buy or sell market orders:
359
+
360
+ ```typescript
361
+ // Buy order - size is USD amount to spend
362
+ const buyOrder = await sdk.polymarket.marketOrder({
363
+ tokenId: "123456789...", // Market token ID
364
+ size: 10, // Spend $10 to buy shares
365
+ side: "BUY"
366
+ });
367
+
368
+ // Sell order - size is number of shares to sell
369
+ const sellOrder = await sdk.polymarket.marketOrder({
370
+ tokenId: "123456789...",
371
+ size: 5.5, // Sell 5.5 shares
372
+ side: "SELL"
373
+ });
374
+
375
+ if (buyOrder.success && buyOrder.data) {
376
+ console.log(`Order Success: ${buyOrder.data.success}`);
377
+ console.log(`Order ID: ${buyOrder.data.orderInfo.orderId}`);
378
+ console.log(`Filled at $${buyOrder.data.orderInfo.priceUsd} per share`);
379
+ console.log(`Total cost: $${buyOrder.data.orderInfo.totalPriceUsd}`);
380
+ }
381
+ ```
382
+
383
+ #### Redeem Positions
384
+
385
+ Claim winnings from settled positions:
386
+
387
+ ```typescript
388
+ // Redeem all redeemable positions
389
+ const redemption = await sdk.polymarket.redeemPositions();
390
+
391
+ if (redemption.success && redemption.data) {
392
+ for (const result of redemption.data) {
393
+ if (result.success) {
394
+ console.log(`✅ Redeemed: ${result.position.question}`);
395
+ console.log(` TX: ${result.transactionHash}`);
396
+ }
397
+ }
398
+ }
399
+
400
+ // Redeem specific positions by token IDs
401
+ const specificRedemption = await sdk.polymarket.redeemPositions({
402
+ tokenIds: ["123456", "789012"]
403
+ });
404
+ ```
405
+
406
+ ### Polymarket API Reference
407
+
408
+ #### `sdk.polymarket.positions(): Promise<PolymarketPositionsResponse>`
409
+
410
+ Get all current positions for the session wallet.
411
+
412
+ **Returns:**
413
+ ```typescript
414
+ {
415
+ success: boolean,
416
+ data?: {
417
+ totalValue: number,
418
+ positions: Array<{
419
+ contractAddress: string,
420
+ tokenId: string,
421
+ question: string,
422
+ outcome: string,
423
+ formattedShares: string,
424
+ shares: string,
425
+ valueUsd: string,
426
+ priceUsd: string,
427
+ averagePriceUsd: string,
428
+ pnlUsd: string,
429
+ pnlPercent: string,
430
+ isRedeemable: boolean,
431
+ endDate: string,
432
+ // ... additional fields
433
+ }>
434
+ },
435
+ error?: string,
436
+ errorDetails?: { message: string, status?: number, statusText?: string }
437
+ }
438
+ ```
439
+
440
+ #### `sdk.polymarket.marketOrder(request): Promise<PolymarketMarketOrderResponse>`
441
+
442
+ Place a buy or sell market order.
443
+
444
+ ⚠️ **Important**: The `size` parameter meaning differs by order side:
445
+ - **BUY**: `size` is the USD amount to spend (e.g., 10 = $10 worth of shares)
446
+ - **SELL**: `size` is the number of shares/tokens to sell (e.g., 10 = 10 shares)
447
+
448
+ **Parameters:**
449
+ ```typescript
450
+ {
451
+ tokenId: string, // Market token ID for the position
452
+ size: number, // For BUY: USD amount. For SELL: Number of shares
453
+ side: "BUY" | "SELL"
454
+ }
455
+ ```
456
+
457
+ **Returns:**
458
+ ```typescript
459
+ {
460
+ success: boolean,
461
+ data?: {
462
+ success: boolean, // Whether the order was successfully submitted
463
+ orderInfo: {
464
+ orderId: string,
465
+ side: string,
466
+ size: string,
467
+ priceUsd: string,
468
+ totalPriceUsd: string,
469
+ txHashes: string[]
470
+ }
471
+ },
472
+ error?: string,
473
+ errorDetails?: { message: string, status?: number, statusText?: string }
474
+ }
475
+ ```
476
+
477
+ #### `sdk.polymarket.redeemPositions(request?): Promise<PolymarketRedeemPositionsResponse>`
478
+
479
+ Redeem settled positions to claim winnings.
480
+
481
+ **Parameters (optional):**
482
+ ```typescript
483
+ {
484
+ tokenIds?: string[] // Specific token IDs to redeem (default: all redeemable positions)
485
+ }
486
+ ```
487
+
488
+ **Returns:**
489
+ ```typescript
490
+ {
491
+ success: boolean,
492
+ data?: Array<{
493
+ success: boolean,
494
+ position: { /* Full position details */ },
495
+ transactionHash: string | null
496
+ }>,
497
+ error?: string,
498
+ errorDetails?: { message: string, status?: number, statusText?: string }
499
+ }
500
+ ```
501
+
502
+ ### Complete Polymarket Example
503
+
504
+ ```typescript
505
+ const executionFunction: ExecutionFunctionContract = async (request) => {
506
+ const sdk = new AgentSdk({ sessionId: request.sessionId });
507
+
508
+ try {
509
+ // Get current positions
510
+ const positions = await sdk.polymarket.positions();
511
+
512
+ if (!positions.success || !positions.data) {
513
+ throw new Error(`Failed to get positions: ${positions.error}`);
514
+ }
515
+
516
+ // Find specific position
517
+ const targetPosition = positions.data.positions.find(
518
+ p => p.tokenId === "YOUR_TOKEN_ID"
519
+ );
520
+
521
+ if (targetPosition && Number(targetPosition.formattedShares) > 0) {
522
+ // Sell position
523
+ const sellOrder = await sdk.polymarket.marketOrder({
524
+ tokenId: targetPosition.tokenId,
525
+ size: Number(targetPosition.formattedShares),
526
+ side: "SELL"
527
+ });
528
+
529
+ if (sellOrder.success && sellOrder.data?.orderInfo) {
530
+ await sdk.sendLog({
531
+ type: "observe",
532
+ shortMessage: `Sold ${targetPosition.outcome} for $${sellOrder.data.orderInfo.totalPriceUsd}`
533
+ });
534
+ }
535
+ }
536
+
537
+ return { success: true };
538
+ } catch (error) {
539
+ await sdk.sendLog({
540
+ type: "error",
541
+ shortMessage: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
542
+ });
543
+ return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
544
+ }
545
+ };
546
+
547
+ const stopFunction: StopFunctionContract = async (request) => {
548
+ const sdk = new AgentSdk({ sessionId: request.sessionId });
549
+
550
+ try {
551
+ // Redeem all settled positions on stop
552
+ const redemption = await sdk.polymarket.redeemPositions();
553
+
554
+ if (redemption.success && redemption.data) {
555
+ const successful = redemption.data.filter(r => r.success);
556
+ await sdk.sendLog({
557
+ type: "observe",
558
+ shortMessage: `✅ Redeemed ${successful.length} positions`
559
+ });
560
+ }
561
+
562
+ return { success: true };
563
+ } catch (error) {
564
+ return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
565
+ }
566
+ };
567
+ ```
568
+
569
+
330
570
  ## 🔧 Examples
331
571
 
332
572
  ### Barebones Agent
package/index.d.ts CHANGED
@@ -66,7 +66,7 @@ declare const EIP712TypedDataSchema: z.ZodObject<{
66
66
  type: z.ZodString;
67
67
  }, z.core.$strip>>>;
68
68
  primaryType: z.ZodString;
69
- message: z.ZodRecord<z.ZodString, z.ZodAny>;
69
+ message: z.ZodRecord<z.ZodString, z.ZodUnknown>;
70
70
  }, z.core.$strip>;
71
71
  /**
72
72
  * EIP191 Message schema for simple message signing
@@ -380,6 +380,132 @@ type SwidgeQuoteResponse = z.infer<typeof SwidgeQuoteResponseWrapperSchema>;
380
380
  type SwidgeExecuteRequest = z.infer<typeof SwidgeExecuteRequestSchema>;
381
381
  type SwidgeExecuteResponse = z.infer<typeof SwidgeExecuteResponseWrapperSchema>;
382
382
 
383
+ declare const PolymarketPositionSchema: z.ZodObject<{
384
+ contractAddress: z.ZodString;
385
+ tokenId: z.ZodNullable<z.ZodString>;
386
+ decimals: z.ZodNumber;
387
+ conditionId: z.ZodString;
388
+ formattedShares: z.ZodString;
389
+ shares: z.ZodString;
390
+ valueUsd: z.ZodString;
391
+ question: z.ZodString;
392
+ outcome: z.ZodString;
393
+ priceUsd: z.ZodString;
394
+ averagePriceUsd: z.ZodString;
395
+ isRedeemable: z.ZodBoolean;
396
+ imageUrl: z.ZodString;
397
+ initialValue: z.ZodString;
398
+ pnlUsd: z.ZodString;
399
+ pnlPercent: z.ZodString;
400
+ pnlRealizedUsd: z.ZodString;
401
+ pnlRealizedPercent: z.ZodString;
402
+ endDate: z.ZodString;
403
+ }, z.core.$strip>;
404
+ declare const PolymarketMarketOrderRequestSchema: z.ZodObject<{
405
+ tokenId: z.ZodString;
406
+ size: z.ZodNumber;
407
+ side: z.ZodEnum<{
408
+ BUY: "BUY";
409
+ SELL: "SELL";
410
+ }>;
411
+ }, z.core.$strip>;
412
+ declare const PolymarketRedeemPositionsRequestSchema: z.ZodObject<{
413
+ tokenIds: z.ZodDefault<z.ZodOptional<z.ZodArray<z.ZodString>>>;
414
+ }, z.core.$strip>;
415
+ declare const PolymarketPositionsResponseSchema: z.ZodObject<{
416
+ success: z.ZodBoolean;
417
+ data: z.ZodOptional<z.ZodObject<{
418
+ totalValue: z.ZodNumber;
419
+ positions: z.ZodArray<z.ZodObject<{
420
+ contractAddress: z.ZodString;
421
+ tokenId: z.ZodNullable<z.ZodString>;
422
+ decimals: z.ZodNumber;
423
+ conditionId: z.ZodString;
424
+ formattedShares: z.ZodString;
425
+ shares: z.ZodString;
426
+ valueUsd: z.ZodString;
427
+ question: z.ZodString;
428
+ outcome: z.ZodString;
429
+ priceUsd: z.ZodString;
430
+ averagePriceUsd: z.ZodString;
431
+ isRedeemable: z.ZodBoolean;
432
+ imageUrl: z.ZodString;
433
+ initialValue: z.ZodString;
434
+ pnlUsd: z.ZodString;
435
+ pnlPercent: z.ZodString;
436
+ pnlRealizedUsd: z.ZodString;
437
+ pnlRealizedPercent: z.ZodString;
438
+ endDate: z.ZodString;
439
+ }, z.core.$strip>>;
440
+ }, z.core.$strip>>;
441
+ error: z.ZodOptional<z.ZodString>;
442
+ errorDetails: z.ZodOptional<z.ZodObject<{
443
+ message: z.ZodString;
444
+ status: z.ZodOptional<z.ZodNumber>;
445
+ statusText: z.ZodOptional<z.ZodString>;
446
+ }, z.core.$strip>>;
447
+ }, z.core.$strip>;
448
+ declare const PolymarketMarketOrderResponseSchema: z.ZodObject<{
449
+ success: z.ZodBoolean;
450
+ data: z.ZodOptional<z.ZodObject<{
451
+ success: z.ZodBoolean;
452
+ orderInfo: z.ZodObject<{
453
+ orderId: z.ZodString;
454
+ side: z.ZodString;
455
+ size: z.ZodString;
456
+ priceUsd: z.ZodString;
457
+ totalPriceUsd: z.ZodString;
458
+ txHashes: z.ZodArray<z.ZodString>;
459
+ }, z.core.$strip>;
460
+ }, z.core.$strip>>;
461
+ error: z.ZodOptional<z.ZodString>;
462
+ errorDetails: z.ZodOptional<z.ZodObject<{
463
+ message: z.ZodString;
464
+ status: z.ZodOptional<z.ZodNumber>;
465
+ statusText: z.ZodOptional<z.ZodString>;
466
+ }, z.core.$strip>>;
467
+ }, z.core.$strip>;
468
+ declare const PolymarketRedeemPositionsResponseSchema: z.ZodObject<{
469
+ success: z.ZodBoolean;
470
+ data: z.ZodOptional<z.ZodArray<z.ZodObject<{
471
+ success: z.ZodBoolean;
472
+ position: z.ZodObject<{
473
+ contractAddress: z.ZodString;
474
+ tokenId: z.ZodNullable<z.ZodString>;
475
+ decimals: z.ZodNumber;
476
+ conditionId: z.ZodString;
477
+ formattedShares: z.ZodString;
478
+ shares: z.ZodString;
479
+ valueUsd: z.ZodString;
480
+ question: z.ZodString;
481
+ outcome: z.ZodString;
482
+ priceUsd: z.ZodString;
483
+ averagePriceUsd: z.ZodString;
484
+ isRedeemable: z.ZodBoolean;
485
+ imageUrl: z.ZodString;
486
+ initialValue: z.ZodString;
487
+ pnlUsd: z.ZodString;
488
+ pnlPercent: z.ZodString;
489
+ pnlRealizedUsd: z.ZodString;
490
+ pnlRealizedPercent: z.ZodString;
491
+ endDate: z.ZodString;
492
+ }, z.core.$strip>;
493
+ transactionHash: z.ZodNullable<z.ZodString>;
494
+ }, z.core.$strip>>>;
495
+ error: z.ZodOptional<z.ZodString>;
496
+ errorDetails: z.ZodOptional<z.ZodObject<{
497
+ message: z.ZodString;
498
+ status: z.ZodOptional<z.ZodNumber>;
499
+ statusText: z.ZodOptional<z.ZodString>;
500
+ }, z.core.$strip>>;
501
+ }, z.core.$strip>;
502
+ type PolymarketPosition = z.infer<typeof PolymarketPositionSchema>;
503
+ type PolymarketMarketOrderRequest = z.infer<typeof PolymarketMarketOrderRequestSchema>;
504
+ type PolymarketRedeemPositionsRequest = z.infer<typeof PolymarketRedeemPositionsRequestSchema>;
505
+ type PolymarketPositionsResponse = z.infer<typeof PolymarketPositionsResponseSchema>;
506
+ type PolymarketMarketOrderResponse = z.infer<typeof PolymarketMarketOrderResponseSchema>;
507
+ type PolymarketRedeemPositionsResponse = z.infer<typeof PolymarketRedeemPositionsResponseSchema>;
508
+
383
509
  /**
384
510
  * Main AgentSdk class with simplified API surface
385
511
  */
@@ -649,6 +775,208 @@ declare class AgentSdk {
649
775
  */
650
776
  execute: (executeQuote: SwidgeExecuteRequest) => Promise<SwidgeExecuteResponse>;
651
777
  };
778
+ /**
779
+ * 📈 Polymarket: Trade prediction markets seamlessly
780
+ *
781
+ * Access Polymarket positions, execute market orders, and redeem positions using your
782
+ * session wallet. All operations are policy-checked and signed automatically.
783
+ */
784
+ readonly polymarket: {
785
+ /**
786
+ * Get current positions on Polymarket
787
+ *
788
+ * Fetches all open positions for the session wallet, including value, PNL, and market details.
789
+ *
790
+ * @returns Wrapped response with positions array and total value
791
+ * @example
792
+ * // Usage
793
+ * const result = await sdk.polymarket.positions();
794
+ *
795
+ * if (result.success && result.data) {
796
+ * console.log(`Total portfolio value: $${result.data.totalValue}`);
797
+ * result.data.positions.forEach(pos => {
798
+ * console.log(`${pos.question} - ${pos.outcome}: $${pos.valueUsd} (PNL: ${pos.pnlUsd})`);
799
+ * });
800
+ * } else {
801
+ * console.log(`Error: ${result.error}`);
802
+ * }
803
+ *
804
+ * // Input: None (GET request)
805
+ *
806
+ * // Output showcase (success case):
807
+ * {
808
+ * success: true,
809
+ * data: {
810
+ * totalValue: 150.75,
811
+ * positions: [
812
+ * {
813
+ * contractAddress: "0x...",
814
+ * tokenId: "123456",
815
+ * decimals: 6,
816
+ * conditionId: "0x...",
817
+ * formattedShares: "10.0",
818
+ * shares: "10000000",
819
+ * valueUsd: "10.5",
820
+ * question: "Will event X happen?",
821
+ * outcome: "Yes",
822
+ * priceUsd: "1.05",
823
+ * averagePriceUsd: "0.95",
824
+ * isRedeemable: false,
825
+ * imageUrl: "https://...",
826
+ * initialValue: "9.5",
827
+ * pnlUsd: "1.0",
828
+ * pnlPercent: "10.53",
829
+ * pnlRealizedUsd: "0",
830
+ * pnlRealizedPercent: "0",
831
+ * endDate: "2024-12-31"
832
+ * },
833
+ * // ... more positions
834
+ * ]
835
+ * }
836
+ * }
837
+ *
838
+ * // Error case:
839
+ * {
840
+ * success: false,
841
+ * error: "Could not get positions",
842
+ * errorDetails: { message: "Wallet not found", status: 400 }
843
+ * }
844
+ */
845
+ positions: () => Promise<PolymarketPositionsResponse>;
846
+ /**
847
+ * Execute a market order on Polymarket
848
+ *
849
+ * Places a buy or sell market order for the specified token and size. Handles approvals,
850
+ * signing, and submission automatically.
851
+ *
852
+ * ⚠️ **Important**: The `size` parameter meaning differs by order side:
853
+ * - **BUY**: `size` is the USD amount to spend (e.g., 10 = $10 worth of shares)
854
+ * - **SELL**: `size` is the number of shares/tokens to sell (e.g., 10 = 10 shares)
855
+ *
856
+ * @param request Order parameters
857
+ * @param request.tokenId Market token ID for the position
858
+ * @param request.size For BUY: USD amount to spend. For SELL: Number of shares to sell
859
+ * @param request.side "BUY" or "SELL"
860
+ * @returns Wrapped response with order details and submission result
861
+ * @example
862
+ * // BUY order - size is USD amount
863
+ * const buyResult = await sdk.polymarket.marketOrder({
864
+ * tokenId: "123456",
865
+ * size: 10, // Spend $10 to buy shares
866
+ * side: "BUY"
867
+ * });
868
+ *
869
+ * // SELL order - size is number of shares
870
+ * const sellResult = await sdk.polymarket.marketOrder({
871
+ * tokenId: "123456",
872
+ * size: 5, // Sell 5 shares
873
+ * side: "SELL"
874
+ * });
875
+ *
876
+ * if (buyResult.success && buyResult.data) {
877
+ * console.log(`Order ID: ${buyResult.data.submitOrder.orderId}`);
878
+ * console.log(`Success: ${buyResult.data.submitOrder.success}`);
879
+ * } else {
880
+ * console.log(`Error: ${buyResult.error}`);
881
+ * }
882
+ *
883
+ * // Input showcase:
884
+ * {
885
+ * tokenId: "123456", // Market token ID
886
+ * size: 10, // BUY: USD amount ($10) | SELL: Number of shares (10 shares)
887
+ * side: "BUY" // or "SELL"
888
+ * }
889
+ *
890
+ * // Output showcase (success case):
891
+ * {
892
+ * success: true,
893
+ * data: {
894
+ * order: {
895
+ * eip712Message: {
896
+ * // Typed data for signing (domain, types, message)
897
+ * },
898
+ * order: {
899
+ * salt: "123456789",
900
+ * maker: "0x...",
901
+ * signer: "0x...",
902
+ * taker: "0x...",
903
+ * tokenId: "123456",
904
+ * makerAmount: "105000000", // USD amount in USDC decimals
905
+ * takerAmount: "10000000", // Shares in decimals
906
+ * expiration: "0",
907
+ * nonce: "0",
908
+ * feeRateBps: "0",
909
+ * side: 0, // 0 = BUY, 1 = SELL
910
+ * signatureType: 0 // 0 = EIP712
911
+ * }
912
+ * },
913
+ * submitOrder: {
914
+ * orderId: "abc123",
915
+ * success: true,
916
+ * errorMessage: ""
917
+ * }
918
+ * }
919
+ * }
920
+ *
921
+ * // Error case:
922
+ * {
923
+ * success: false,
924
+ * error: "Could not get order",
925
+ * errorDetails: { message: "Invalid request", status: 400 }
926
+ * }
927
+ */
928
+ marketOrder: (request: PolymarketMarketOrderRequest) => Promise<PolymarketMarketOrderResponse>;
929
+ /**
930
+ * Redeem settled positions on Polymarket
931
+ *
932
+ * Redeems one or all redeemable positions, claiming winnings. Handles multiple transactions if needed.
933
+ *
934
+ * @param request Redemption parameters (omit to redeem all, or pass tokenIds for specific positions)
935
+ * @returns Wrapped response with per-position redemption results
936
+ * @example
937
+ * // Redeem all positions (no arguments - default behavior)
938
+ * const allResult = await sdk.polymarket.redeemPositions();
939
+ *
940
+ * // Redeem specific positions
941
+ * const specificResult = await sdk.polymarket.redeemPositions({ tokenIds: ["123456", "789012"] });
942
+ *
943
+ * if (result.success && result.data) {
944
+ * result.data.forEach(tx => {
945
+ * if (tx.success) {
946
+ * console.log(`Redeemed ${tx.position.question}: Tx ${tx.transactionHash}`);
947
+ * }
948
+ * });
949
+ * }
950
+ *
951
+ * // Input showcase:
952
+ * // No arguments - redeem all positions (default)
953
+ * // or
954
+ * { tokenIds: ["123456", "789012"] } // Redeem specific positions
955
+ *
956
+ * // Output showcase (success case):
957
+ * {
958
+ * success: true,
959
+ * data: [
960
+ * {
961
+ * success: true,
962
+ * position: {
963
+ * // Full position details as in positions response
964
+ * },
965
+ * transactionHash: "0xabc123..."
966
+ * },
967
+ * // ... more redemptions
968
+ * ]
969
+ * }
970
+ *
971
+ * // Error case:
972
+ * {
973
+ * success: false,
974
+ * error: "Could not get positions",
975
+ * errorDetails: { message: "No redeemable positions", status: 404 }
976
+ * }
977
+ */
978
+ redeemPositions: (request?: PolymarketRedeemPositionsRequest) => Promise<PolymarketRedeemPositionsResponse>;
979
+ };
652
980
  /**
653
981
  * Handle EVM transaction signing and broadcasting
654
982
  */
@@ -680,6 +1008,9 @@ declare class AgentSdk {
680
1008
  * Handle swidge execute requests
681
1009
  */
682
1010
  private handleSwidgeExecute;
1011
+ private handlePolymarketPositions;
1012
+ private handlePolymarketMarketOrder;
1013
+ private handlePolymarketRedeemPositions;
683
1014
  }
684
1015
 
685
1016
  /**
@@ -748,6 +1079,13 @@ declare const AgentRequestSchema: z.ZodObject<{
748
1079
  sessionId: z.ZodNumber;
749
1080
  sessionWalletAddress: z.ZodString;
750
1081
  jobId: z.ZodOptional<z.ZodString>;
1082
+ currentPositions: z.ZodOptional<z.ZodArray<z.ZodObject<{
1083
+ network: z.ZodString;
1084
+ assetAddress: z.ZodString;
1085
+ tokenId: z.ZodNullable<z.ZodString>;
1086
+ avgUnitCost: z.ZodString;
1087
+ currentQty: z.ZodString;
1088
+ }, z.core.$strip>>>;
751
1089
  otherParameters: z.ZodOptional<z.ZodObject<{}, z.core.$strip>>;
752
1090
  }, z.core.$strip>;
753
1091
  /**
@@ -954,4 +1292,4 @@ declare function isSolanaNetwork(network: Network): network is "solana";
954
1292
  */
955
1293
  declare function getChainIdFromNetwork(network: `ethereum:${number}`): number;
956
1294
 
957
- export { APIClient, Agent, AgentSdk, type ExecutionFunctionContract, type Network, QUOTE_RESULT, type SDKConfig, type SignAndSendRequest, type SignAndSendResponse, type SignMessageRequest, type SignMessageResponse, type StopFunctionContract, type SwidgeExecuteResponse, type SwidgeQuoteRequest, type SwidgeQuoteResponse, type SwidgeQuoteResult, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork };
1295
+ export { APIClient, Agent, AgentSdk, type ExecutionFunctionContract, type Network, type PolymarketMarketOrderRequest, type PolymarketMarketOrderResponse, type PolymarketPosition, type PolymarketPositionsResponse, 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, getChainIdFromNetwork, isEthereumNetwork, isSolanaNetwork };
package/index.js CHANGED
@@ -1 +1 @@
1
- var __getOwnPropNames=Object.getOwnPropertyNames,__require=(t=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(t,{get:(t,e)=>("undefined"!=typeof require?require:t)[e]}):t)(function(t){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),__commonJS=(t,e)=>function(){return e||(0,t[__getOwnPropNames(t)[0]])((e={exports:{}}).exports,e),e.exports},require_auth_loader=__commonJS({"src/utils/auth-loader.cjs"(exports,module){function loadAuthFromFileSystem(){try{if("undefined"==typeof process)return;const fs=eval("require")("fs"),path=eval("require")("path"),os=eval("require")("os"),homeDir=os.homedir();let authPath=path.join(homeDir,".config","circuit","auth.json");if(!fs.existsSync(authPath)&&(authPath=path.join(homeDir,".circuit","auth.json"),!fs.existsSync(authPath)))return;const authContent=fs.readFileSync(authPath,"utf-8");return JSON.parse(authContent)}catch(t){return}}module.exports={loadAuthFromFileSystem:loadAuthFromFileSystem}}}),API_BASE_URL_LOCAL="https://agents.circuit.org",APIClient=class{config;baseUrl;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){let t=!1;return this.isCloudflareWorker()&&(void 0!==globalThis.AGENTS_TO_API_PROXY||void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)&&(t=!0),this.config.verbose,t}constructor(t){this.config=t,this.baseUrl=t.baseUrl||API_BASE_URL_LOCAL}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 t={};t["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(t["X-Agent-Slug"]=e),!this.hasServiceBinding())try{const e=this.loadAuthConfig();e?.sessionToken&&(t.Authorization=`Bearer ${e.sessionToken}`)}catch(t){}return t}loadAuthConfig(){try{const{loadAuthFromFileSystem:t}=require_auth_loader();return t()}catch(t){this.config.verbose}}logging(t,e){this.config.verbose}sanitizeHeaders(t){const e={},s=new Set(["report-to","server-timing","server"]),r=t&&"object"==typeof t?t:{};for(const[t,a]of Object.entries(r)){if("string"!=typeof a)continue;const r=t.toLowerCase();s.has(r)||(e[t]="authorization"===r?a.startsWith("Bearer ")?`Bearer ${a.slice(7,14)}***`:"***":a)}return e}async makeRequest(t,e={}){const s={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let r;if(this.logging("=== REQUEST DETAILS ==="),this.logging("Endpoint:",t),this.logging("Method:",e.method||"GET"),this.logging("Headers:",this.sanitizeHeaders(s)),this.logging("Body:",e.body),this.logging("Session ID:",this.config.sessionId),this.logging("Agent Slug:",this.getAgentSlug()||"not set"),this.logging("Using Service Binding:",this.hasServiceBinding()),this.logging("====================="),this.hasServiceBinding()){let a;if(void 0!==globalThis.AGENTS_TO_API_PROXY)a=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");a=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}this.logging("Using service binding AGENTS_TO_API_PROXY"),this.logging("Service binding type:",typeof a);const i={...e,headers:s},o=`https://agents-to-api-proxy.circuit-0bc.workers.dev${t}`;r=await a.fetch(o,i)}else{this.logging("Using HTTP fallback to:",this.baseUrl);const a=`${this.baseUrl}${t}`,i={...e,headers:s};r=await fetch(a,i)}if(this.logging("=== RESPONSE DETAILS ==="),this.logging("Status:",r.status),this.logging("Status Text:",r.statusText),this.logging("Response Headers:",this.sanitizeHeaders(Object.fromEntries(r.headers.entries()))),this.logging("======================"),!r.ok){const t=await r.json().catch(()=>({}));throw this.logging("=== ERROR RESPONSE ==="),this.logging("Error Data:",t),this.logging("===================="),new Error(t.message||`HTTP ${r.status}: ${r.statusText}`)}const a=await r.json();return this.logging("=== SUCCESS RESPONSE ==="),this.logging("Response Data:",a),this.logging("======================"),a}async get(t){return this.makeRequest(t,{method:"GET"})}async post(t,e){return this.makeRequest(t,{method:"POST",body:e?JSON.stringify(e):void 0})}};function isEthereumNetwork(t){return t.startsWith("ethereum:")}function isSolanaNetwork(t){return"solana"===t}function getChainIdFromNetwork(t){return Number(t.split(":")[1])}var AgentSdk=class{client;config;constructor(t){this.config=t,this.client=new APIClient(t)}logging(t,e){this.config.verbose}async sendLog(t){this.logging("=== ADD MESSAGE ==="),this.logging("Message:",t),this.logging("===================");try{await this._sendLog([t])}catch(t){this.logging("=== SEND LOG ERROR ==="),this.logging("Error:",t),this.logging("======================")}}async signAndSend(t){this.logging("=== SIGN AND SEND ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("====================");try{if(this.config.testing)return{success:!0,internalTransactionId:123,txHash:isEthereumNetwork(t.network)?"0xTEST":"TEST_SOL_TX",transactionUrl:void 0};if(isEthereumNetwork(t.network)){const e=getChainIdFromNetwork(t.network);if("toAddress"in t.request)return await this.handleEvmTransaction({chainId:e,toAddress:t.request.toAddress,data:t.request.data,valueWei:t.request.value,message:t.message})}return isSolanaNetwork(t.network)&&"hexTransaction"in t.request?await this.handleSolanaTransaction({hexTransaction:t.request.hexTransaction,message:t.message}):{success:!1,error:`Unsupported network: ${t.network}`,errorDetails:{message:`Unsupported network: ${t.network}`}}}catch(t){return this.logging("=== SIGN AND SEND ERROR ==="),this.logging("Error:",t),this.logging("==========================="),{success:!1,error:t instanceof Error?t.message:"Unknown error",errorDetails:{message:t instanceof Error?t.message:"Unknown error"}}}}async signMessage(t){this.logging("=== SIGN MESSAGE ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("====================");try{return this.config.testing?{v:27,r:"0xTEST_R",s:"0xTEST_S",formattedSignature:"0xTEST_FORMATTED",type:"evm"}:isEthereumNetwork(t.network)?await this.handleEvmSignMessage(t):{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}catch(t){return this.logging("=== SIGN MESSAGE ERROR ==="),this.logging("Error:",t),this.logging("=========================="),{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}}swidge={quote:async t=>this.handleSwidgeQuote(t),execute:async t=>this.handleSwidgeExecute(t)};async handleEvmTransaction(t){try{const e=await this.client.post("/v1/transactions/evm",t),s=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{success:!0,internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}catch(t){this.logging("=== EVM TRANSACTION ERROR ==="),this.logging("Error:",t),this.logging("=============================");let e,s,r,a="Unknown error";if(t instanceof Error){a=t.message;const i=t.message.match(/HTTP (\d+): (.+)/);i&&(e=Number.parseInt(i[1]),s=i[2]),t.message.includes("Failed to estimate gas")&&(r=t.message)}return{success:!1,error:a,errorDetails:{message:r||a,status:e,statusText:s}}}}async handleSolanaTransaction(t){try{const e=await this.client.post("/v1/transactions/solana",t),s=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{success:!0,internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}catch(t){this.logging("=== SOLANA TRANSACTION ERROR ==="),this.logging("Error:",t),this.logging("================================");let e,s,r="Unknown error";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handleEvmSignMessage(t){try{return await this.client.post("/v1/messages/evm",{messageType:t.request.messageType,data:t.request.data,chainId:t.request.chainId})}catch(t){return this.logging("=== EVM SIGN MESSAGE ERROR ==="),this.logging("Error:",t),this.logging("=============================="),{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}}async _sendLog(t){return this.config.testing?{status:200,message:"Logs added successfully (TESTING)"}:this.client.post("/v1/logs",t)}async _updateJobStatus(t){if(this.logging("UPDATE_JOB_STATUS",t),this.config.testing)return{status:200,message:"Job status updated successfully (TESTING)"};try{return await this.client.post(`/v1/jobs/${t.jobId}/status`,t)}catch(t){return this.logging("=== UPDATE JOB STATUS ERROR ==="),this.logging("Error:",t),this.logging("==============================="),{status:400,message:`Failed to update job status: ${t instanceof Error?t.message:"Unknown error"}`}}}async handleSwidgeQuote(t){this.logging("=== SWIDGE QUOTE ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("===================");try{return this.config.testing?{success:!0,data:{engine:"relay",assetSend:{network:t.from.network,address:t.from.address,token:t.fromToken||null,amount:t.amount,amountFormatted:"1.0",amountUsd:"100.00"},assetReceive:{network:t.to.network,address:t.to.address,token:t.toToken||null,amount:"950000000000000000",amountFormatted:"0.95",amountUsd:"95.00"},priceImpact:{percentage:"0.5",usd:"5.00"},fees:[{name:"gas",amount:"21000000000000000",amountFormatted:"0.021",amountUsd:"2.10"}],steps:[{type:"transaction",description:"Test swap transaction",transactionDetails:{type:"evm",from:"0xtest",to:"0xtest",chainId:1,value:0,data:"0x",gas:21e3,maxFeePerGas:2e10,maxPriorityFeePerGas:1e9},metadata:{requestId:"test-request-id"}}]}}:{success:!0,data:await this.client.post("/v1/swidge/quote",t)}}catch(t){this.logging("=== SWIDGE QUOTE ERROR ==="),this.logging("Error:",t),this.logging("=========================");let e,s,r="Failed to get swidge quote";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handleSwidgeExecute(t){this.logging("=== SWIDGE EXECUTE ==="),this.logging("Quote:",t),this.logging("Testing mode:",this.config.testing),this.logging("=====================");try{if(this.config.testing)return{success:!0,data:{status:"success",in:{network:t.assetSend.network,txs:["0xtest_in_tx"]},out:{network:t.assetReceive.network,txs:["0xtest_out_tx"]},lastUpdated:Date.now()}};this.logging("Making execute request to /v1/swidge/execute");const e=await this.client.post("/v1/swidge/execute",t);return this.logging("Execute response received:",JSON.stringify(e,null,2)),{success:!0,data:e}}catch(t){this.logging("=== SWIDGE EXECUTE ERROR ==="),this.logging("Error:",t),this.logging("============================");let e,s,r="Failed to execute swidge swap";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}};import{zValidator}from"@hono/zod-validator";import{Hono}from"hono";import{cors}from"hono/cors";import{z}from"zod";var AgentRequestSchema=z.object({sessionId:z.number(),sessionWalletAddress:z.string(),jobId:z.string().optional(),otherParameters:z.object().optional()}),AgentResponseSchema=z.object({success:z.boolean(),error:z.string().optional(),message:z.string().optional()}),HealthResponseSchema=z.object({status:z.string()}),Agent=class{app;executionFunction;stopFunction;healthCheckFunction;constructor(t){this.app=new Hono,this.executionFunction=t.executionFunction,this.stopFunction=t.stopFunction,this.healthCheckFunction=t.healthCheckFunction||(async()=>({status:"healthy"})),this.app.use("*",cors()),this.setupRoutes()}defaultStopFunction=async t=>({success:!0,message:`Agent stopped for session ${t.sessionId}`});async executeWithJobTracking(t,e){try{const s=await e(t);if(t.jobId&&s.success)try{await this.updateJobStatus(t.sessionId,t.jobId,"success")}catch(t){}else if(t.jobId&&!s.success)try{const e=s.error||s.message||"Function returned failure";await this.updateJobStatus(t.sessionId,t.jobId,"failed",e)}catch(t){}return s}catch(e){if(t.jobId)try{const s=e instanceof Error?e.message:"Unknown error";await this.updateJobStatus(t.sessionId,t.jobId,"failed",s)}catch(t){}return{success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Function execution failed"}}}async updateJobStatus(t,e,s,r){try{const a=new AgentSdk({sessionId:t}),i={jobId:e,status:s,...r&&{errorMessage:r}};await a._updateJobStatus(i)}catch(t){}}setupRoutes(){this.app.post("/execute",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await this.executeWithJobTracking(e,this.executionFunction);return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Execution failed"},500)}}),this.app.post("/stop",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=this.stopFunction||this.defaultStopFunction,r=await this.executeWithJobTracking(e,s);return t.json(r)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Stop operation failed"},500)}}),this.app.get("/health",async t=>{try{const e=await(this.healthCheckFunction?.());return t.json(e)}catch(e){return t.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const t=__require("fs"),e=__require("path").join(process.cwd(),"package.json");if(t.existsSync(e)){const s=JSON.parse(t.readFileSync(e,"utf-8"));if(s.circuit?.port)return Number.parseInt(s.circuit.port,10)}}catch(t){}return null}run(port){const isCloudflareWorker="undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare;if(isCloudflareWorker)return this.getWorkerExport();const bunEnv=globalThis.Bun?.env,envPort=process.env.AGENT_PORT||bunEnv?.AGENT_PORT,packageJsonPort=this.getPortFromPackageJson();let finalPort=port;!finalPort&&envPort&&(finalPort=Number.parseInt(envPort,10)),!finalPort&&packageJsonPort&&(finalPort=packageJsonPort),finalPort||(finalPort=3e3);try{const req=eval("require"),{serve:serve}=req("@hono/node-server");serve({fetch:this.app.fetch,port:finalPort})}catch(t){process.exit(1)}}getWorkerExport(){return{fetch:async(t,e,s)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(t,e,s))}}};function createAgentHandler(t,e,s){return new Agent({executionFunction:t,stopFunction:e,healthCheckFunction:s})}import{z as z2}from"zod";var zEthereumNetwork=z2.templateLiteral(["ethereum:",z2.coerce.number().int().nonnegative()]),SwidgeNetworkSchema=z2.union([z2.literal("solana"),zEthereumNetwork]),SwidgeWalletSchema=z2.object({address:z2.string(),network:SwidgeNetworkSchema}),SwidgeQuoteRequestSchema=z2.object({from:SwidgeWalletSchema,to:SwidgeWalletSchema,fromToken:z2.string().optional(),toToken:z2.string().optional(),amount:z2.string(),priceImpact:z2.string().optional(),slippage:z2.string().optional()}),SwidgeQuoteAssetSchema=z2.object({network:SwidgeNetworkSchema,address:z2.string(),token:z2.string().nullable(),name:z2.string().optional(),symbol:z2.string().optional(),decimals:z2.number().optional(),amount:z2.string().optional(),minimumAmount:z2.string().optional(),amountFormatted:z2.string().optional(),amountUsd:z2.string().optional()}),SwidgePriceImpactSchema=z2.object({usd:z2.string().optional(),percentage:z2.string().optional()}),SwidgeFeeSchema=z2.object({name:z2.string(),amount:z2.string().optional(),amountFormatted:z2.string().optional(),amountUsd:z2.string().optional()}),SwidgeSolanaInstructionSchema=z2.object({programId:z2.string(),keys:z2.array(z2.object({pubkey:z2.string(),isSigner:z2.boolean(),isWritable:z2.boolean()})),data:z2.union([z2.string(),z2.instanceof(Buffer)])}),SwidgeEvmTransactionDetailsSchema=z2.object({type:z2.literal("evm"),from:z2.string().regex(/^0x[a-fA-F0-9]{40}$/),to:z2.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:z2.number(),value:z2.number(),data:z2.string().regex(/^0x[a-fA-F0-9]*$/),gas:z2.number().optional(),maxFeePerGas:z2.number().optional(),maxPriorityFeePerGas:z2.number().optional()}),SwidgeSolanaTransactionDetailsSchema=z2.object({type:z2.literal("solana"),instructions:z2.array(SwidgeSolanaInstructionSchema),addressLookupTableAddresses:z2.array(z2.string())}),zTransactionStep=z2.object({type:z2.literal("transaction"),description:z2.string(),transactionDetails:z2.union([SwidgeEvmTransactionDetailsSchema,SwidgeSolanaTransactionDetailsSchema]),metadata:z2.record(z2.string(),z2.string())}),zUnsignedSignatureStep=z2.object({type:z2.literal("signature"),description:z2.string(),signatureData:z2.string(),metadata:z2.record(z2.string(),z2.string())}),SwidgeUnsignedStepSchema=z2.discriminatedUnion("type",[zTransactionStep,zUnsignedSignatureStep]),SwidgeQuoteDataSchema=z2.object({engine:z2.literal("relay"),assetSend:SwidgeQuoteAssetSchema,assetReceive:SwidgeQuoteAssetSchema,priceImpact:SwidgePriceImpactSchema,fees:z2.array(SwidgeFeeSchema),steps:z2.array(SwidgeUnsignedStepSchema)}),SwidgeStatusInfoSchema=z2.object({network:z2.string(),txs:z2.array(z2.string())}),SwidgeExecuteResponseSchema=z2.object({status:z2.union([z2.literal("success"),z2.literal("failure"),z2.literal("refund"),z2.literal("delayed")]),in:SwidgeStatusInfoSchema,out:SwidgeStatusInfoSchema,lastUpdated:z2.number()}),QUOTE_RESULT={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"},SwidgeSDKResponseSchema=t=>z2.object({success:z2.boolean(),data:t.optional(),error:z2.string().optional(),errorDetails:z2.object({message:z2.string(),status:z2.number().optional(),statusText:z2.string().optional()}).optional()}),SwidgeQuoteResponseWrapperSchema=SwidgeSDKResponseSchema(SwidgeQuoteDataSchema),SwidgeExecuteResponseWrapperSchema=SwidgeSDKResponseSchema(SwidgeExecuteResponseSchema);export{APIClient,Agent,AgentSdk,QUOTE_RESULT,getChainIdFromNetwork,isEthereumNetwork,isSolanaNetwork};
1
+ var __getOwnPropNames=Object.getOwnPropertyNames,__require=(t=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(t,{get:(t,e)=>("undefined"!=typeof require?require:t)[e]}):t)(function(t){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')}),__commonJS=(t,e)=>function(){return e||(0,t[__getOwnPropNames(t)[0]])((e={exports:{}}).exports,e),e.exports},require_auth_loader=__commonJS({"src/utils/auth-loader.cjs"(exports,module){function loadAuthFromFileSystem(){try{if("undefined"==typeof process)return;const fs=eval("require")("fs"),path=eval("require")("path"),os=eval("require")("os"),homeDir=os.homedir();let authPath=path.join(homeDir,".config","circuit","auth.json");if(!fs.existsSync(authPath)&&(authPath=path.join(homeDir,".circuit","auth.json"),!fs.existsSync(authPath)))return;const authContent=fs.readFileSync(authPath,"utf-8");return JSON.parse(authContent)}catch(t){return}}module.exports={loadAuthFromFileSystem:loadAuthFromFileSystem}}}),API_BASE_URL_LOCAL="https://agents.circuit.org",APIClient=class{config;baseUrl;isCloudflareWorker(){return"undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare}hasServiceBinding(){let t=!1;return this.isCloudflareWorker()&&(void 0!==globalThis.AGENTS_TO_API_PROXY||void 0!==globalThis.__AGENT_ENV__&&globalThis.__AGENT_ENV__?.AGENTS_TO_API_PROXY)&&(t=!0),this.config.verbose,t}constructor(t){this.config=t,this.baseUrl=t.baseUrl||API_BASE_URL_LOCAL}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 t={};t["X-Session-Id"]=this.config.sessionId.toString();const e=this.getAgentSlug();if(e&&(t["X-Agent-Slug"]=e),!this.hasServiceBinding())try{const e=this.loadAuthConfig();e?.sessionToken&&(t.Authorization=`Bearer ${e.sessionToken}`)}catch(t){}return t}loadAuthConfig(){try{const{loadAuthFromFileSystem:t}=require_auth_loader();return t()}catch(t){this.config.verbose}}logging(t,e){this.config.verbose}sanitizeHeaders(t){const e={},s=new Set(["report-to","server-timing","server"]),r=t&&"object"==typeof t?t:{};for(const[t,a]of Object.entries(r)){if("string"!=typeof a)continue;const r=t.toLowerCase();s.has(r)||(e[t]="authorization"===r?a.startsWith("Bearer ")?`Bearer ${a.slice(7,14)}***`:"***":a)}return e}async makeRequest(t,e={}){const s={...{"Content-Type":"application/json",...this.getAuthHeaders()},...e.headers};let r;if(this.logging("=== REQUEST DETAILS ==="),this.logging("Endpoint:",t),this.logging("Method:",e.method||"GET"),this.logging("Headers:",this.sanitizeHeaders(s)),this.logging("Body:",e.body),this.logging("Session ID:",this.config.sessionId),this.logging("Agent Slug:",this.getAgentSlug()||"not set"),this.logging("Using Service Binding:",this.hasServiceBinding()),this.logging("====================="),this.hasServiceBinding()){let a;if(void 0!==globalThis.AGENTS_TO_API_PROXY)a=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");a=globalThis.__AGENT_ENV__.AGENTS_TO_API_PROXY}this.logging("Using service binding AGENTS_TO_API_PROXY"),this.logging("Service binding type:",typeof a);const i={...e,headers:s},o=`https://agents-to-api-proxy.circuit-0bc.workers.dev${t}`;r=await a.fetch(o,i)}else{this.logging("Using HTTP fallback to:",this.baseUrl);const a=`${this.baseUrl}${t}`,i={...e,headers:s};r=await fetch(a,i)}if(this.logging("=== RESPONSE DETAILS ==="),this.logging("Status:",r.status),this.logging("Status Text:",r.statusText),this.logging("Response Headers:",this.sanitizeHeaders(Object.fromEntries(r.headers.entries()))),this.logging("======================"),!r.ok){const t=await r.json().catch(()=>({}));throw this.logging("=== ERROR RESPONSE ==="),this.logging("Error Data:",t),this.logging("===================="),new Error(t.error||t.message||`HTTP ${r.status}: ${r.statusText}`)}const a=await r.json();return this.logging("=== SUCCESS RESPONSE ==="),this.logging("Response Data:",a),this.logging("======================"),a}async get(t){return this.makeRequest(t,{method:"GET"})}async post(t,e){return this.makeRequest(t,{method:"POST",body:e?JSON.stringify(e):void 0})}};function isEthereumNetwork(t){return t.startsWith("ethereum:")}function isSolanaNetwork(t){return"solana"===t}function getChainIdFromNetwork(t){return Number(t.split(":")[1])}var AgentSdk=class{client;config;constructor(t){this.config=t,this.client=new APIClient(t)}logging(t,e){this.config.verbose}async sendLog(t){this.logging("=== ADD MESSAGE ==="),this.logging("Message:",t),this.logging("===================");try{await this._sendLog([t])}catch(t){this.logging("=== SEND LOG ERROR ==="),this.logging("Error:",t),this.logging("======================")}}async signAndSend(t){this.logging("=== SIGN AND SEND ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("====================");try{if(this.config.testing)return{success:!0,internalTransactionId:123,txHash:isEthereumNetwork(t.network)?"0xTEST":"TEST_SOL_TX",transactionUrl:void 0};if(isEthereumNetwork(t.network)){const e=getChainIdFromNetwork(t.network);if("toAddress"in t.request)return await this.handleEvmTransaction({chainId:e,toAddress:t.request.toAddress,data:t.request.data,valueWei:t.request.value,message:t.message})}return isSolanaNetwork(t.network)&&"hexTransaction"in t.request?await this.handleSolanaTransaction({hexTransaction:t.request.hexTransaction,message:t.message}):{success:!1,error:`Unsupported network: ${t.network}`,errorDetails:{message:`Unsupported network: ${t.network}`}}}catch(t){return this.logging("=== SIGN AND SEND ERROR ==="),this.logging("Error:",t),this.logging("==========================="),{success:!1,error:t instanceof Error?t.message:"Unknown error",errorDetails:{message:t instanceof Error?t.message:"Unknown error"}}}}async signMessage(t){this.logging("=== SIGN MESSAGE ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("====================");try{return this.config.testing?{v:27,r:"0xTEST_R",s:"0xTEST_S",formattedSignature:"0xTEST_FORMATTED",type:"evm"}:isEthereumNetwork(t.network)?await this.handleEvmSignMessage(t):{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}catch(t){return this.logging("=== SIGN MESSAGE ERROR ==="),this.logging("Error:",t),this.logging("=========================="),{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}}swidge={quote:async t=>this.handleSwidgeQuote(t),execute:async t=>this.handleSwidgeExecute(t)};polymarket={positions:async()=>this.handlePolymarketPositions(),marketOrder:async t=>this.handlePolymarketMarketOrder(t),redeemPositions:async t=>this.handlePolymarketRedeemPositions(t||{tokenIds:[]})};async handleEvmTransaction(t){try{const e=await this.client.post("/v1/transactions/evm",t),s=await this.client.post(`/v1/transactions/evm/${e.internalTransactionId}/broadcast`);return{success:!0,internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}catch(t){this.logging("=== EVM TRANSACTION ERROR ==="),this.logging("Error:",t),this.logging("=============================");let e,s,r,a="Unknown error";if(t instanceof Error){a=t.message;const i=t.message.match(/HTTP (\d+): (.+)/);i&&(e=Number.parseInt(i[1]),s=i[2]),t.message.includes("Failed to estimate gas")&&(r=t.message)}return{success:!1,error:a,errorDetails:{message:r||a,status:e,statusText:s}}}}async handleSolanaTransaction(t){try{const e=await this.client.post("/v1/transactions/solana",t),s=await this.client.post(`/v1/transactions/solana/${e.internalTransactionId}/broadcast`);return{success:!0,internalTransactionId:e.internalTransactionId,txHash:s.txHash,transactionUrl:s.transactionUrl}}catch(t){this.logging("=== SOLANA TRANSACTION ERROR ==="),this.logging("Error:",t),this.logging("================================");let e,s,r="Unknown error";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handleEvmSignMessage(t){try{return await this.client.post("/v1/messages/evm",{messageType:t.request.messageType,data:t.request.data,chainId:t.request.chainId})}catch(t){return this.logging("=== EVM SIGN MESSAGE ERROR ==="),this.logging("Error:",t),this.logging("=============================="),{v:0,r:"0x0",s:"0x0",formattedSignature:"0x0",type:"evm"}}}async _sendLog(t){return this.config.testing?{status:200,message:"Logs added successfully (TESTING)"}:this.client.post("/v1/logs",t)}async _updateJobStatus(t){if(this.logging("UPDATE_JOB_STATUS",t),this.config.testing)return{status:200,message:"Job status updated successfully (TESTING)"};try{return await this.client.post(`/v1/jobs/${t.jobId}/status`,t)}catch(t){return this.logging("=== UPDATE JOB STATUS ERROR ==="),this.logging("Error:",t),this.logging("==============================="),{status:400,message:`Failed to update job status: ${t instanceof Error?t.message:"Unknown error"}`}}}async handleSwidgeQuote(t){this.logging("=== SWIDGE QUOTE ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("===================");try{return this.config.testing?{success:!0,data:{engine:"relay",assetSend:{network:t.from.network,address:t.from.address,token:t.fromToken||null,amount:t.amount,amountFormatted:"1.0",amountUsd:"100.00"},assetReceive:{network:t.to.network,address:t.to.address,token:t.toToken||null,amount:"950000000000000000",amountFormatted:"0.95",amountUsd:"95.00"},priceImpact:{percentage:"0.5",usd:"5.00"},fees:[{name:"gas",amount:"21000000000000000",amountFormatted:"0.021",amountUsd:"2.10"}],steps:[{type:"transaction",description:"Test swap transaction",transactionDetails:{type:"evm",from:"0xtest",to:"0xtest",chainId:1,value:0,data:"0x",gas:21e3,maxFeePerGas:2e10,maxPriorityFeePerGas:1e9},metadata:{requestId:"test-request-id"}}]}}:{success:!0,data:await this.client.post("/v1/swidge/quote",t)}}catch(t){this.logging("=== SWIDGE QUOTE ERROR ==="),this.logging("Error:",t),this.logging("=========================");let e,s,r="Failed to get swidge quote";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handleSwidgeExecute(t){this.logging("=== SWIDGE EXECUTE ==="),this.logging("Quote:",t),this.logging("Testing mode:",this.config.testing),this.logging("=====================");try{if(this.config.testing)return{success:!0,data:{status:"success",in:{network:t.assetSend.network,txs:["0xtest_in_tx"]},out:{network:t.assetReceive.network,txs:["0xtest_out_tx"]},lastUpdated:Date.now()}};this.logging("Making execute request to /v1/swidge/execute");const e=await this.client.post("/v1/swidge/execute",t);return this.logging("Execute response received:",JSON.stringify(e,null,2)),{success:!0,data:e}}catch(t){this.logging("=== SWIDGE EXECUTE ERROR ==="),this.logging("Error:",t),this.logging("============================");let e,s,r="Failed to execute swidge swap";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handlePolymarketPositions(){this.logging("=== POLYMARKET POSITIONS ==="),this.logging("Testing mode:",this.config.testing),this.logging("===========================");try{return this.config.testing?{success:!0,data:{totalValue:0,positions:[]}}:{success:!0,data:await this.client.get("/v1/platforms/polymarket/positions")}}catch(t){this.logging("=== POLYMARKET POSITIONS ERROR ==="),this.logging("Error:",t),this.logging("=================================");let e,s,r="Failed to get polymarket positions";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handlePolymarketMarketOrder(t){this.logging("=== POLYMARKET MARKET ORDER ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("==============================");try{return this.config.testing?{success:!0,data:{success:!0,orderInfo:{orderId:"test-order-id",side:"BUY",size:"1.0",priceUsd:"0.50",totalPriceUsd:"0.50",txHashes:["0xtest"]}}}:{success:!0,data:await this.client.post("/v1/platforms/polymarket/market-order",t)}}catch(t){this.logging("=== POLYMARKET MARKET ORDER ERROR ==="),this.logging("Error:",t),this.logging("====================================");let e,s,r="Failed to execute polymarket market order";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}async handlePolymarketRedeemPositions(t){this.logging("=== POLYMARKET REDEEM POSITIONS ==="),this.logging("Request:",t),this.logging("Testing mode:",this.config.testing),this.logging("==================================");try{return this.config.testing?{success:!0,data:[]}:{success:!0,data:await this.client.post("/v1/platforms/polymarket/redeem-positions",t)}}catch(t){this.logging("=== POLYMARKET REDEEM POSITIONS ERROR ==="),this.logging("Error:",t),this.logging("========================================");let e,s,r="Failed to redeem polymarket positions";if(t instanceof Error){r=t.message;const a=t.message.match(/HTTP (\d+): (.+)/);a&&(e=Number.parseInt(a[1]),s=a[2])}return{success:!1,error:r,errorDetails:{message:r,status:e,statusText:s}}}}};import{zValidator}from"@hono/zod-validator";import{Hono}from"hono";import{cors}from"hono/cors";import{z}from"zod";var CurrentPositionSchema=z.object({network:z.string(),assetAddress:z.string(),tokenId:z.string().nullable(),avgUnitCost:z.string(),currentQty:z.string()}),AgentRequestSchema=z.object({sessionId:z.number(),sessionWalletAddress:z.string(),jobId:z.string().optional(),currentPositions:z.array(CurrentPositionSchema).optional(),otherParameters:z.object().optional()}),AgentResponseSchema=z.object({success:z.boolean(),error:z.string().optional(),message:z.string().optional()}),HealthResponseSchema=z.object({status:z.string()}),Agent=class{app;executionFunction;stopFunction;healthCheckFunction;constructor(t){this.app=new Hono,this.executionFunction=t.executionFunction,this.stopFunction=t.stopFunction,this.healthCheckFunction=t.healthCheckFunction||(async()=>({status:"healthy"})),this.app.use("*",cors()),this.setupRoutes()}defaultStopFunction=async t=>({success:!0,message:`Agent stopped for session ${t.sessionId}`});async executeWithJobTracking(t,e){try{const s=await e(t);if(t.jobId&&s.success)try{await this.updateJobStatus(t.sessionId,t.jobId,"success")}catch(t){}else if(t.jobId&&!s.success)try{const e=s.error||s.message||"Function returned failure";await this.updateJobStatus(t.sessionId,t.jobId,"failed",e)}catch(t){}return s}catch(e){if(t.jobId)try{const s=e instanceof Error?e.message:"Unknown error";await this.updateJobStatus(t.sessionId,t.jobId,"failed",s)}catch(t){}return{success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Function execution failed"}}}async updateJobStatus(t,e,s,r){try{const a=new AgentSdk({sessionId:t}),i={jobId:e,status:s,...r&&{errorMessage:r}};await a._updateJobStatus(i)}catch(t){}}setupRoutes(){this.app.post("/execute",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=await this.executeWithJobTracking(e,this.executionFunction);return t.json(s)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Execution failed"},500)}}),this.app.post("/stop",zValidator("json",AgentRequestSchema),async t=>{try{const e=t.req.valid("json"),s=this.stopFunction||this.defaultStopFunction,r=await this.executeWithJobTracking(e,s);return t.json(r)}catch(e){return t.json({success:!1,error:e instanceof Error?e.message:"Unknown error",message:"Stop operation failed"},500)}}),this.app.get("/health",async t=>{try{const e=await(this.healthCheckFunction?.());return t.json(e)}catch(e){return t.json({status:"unhealthy",error:e instanceof Error?e.message:"Unknown error",timestamp:(new Date).toISOString()},500)}})}getPortFromPackageJson(){try{const t=__require("fs"),e=__require("path").join(process.cwd(),"package.json");if(t.existsSync(e)){const s=JSON.parse(t.readFileSync(e,"utf-8"));if(s.circuit?.port)return Number.parseInt(s.circuit.port,10)}}catch(t){}return null}run(port){const isCloudflareWorker="undefined"!=typeof globalThis&&void 0!==globalThis.Cloudflare;if(isCloudflareWorker)return this.getWorkerExport();const bunEnv=globalThis.Bun?.env,envPort=process.env.AGENT_PORT||bunEnv?.AGENT_PORT,packageJsonPort=this.getPortFromPackageJson();let finalPort=port;!finalPort&&envPort&&(finalPort=Number.parseInt(envPort,10)),!finalPort&&packageJsonPort&&(finalPort=packageJsonPort),finalPort||(finalPort=3e3);try{const req=eval("require"),{serve:serve}=req("@hono/node-server");serve({fetch:this.app.fetch,port:finalPort})}catch(t){process.exit(1)}}getWorkerExport(){return{fetch:async(t,e,s)=>(e&&"undefined"!=typeof globalThis&&(globalThis.__AGENT_ENV__=e),this.app.fetch(t,e,s))}}};function createAgentHandler(t,e,s){return new Agent({executionFunction:t,stopFunction:e,healthCheckFunction:s})}import{z as z2}from"zod";var zEthereumNetwork=z2.templateLiteral(["ethereum:",z2.coerce.number().int().nonnegative()]),SwidgeNetworkSchema=z2.union([z2.literal("solana"),zEthereumNetwork]),SwidgeWalletSchema=z2.object({address:z2.string(),network:SwidgeNetworkSchema}),SwidgeQuoteRequestSchema=z2.object({from:SwidgeWalletSchema,to:SwidgeWalletSchema,fromToken:z2.string().optional(),toToken:z2.string().optional(),amount:z2.string(),priceImpact:z2.string().optional(),slippage:z2.string().optional()}),SwidgeQuoteAssetSchema=z2.object({network:SwidgeNetworkSchema,address:z2.string(),token:z2.string().nullable(),name:z2.string().optional(),symbol:z2.string().optional(),decimals:z2.number().optional(),amount:z2.string().optional(),minimumAmount:z2.string().optional(),amountFormatted:z2.string().optional(),amountUsd:z2.string().optional()}),SwidgePriceImpactSchema=z2.object({usd:z2.string().optional(),percentage:z2.string().optional()}),SwidgeFeeSchema=z2.object({name:z2.string(),amount:z2.string().optional(),amountFormatted:z2.string().optional(),amountUsd:z2.string().optional()}),SwidgeSolanaInstructionSchema=z2.object({programId:z2.string(),keys:z2.array(z2.object({pubkey:z2.string(),isSigner:z2.boolean(),isWritable:z2.boolean()})),data:z2.union([z2.string(),z2.instanceof(Buffer)])}),SwidgeEvmTransactionDetailsSchema=z2.object({type:z2.literal("evm"),from:z2.string().regex(/^0x[a-fA-F0-9]{40}$/),to:z2.string().regex(/^0x[a-fA-F0-9]{40}$/),chainId:z2.number(),value:z2.number(),data:z2.string().regex(/^0x[a-fA-F0-9]*$/),gas:z2.number().optional(),maxFeePerGas:z2.number().optional(),maxPriorityFeePerGas:z2.number().optional()}),SwidgeSolanaTransactionDetailsSchema=z2.object({type:z2.literal("solana"),instructions:z2.array(SwidgeSolanaInstructionSchema),addressLookupTableAddresses:z2.array(z2.string())}),zTransactionStep=z2.object({type:z2.literal("transaction"),description:z2.string(),transactionDetails:z2.union([SwidgeEvmTransactionDetailsSchema,SwidgeSolanaTransactionDetailsSchema]),metadata:z2.record(z2.string(),z2.string())}),zUnsignedSignatureStep=z2.object({type:z2.literal("signature"),description:z2.string(),signatureData:z2.string(),metadata:z2.record(z2.string(),z2.string())}),SwidgeUnsignedStepSchema=z2.discriminatedUnion("type",[zTransactionStep,zUnsignedSignatureStep]),SwidgeQuoteDataSchema=z2.object({engine:z2.literal("relay"),assetSend:SwidgeQuoteAssetSchema,assetReceive:SwidgeQuoteAssetSchema,priceImpact:SwidgePriceImpactSchema,fees:z2.array(SwidgeFeeSchema),steps:z2.array(SwidgeUnsignedStepSchema)}),SwidgeStatusInfoSchema=z2.object({network:z2.string(),txs:z2.array(z2.string())}),SwidgeExecuteResponseSchema=z2.object({status:z2.union([z2.literal("success"),z2.literal("failure"),z2.literal("refund"),z2.literal("delayed")]),in:SwidgeStatusInfoSchema,out:SwidgeStatusInfoSchema,lastUpdated:z2.number()}),QUOTE_RESULT={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"},SwidgeSDKResponseSchema=t=>z2.object({success:z2.boolean(),data:t.optional(),error:z2.string().optional(),errorDetails:z2.object({message:z2.string(),status:z2.number().optional(),statusText:z2.string().optional()}).optional()}),SwidgeQuoteResponseWrapperSchema=SwidgeSDKResponseSchema(SwidgeQuoteDataSchema),SwidgeExecuteResponseWrapperSchema=SwidgeSDKResponseSchema(SwidgeExecuteResponseSchema);export{APIClient,Agent,AgentSdk,QUOTE_RESULT,getChainIdFromNetwork,isEthereumNetwork,isSolanaNetwork};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@circuitorg/agent-sdk",
3
- "version": "1.1.4",
3
+ "version": "1.1.7",
4
4
  "description": "typescript sdk for the Agent Toolset Service",
5
5
  "type": "module",
6
6
  "main": "index.js",