@circuitorg/agent-sdk 1.1.8 β 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +359 -667
- package/chunk-4I3A6QAK.js +1 -0
- package/index.d.ts +1239 -522
- package/index.js +1 -1
- package/package.json +1 -1
- package/utils/auth-loader.d.ts +6 -0
- package/utils/auth-loader.js +1 -0
- package/utils/auth-loader.cjs +0 -39
package/README.md
CHANGED
|
@@ -1,30 +1,45 @@
|
|
|
1
|
-
# Circuit Agent SDK -
|
|
1
|
+
# Circuit Agent SDK - TypeScript
|
|
2
2
|
|
|
3
|
+
> **Clean, unified, type-safe TypeScript SDK for building cross-chain agents on Circuit**
|
|
3
4
|
|
|
4
|
-
A TypeScript SDK for building automated agents to deploy on Circuit.
|
|
5
|
+
A simplified TypeScript SDK for building automated agents to deploy on Circuit. Agents receive a single `AgentContext` object containing everything they need - request data, SDK methods, and unified logging. No boilerplate, no return values to manage, just write your logic.
|
|
5
6
|
|
|
6
7
|
> **π‘ Best used with [Circuit Agents CLI](https://github.com/circuitorg/agents-cli)** - Deploy, manage, and test your agents with ease
|
|
7
8
|
|
|
8
9
|
## π Table of Contents
|
|
9
10
|
|
|
10
|
-
- [
|
|
11
|
-
- [
|
|
12
|
-
- [
|
|
13
|
-
- [
|
|
14
|
-
- [
|
|
15
|
-
- [
|
|
16
|
-
- [
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
22
|
-
-
|
|
23
|
-
-
|
|
24
|
-
-
|
|
25
|
-
-
|
|
11
|
+
- [Circuit Agent SDK - TypeScript](#circuit-agent-sdk---typescript)
|
|
12
|
+
- [π Table of Contents](#-table-of-contents)
|
|
13
|
+
- [π Quick Start](#-quick-start)
|
|
14
|
+
- [Install the SDK](#install-the-sdk)
|
|
15
|
+
- [Create Your First Agent](#create-your-first-agent)
|
|
16
|
+
- [π― Core Concepts](#-core-concepts)
|
|
17
|
+
- [The AgentContext Object](#the-agentcontext-object)
|
|
18
|
+
- [Run/Stop Function Requirements](#runstop-function-requirements)
|
|
19
|
+
- [π Unified Logging with agent.log()](#-unified-logging-with-agentlog)
|
|
20
|
+
- [πΎ Session Memory Storage](#-session-memory-storage)
|
|
21
|
+
- [π Cross-Chain Swaps with Swidge](#-cross-chain-swaps-with-swidge)
|
|
22
|
+
- [Get and execute a quote](#get-and-execute-a-quote)
|
|
23
|
+
- [π Polymarket Prediction Markets](#-polymarket-prediction-markets)
|
|
24
|
+
- [Place Market Orders](#place-market-orders)
|
|
25
|
+
- [Redeem Positions](#redeem-positions)
|
|
26
|
+
- [π Sign \& Send Transactions](#-sign--send-transactions)
|
|
27
|
+
- [Ethereum (any EVM chain)](#ethereum-any-evm-chain)
|
|
28
|
+
- [Solana](#solana)
|
|
29
|
+
- [β‘ Error Handling](#-error-handling)
|
|
30
|
+
- [π οΈ Deployment](#οΈ-deployment)
|
|
31
|
+
- [What You Write](#what-you-write)
|
|
32
|
+
- [Deploy to Circuit](#deploy-to-circuit)
|
|
33
|
+
- [Test Locally](#test-locally)
|
|
34
|
+
- [π§ͺ Manual Instantiation (Testing)](#-manual-instantiation-testing)
|
|
35
|
+
- [π Working Examples](#-working-examples)
|
|
36
|
+
- [`demo-agent.ts`](#demo-agentts)
|
|
37
|
+
- [`examples/kitchen-sink.ts`](#exampleskitchen-sinkts)
|
|
38
|
+
- [π― Key Takeaways](#-key-takeaways)
|
|
39
|
+
- [π Additional Resources](#-additional-resources)
|
|
26
40
|
|
|
27
41
|
## π Quick Start
|
|
42
|
+
|
|
28
43
|
### Install the SDK
|
|
29
44
|
```bash
|
|
30
45
|
npm install @circuitorg/agent-sdk
|
|
@@ -34,771 +49,448 @@ yarn add @circuitorg/agent-sdk
|
|
|
34
49
|
bun add @circuitorg/agent-sdk
|
|
35
50
|
```
|
|
36
51
|
|
|
37
|
-
###
|
|
38
|
-
>**NOTE:** The fastest, and recommended, way to get started is to setup an agent via the circuit [CLI](https://github.com/circuitorg/agents-cli)'s 'circuit agent init' command. This will setup a sample agent directory with the necessary agent wireframe, and configure the cli to allow you for easy testing and deployment. You just simply need to add in your secret formula to the execution and stop functions.
|
|
52
|
+
### Create Your First Agent
|
|
39
53
|
|
|
40
|
-
|
|
41
|
-
import { AgentSdk } from "@circuitorg/agent-sdk";
|
|
54
|
+
Every agent receives a single `AgentContext` object that provides:
|
|
42
55
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
## π― Core SDK API (Only 2 Methods!)
|
|
56
|
+
**Session Data:**
|
|
57
|
+
- `agent.sessionId` - Unique session identifier
|
|
58
|
+
- `agent.sessionWalletAddress` - The wallet address for this session
|
|
59
|
+
- `agent.currentPositions` - Assets allocated to the agent at the start of this execution
|
|
50
60
|
|
|
51
|
-
|
|
61
|
+
**Available Methods:**
|
|
62
|
+
- `agent.log()` - Send messages to users and log locally
|
|
63
|
+
- `agent.memory` - Persist data across executions (`.set()`, `.get()`, `.list()`, `.delete()`)
|
|
64
|
+
- `agent.platforms.polymarket` - Trade prediction markets (`.marketOrder()`, `.redeemPositions()`)
|
|
65
|
+
- `agent.swidge` - Cross-chain swaps and bridges (`.quote()`, `.execute()`)
|
|
66
|
+
- `agent.signAndSend()` - Execute custom built transactions on any supported chain
|
|
67
|
+
- `agent.signMessage()` - Sign messages (EVM only)
|
|
52
68
|
|
|
53
|
-
|
|
69
|
+
**Important:** `currentPositions` reflects your allocated assets at the **start** of each execution. To avoid failed transactions, you should be tracking intra-run position changes based on transactions the agent makes during the execution. Circuit will provide updated positions on the next execution request.
|
|
54
70
|
|
|
55
71
|
```typescript
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
72
|
+
import { Agent, AgentContext } from "@circuitorg/agent-sdk";
|
|
73
|
+
|
|
74
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
75
|
+
/**
|
|
76
|
+
* Main agent logic - receives AgentContext with everything needed.
|
|
77
|
+
* No return value - errors are caught automatically.
|
|
78
|
+
*/
|
|
79
|
+
// Access session data
|
|
80
|
+
await agent.log(`Starting execution for session ${agent.sessionId}`);
|
|
81
|
+
await agent.log(`Wallet: ${agent.sessionWalletAddress}`);
|
|
82
|
+
await agent.log(`Managing ${agent.currentPositions.length} allocated positions`);
|
|
83
|
+
|
|
84
|
+
// Use SDK methods
|
|
85
|
+
await agent.memory.set("last_run", Date.now().toString());
|
|
86
|
+
|
|
87
|
+
// Your agent logic here - track position changes within this execution
|
|
88
|
+
// Circuit will provide updated positions on the next run
|
|
89
|
+
}
|
|
63
90
|
|
|
64
|
-
|
|
91
|
+
async function stop(agent: AgentContext): Promise<void> {
|
|
92
|
+
/**Cleanup when agent is stopped.*/
|
|
93
|
+
await agent.log("Cleaning up resources");
|
|
94
|
+
await agent.memory.delete("temp_data");
|
|
95
|
+
}
|
|
65
96
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
request: {
|
|
71
|
-
toAddress: "0x742d35cc6634C0532925a3b8D65e95f32B6b5582" as `0x${string}`,
|
|
72
|
-
data: "0x" as `0x${string}`,
|
|
73
|
-
value: "1000000000000000000" // 1 ETH in wei
|
|
74
|
-
},
|
|
75
|
-
message: "Sending 1 ETH"
|
|
97
|
+
// Boilerplate - This should never change unless you want to change the names of your run and stop functions
|
|
98
|
+
const agent = new Agent({
|
|
99
|
+
runFunction: run,
|
|
100
|
+
stopFunction: stop
|
|
76
101
|
});
|
|
77
102
|
|
|
78
|
-
|
|
79
|
-
await sdk.signAndSend({
|
|
80
|
-
network: "ethereum:42161", // Arbitrum
|
|
81
|
-
request: {
|
|
82
|
-
toAddress: "0xTokenContract..." as `0x${string}`,
|
|
83
|
-
data: "0xa9059cbb..." as `0x${string}`, // encoded transfer()
|
|
84
|
-
value: "0"
|
|
85
|
-
}
|
|
86
|
-
});
|
|
103
|
+
export default agent.getExport();
|
|
87
104
|
```
|
|
88
105
|
|
|
89
|
-
|
|
106
|
+
## π― Core Concepts
|
|
90
107
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
request: {
|
|
95
|
-
hexTransaction: "010001030a0b..." // serialized VersionedTransaction
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
```
|
|
108
|
+
### The AgentContext Object
|
|
109
|
+
|
|
110
|
+
Every agent function receives a single `AgentContext` object that contains:
|
|
99
111
|
|
|
112
|
+
**Request Data:**
|
|
113
|
+
- `agent.sessionId` - Unique session identifier
|
|
114
|
+
- `agent.sessionWalletAddress` - Wallet address for this session
|
|
115
|
+
- `agent.currentPositions` - Current positions allocated to this agent
|
|
100
116
|
|
|
101
|
-
|
|
117
|
+
**SDK Methods:**
|
|
118
|
+
- `agent.log()` - Unified logging (console + backend)
|
|
119
|
+
- `agent.memory` - Session-scoped key-value storage
|
|
120
|
+
- `agent.platforms.polymarket` - Prediction market operations
|
|
121
|
+
- `agent.swidge` - Cross-chain swap operations
|
|
122
|
+
- `agent.signAndSend()` - Sign and broadcast transactions
|
|
123
|
+
- `agent.signMessage()` - Sign messages on EVM
|
|
102
124
|
|
|
103
|
-
|
|
125
|
+
### Run/Stop Function Requirements
|
|
104
126
|
|
|
105
|
-
|
|
127
|
+
1. **Signature**: `async function myFunction(agent: AgentContext): Promise<void>`
|
|
128
|
+
2. **Return**: Always return `void` (or no return statement)
|
|
129
|
+
3. **Errors**: You should surface any relevant errors via `agent.log('error message', { error: true })`. All errors from built-in SDK functions will be caught gracefully and provided in the return data for you to handle as necessary.
|
|
106
130
|
|
|
107
|
-
|
|
131
|
+
## π Unified Logging with agent.log()
|
|
108
132
|
|
|
109
|
-
|
|
133
|
+
Use `agent.log()` to communicate with your users and debug your agent. Every message appears in your terminal, and by default also shows up in the Circuit UI for your users to see. Simply pass `debug: true` to skip sending the message to the user.
|
|
110
134
|
|
|
111
135
|
```typescript
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
});
|
|
136
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
137
|
+
// Standard log: Shows to user in Circuit UI
|
|
138
|
+
await agent.log("Processing transaction");
|
|
139
|
+
|
|
140
|
+
// Error log: Shows to user in Circuit UI (as an error)
|
|
141
|
+
const result = await agent.memory.get("key");
|
|
142
|
+
if (!result.success) {
|
|
143
|
+
await agent.log(result.error_message || result.error, { error: true });
|
|
144
|
+
}
|
|
122
145
|
|
|
123
|
-
//
|
|
124
|
-
|
|
125
|
-
from: { network: "ethereum:42161", address: request.sessionWalletAddress },
|
|
126
|
-
to: { network: "ethereum:42161", address: request.sessionWalletAddress },
|
|
127
|
-
amount: "100000000", // $100 USDC (6 decimals)
|
|
128
|
-
fromToken: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC
|
|
129
|
-
// toToken omitted = native ETH (default behavior)
|
|
130
|
-
// slippage defaults to "0.5", priceImpact defaults to "0.5"
|
|
131
|
-
});
|
|
146
|
+
// Debug log: Only you see this in your terminal
|
|
147
|
+
await agent.log("Internal state: processing...", { debug: true });
|
|
132
148
|
|
|
133
|
-
|
|
134
|
-
console
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
// Check
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
console.log("π Wallet address doesn't match session");
|
|
142
|
-
} else {
|
|
143
|
-
console.log("β Quote not available for this swap");
|
|
149
|
+
// Logging objects
|
|
150
|
+
// Objects are pretty-printed to console and serialized/truncated for backend
|
|
151
|
+
await agent.log({ wallet: agent.sessionWalletAddress, status: "active" });
|
|
152
|
+
|
|
153
|
+
// Check if message reached the user
|
|
154
|
+
const logResult = await agent.log("Important message");
|
|
155
|
+
if (!logResult.success) {
|
|
156
|
+
// Rare - usually means Circuit UI is unreachable
|
|
144
157
|
}
|
|
145
158
|
}
|
|
146
159
|
```
|
|
147
160
|
|
|
148
|
-
|
|
161
|
+
**What Your Users See:**
|
|
149
162
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
fromToken: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC on Arbitrum
|
|
157
|
-
priceImpact: "0.1", // Conservative price impact setting
|
|
158
|
-
slippage: "5.0"
|
|
159
|
-
};
|
|
163
|
+
| Code | You See (Terminal) | User Sees (Circuit UI) |
|
|
164
|
+
|------|-------------------|----------------------|
|
|
165
|
+
| `agent.log("msg")` | β
In your terminal | β
In Circuit UI |
|
|
166
|
+
| `agent.log("msg", { error: true })` | β
As error in terminal | β
As error in Circuit UI |
|
|
167
|
+
| `agent.log("msg", { debug: true })` | β
In terminal | β Hidden from user |
|
|
168
|
+
| `agent.log("msg", { error: true, debug: true })` | β
As error in terminal | β Hidden from user |
|
|
160
169
|
|
|
161
|
-
|
|
170
|
+
## πΎ Session Memory Storage
|
|
162
171
|
|
|
163
|
-
|
|
164
|
-
if (quote.error === QUOTE_RESULT.NO_QUOTE_PROVIDED) {
|
|
165
|
-
console.log(`β Quote not available, increasing price impact and retrying...`)
|
|
166
|
-
// Retry with more permissive parameters
|
|
167
|
-
quoteRequest.priceImpact = "10.0";
|
|
168
|
-
quoteRequest.slippage = "10.0";
|
|
169
|
-
quote = await sdk.swidge.quote(quoteRequest);
|
|
170
|
-
}
|
|
172
|
+
Store and retrieve data for your agent's session with simple operations. Memory is **automatically scoped to your session ID**, and for now is simple string storage. You will need to handle serialization of whatever data you want to store here.
|
|
171
173
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
console.log("β
Cross-chain swap completed!");
|
|
186
|
-
} else if (result.data.status === "failure") {
|
|
187
|
-
console.log("β Transaction failed");
|
|
188
|
-
} else if (result.data.status === "refund") {
|
|
189
|
-
console.log("β©οΈ Transaction was refunded");
|
|
190
|
-
} else if (result.data.status === "delayed") {
|
|
191
|
-
console.log("β° Transaction is delayed");
|
|
192
|
-
}
|
|
174
|
+
```typescript
|
|
175
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
176
|
+
// Set a value
|
|
177
|
+
const result = await agent.memory.set("lastSwapNetwork", "ethereum:42161");
|
|
178
|
+
if (!result.success) {
|
|
179
|
+
await agent.log(result.error_message || result.error, { error: true });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Get a value
|
|
183
|
+
const getResult = await agent.memory.get("lastSwapNetwork");
|
|
184
|
+
if (getResult.success && getResult.data) {
|
|
185
|
+
const network = getResult.data.value;
|
|
186
|
+
await agent.log(`Using network: ${network}`);
|
|
193
187
|
} else {
|
|
194
|
-
|
|
188
|
+
await agent.log("No saved network found");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// List all keys
|
|
192
|
+
const listResult = await agent.memory.list();
|
|
193
|
+
if (listResult.success && listResult.data) {
|
|
194
|
+
await agent.log(`Found ${listResult.data.count} keys: ${listResult.data.keys}`);
|
|
195
195
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
196
|
+
|
|
197
|
+
// Delete a key
|
|
198
|
+
await agent.memory.delete("tempData");
|
|
199
199
|
}
|
|
200
200
|
```
|
|
201
201
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
> **High-level abstraction** built on core SDK methods. Simplifies prediction market trading on Polygon.
|
|
202
|
+
**All memory operations return responses with `.success` and `.error_message`:**
|
|
205
203
|
|
|
206
|
-
|
|
204
|
+
```typescript
|
|
205
|
+
const result = await agent.memory.set("key", "value");
|
|
206
|
+
if (!result.success) {
|
|
207
|
+
await agent.log(`Failed to save: ${result.error_message}`, { error: true });
|
|
208
|
+
}
|
|
209
|
+
```
|
|
207
210
|
|
|
211
|
+
## π Cross-Chain Swaps with Swidge
|
|
208
212
|
|
|
209
|
-
|
|
213
|
+
Built-in Swidge integration for seamless cross-chain token swaps and bridges.
|
|
210
214
|
|
|
211
|
-
###
|
|
215
|
+
### Get and execute a quote
|
|
216
|
+
> Note: It is important to always validate quotes before executing. Circuit will always do its best to return a quote, and as of now, will only filter out quotes with price impacts exceeding 100% to ensure maximum flexibility. It is on the agent to makes sure a quote is valid, given its own parameters
|
|
212
217
|
|
|
213
|
-
|
|
218
|
+
```typescript
|
|
219
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
220
|
+
// 1. Get quote
|
|
221
|
+
const quote = await agent.swidge.quote({
|
|
222
|
+
from: { network: "ethereum:8453", address: agent.sessionWalletAddress },
|
|
223
|
+
to: { network: "ethereum:137", address: agent.sessionWalletAddress },
|
|
224
|
+
amount: "1000000000000000", // 0.001 ETH
|
|
225
|
+
toToken: "0x2791bca1f2de4661ed88a30c99a7a9449aa84174",
|
|
226
|
+
slippage: "2.0",
|
|
227
|
+
});
|
|
214
228
|
|
|
215
|
-
|
|
229
|
+
if (!quote.success) {
|
|
230
|
+
await agent.log(`Quote failed: ${quote.error_message}`, { error: true });
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
216
233
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
234
|
+
if (quote.data && Math.abs(parseFloat(quote.data.priceImpact.percentage)) > 10) {
|
|
235
|
+
await agent.log(`Warning: Price impact is too high: ${quote.data.priceImpact.percentage}%`, { error: true, debug: true });
|
|
236
|
+
} else if (quote.data) {
|
|
237
|
+
await agent.log(`You'll receive: ${quote.data.assetReceive.amountFormatted}`);
|
|
238
|
+
await agent.log(`Fees: ${quote.data.fees.map(f => f.name).join(', ')}`);
|
|
239
|
+
|
|
240
|
+
// 2. Execute the swap
|
|
241
|
+
const result = await agent.swidge.execute(quote.data);
|
|
242
|
+
|
|
243
|
+
if (result.success && result.data) {
|
|
244
|
+
await agent.log(`Swap status: ${result.data.status}`);
|
|
245
|
+
if (result.data.status === "success") {
|
|
246
|
+
await agent.log("β
Swap completed!");
|
|
247
|
+
await agent.log(`In tx: ${result.data.in.txs}`);
|
|
248
|
+
await agent.log(`Out tx: ${result.data.out.txs}`);
|
|
249
|
+
} else if (result.data.status === "failure") {
|
|
250
|
+
await agent.log("β Swap failed", { error: true });
|
|
251
|
+
}
|
|
252
|
+
} else {
|
|
253
|
+
await agent.log(result.error_message || result.error, { error: true });
|
|
254
|
+
}
|
|
228
255
|
}
|
|
229
256
|
}
|
|
230
257
|
```
|
|
231
258
|
|
|
232
|
-
|
|
259
|
+
## π Polymarket Prediction Markets
|
|
260
|
+
|
|
261
|
+
Trade prediction markets on Polygon.
|
|
233
262
|
|
|
234
|
-
|
|
263
|
+
### Place Market Orders
|
|
264
|
+
> Note: Right now, polymarket's API accepts different decimal precision for buys and sells, this will result in dust positions if you are selling out of a position before expiry. Once expired, dust can be cleaned up during the redeem step.
|
|
235
265
|
|
|
236
266
|
```typescript
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
267
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
268
|
+
// Buy order - size is USD amount to spend
|
|
269
|
+
const buyOrder = await agent.platforms.polymarket.marketOrder({
|
|
270
|
+
tokenId: "86192057611122246511563653509192966169513312957180910360241289053249649036697",
|
|
271
|
+
size: 3, // Spend $3
|
|
272
|
+
side: "BUY"
|
|
273
|
+
});
|
|
243
274
|
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
});
|
|
275
|
+
if (buyOrder.success && buyOrder.data) {
|
|
276
|
+
await agent.log(`Order ID: ${buyOrder.data.orderInfo.orderId}`);
|
|
277
|
+
await agent.log(`Price: $${buyOrder.data.orderInfo.priceUsd}`);
|
|
278
|
+
await agent.log(`Total: $${buyOrder.data.orderInfo.totalPriceUsd}`);
|
|
279
|
+
} else {
|
|
280
|
+
await agent.log(buyOrder.error_message || buyOrder.error, { error: true });
|
|
281
|
+
}
|
|
250
282
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
283
|
+
// Sell order - size is number of shares to sell
|
|
284
|
+
const sellOrder = await agent.platforms.polymarket.marketOrder({
|
|
285
|
+
tokenId: "86192057611122246511563653509192966169513312957180910360241289053249649036697",
|
|
286
|
+
size: 5.5, // Sell 5.5 shares
|
|
287
|
+
side: "SELL"
|
|
288
|
+
});
|
|
256
289
|
}
|
|
257
290
|
```
|
|
258
291
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
Claim winnings from settled positions:
|
|
292
|
+
### Redeem Positions
|
|
262
293
|
|
|
263
294
|
```typescript
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
console.log(`β
Unwrapped collateral`);
|
|
274
|
-
}
|
|
275
|
-
console.log(` TX: ${result.transactionHash}`);
|
|
276
|
-
}
|
|
295
|
+
async function stop(agent: AgentContext): Promise<void> {
|
|
296
|
+
/**Redeem all settled positions.*/
|
|
297
|
+
const redemption = await agent.platforms.polymarket.redeemPositions();
|
|
298
|
+
|
|
299
|
+
if (redemption.success && redemption.data) {
|
|
300
|
+
const successful = redemption.data.filter(r => r.success);
|
|
301
|
+
await agent.log(`Redeemed ${successful.length} positions`);
|
|
302
|
+
} else {
|
|
303
|
+
await agent.log(redemption.error_message || redemption.error, { error: true });
|
|
277
304
|
}
|
|
278
305
|
}
|
|
279
|
-
|
|
280
|
-
// Redeem specific positions by token IDs
|
|
281
|
-
const specificRedemption = await sdk.polymarket.redeemPositions({
|
|
282
|
-
tokenIds: ["123456", "789012"]
|
|
283
|
-
});
|
|
284
306
|
```
|
|
285
307
|
|
|
286
|
-
|
|
308
|
+
## π Sign & Send Transactions
|
|
309
|
+
|
|
310
|
+
### Ethereum (any EVM chain)
|
|
287
311
|
|
|
288
312
|
```typescript
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
313
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
314
|
+
// Self-send demo - send a small amount to yourself
|
|
315
|
+
const response = await agent.signAndSend({
|
|
316
|
+
network: "ethereum:1",
|
|
317
|
+
request: {
|
|
318
|
+
toAddress: agent.sessionWalletAddress, // Send to self
|
|
319
|
+
data: "0x",
|
|
320
|
+
value: "100000000000000" // 0.0001 ETH
|
|
321
|
+
},
|
|
322
|
+
message: "Self-send demo"
|
|
323
|
+
});
|
|
299
324
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
if (targetPosition && Number(targetPosition.formattedShares) > 0) {
|
|
306
|
-
// Sell position
|
|
307
|
-
const sellOrder = await sdk.polymarket.marketOrder({
|
|
308
|
-
tokenId: targetPosition.tokenId,
|
|
309
|
-
size: Number(targetPosition.formattedShares),
|
|
310
|
-
side: "SELL"
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
if (sellOrder.success && sellOrder.data?.orderInfo) {
|
|
314
|
-
await sdk.sendLog({
|
|
315
|
-
type: "observe",
|
|
316
|
-
shortMessage: `Sold ${targetPosition.outcome} for $${sellOrder.data.orderInfo.totalPriceUsd}`
|
|
317
|
-
});
|
|
318
|
-
}
|
|
325
|
+
if (response.success) {
|
|
326
|
+
await agent.log(`Transaction sent: ${response.txHash}`);
|
|
327
|
+
if (response.transactionUrl) {
|
|
328
|
+
await agent.log(`View: ${response.transactionUrl}`);
|
|
319
329
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
} catch (error) {
|
|
323
|
-
await sdk.sendLog({
|
|
324
|
-
type: "error",
|
|
325
|
-
shortMessage: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
|
|
326
|
-
});
|
|
327
|
-
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
|
|
330
|
+
} else {
|
|
331
|
+
await agent.log(response.error_message || response.error, { error: true });
|
|
328
332
|
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
const stopFunction: StopFunctionContract = async (request) => {
|
|
332
|
-
const sdk = new AgentSdk({ sessionId: request.sessionId });
|
|
333
|
+
}
|
|
334
|
+
```
|
|
333
335
|
|
|
334
|
-
|
|
335
|
-
// Redeem all settled positions on stop
|
|
336
|
-
const redemption = await sdk.polymarket.redeemPositions();
|
|
336
|
+
### Solana
|
|
337
337
|
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
338
|
+
```typescript
|
|
339
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
340
|
+
const response = await agent.signAndSend({
|
|
341
|
+
network: "solana",
|
|
342
|
+
request: {
|
|
343
|
+
hexTransaction: "010001030a0b..." // serialized VersionedTransaction
|
|
344
344
|
}
|
|
345
|
+
});
|
|
345
346
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
347
|
+
if (response.success) {
|
|
348
|
+
await agent.log(`Transaction: ${response.txHash}`);
|
|
349
|
+
} else {
|
|
350
|
+
await agent.log(response.error_message || response.error, { error: true });
|
|
349
351
|
}
|
|
350
|
-
}
|
|
352
|
+
}
|
|
351
353
|
```
|
|
352
354
|
|
|
353
|
-
##
|
|
355
|
+
## β‘ Error Handling
|
|
354
356
|
|
|
355
|
-
|
|
357
|
+
**All SDK methods return response objects with `.success` and `.error_message`:**
|
|
356
358
|
|
|
357
|
-
Store and retrieve data for your agent's session with simple get/set/delete/list operations. Memory is **automatically scoped to your session ID** - each session has isolated storage that persists across execution cycles.
|
|
358
359
|
|
|
359
|
-
|
|
360
|
+
**Uncaught Exceptions:**
|
|
360
361
|
|
|
361
|
-
|
|
362
|
+
If your function throws an uncaught exception, the Agent SDK automatically:
|
|
363
|
+
1. Logs the error to console (visible in local dev and cloud logs)
|
|
364
|
+
2. Updates the job in the circuit backend with status='failed' and logs the error.
|
|
362
365
|
|
|
363
366
|
```typescript
|
|
364
|
-
|
|
365
|
-
|
|
367
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
368
|
+
// This typo will be caught and logged automatically
|
|
369
|
+
await agent.memmory.set("key", "value"); // TypeError
|
|
366
370
|
|
|
367
|
-
|
|
368
|
-
console.log(`Stored key: ${result.data.key}`);
|
|
369
|
-
} else {
|
|
370
|
-
console.error(`Failed to store: ${result.error}`);
|
|
371
|
+
// No need for try/catch around everything!
|
|
371
372
|
}
|
|
372
373
|
```
|
|
373
374
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
```typescript
|
|
377
|
-
// Retrieve stored preferences
|
|
378
|
-
const result = await sdk.memory.get("lastSwapNetwork");
|
|
375
|
+
## π οΈ Deployment
|
|
379
376
|
|
|
380
|
-
|
|
381
|
-
console.log(`Network: ${result.data.value}`);
|
|
382
|
-
} else {
|
|
383
|
-
console.log(`Key not found: ${result.error}`);
|
|
384
|
-
}
|
|
385
|
-
```
|
|
377
|
+
### What You Write
|
|
386
378
|
|
|
387
|
-
|
|
379
|
+
Your agent code should look like this - just define your functions and add the boilerplate at the bottom:
|
|
388
380
|
|
|
389
381
|
```typescript
|
|
390
|
-
|
|
391
|
-
const result = await sdk.memory.delete("tempSwapQuote");
|
|
382
|
+
import { Agent, AgentContext } from "@circuitorg/agent-sdk";
|
|
392
383
|
|
|
393
|
-
|
|
394
|
-
|
|
384
|
+
async function run(agent: AgentContext): Promise<void> {
|
|
385
|
+
await agent.log("Hello from my agent!");
|
|
386
|
+
// Your agent logic here
|
|
395
387
|
}
|
|
396
|
-
```
|
|
397
|
-
|
|
398
|
-
#### List All Keys
|
|
399
388
|
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
if (result.success && result.data) {
|
|
405
|
-
console.log(`Found ${result.data.count} keys:`);
|
|
406
|
-
result.data.keys.forEach(key => console.log(` - ${key}`));
|
|
389
|
+
async function stop(agent: AgentContext): Promise<void> {
|
|
390
|
+
await agent.log("Cleaning up...");
|
|
391
|
+
// Optional cleanup logic
|
|
407
392
|
}
|
|
408
|
-
```
|
|
409
|
-
|
|
410
|
-
### Complete Memory Example
|
|
411
393
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
let count = 0;
|
|
421
|
-
if (counterResult.success && counterResult.data) {
|
|
422
|
-
count = parseInt(counterResult.data.value);
|
|
423
|
-
await sdk.sendLog({
|
|
424
|
-
type: "observe",
|
|
425
|
-
shortMessage: `Execution #${count + 1} - Welcome back!`
|
|
426
|
-
});
|
|
427
|
-
} else {
|
|
428
|
-
await sdk.sendLog({
|
|
429
|
-
type: "observe",
|
|
430
|
-
shortMessage: "First execution - initializing..."
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// Store some session data
|
|
435
|
-
await sdk.memory.set("executionCount", String(count + 1));
|
|
436
|
-
await sdk.memory.set("lastRunTimestamp", Date.now().toString());
|
|
437
|
-
await sdk.memory.set("userPreferences", JSON.stringify({
|
|
438
|
-
network: "ethereum:42161",
|
|
439
|
-
slippage: "2.0"
|
|
440
|
-
}));
|
|
441
|
-
|
|
442
|
-
// List all stored keys
|
|
443
|
-
const listResult = await sdk.memory.list();
|
|
444
|
-
if (listResult.success && listResult.data) {
|
|
445
|
-
await sdk.sendLog({
|
|
446
|
-
type: "observe",
|
|
447
|
-
shortMessage: `Stored ${listResult.data.count} keys: ${listResult.data.keys.join(", ")}`
|
|
448
|
-
});
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
return { success: true };
|
|
452
|
-
} catch (error) {
|
|
453
|
-
await sdk.sendLog({
|
|
454
|
-
type: "error",
|
|
455
|
-
shortMessage: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`
|
|
456
|
-
});
|
|
457
|
-
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
|
-
|
|
461
|
-
const stopFunction: StopFunctionContract = async (request) => {
|
|
462
|
-
const sdk = new AgentSdk({ sessionId: request.sessionId });
|
|
463
|
-
|
|
464
|
-
try {
|
|
465
|
-
// Clean up temporary data on stop
|
|
466
|
-
const listResult = await sdk.memory.list();
|
|
467
|
-
if (listResult.success && listResult.data) {
|
|
468
|
-
// Delete all temp keys
|
|
469
|
-
for (const key of listResult.data.keys) {
|
|
470
|
-
if (key.startsWith("temp_")) {
|
|
471
|
-
await sdk.memory.delete(key);
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
}
|
|
394
|
+
// ============================================================================
|
|
395
|
+
// BOILERPLATE - Don't modify, this handles local testing AND Circuit deployment
|
|
396
|
+
// ============================================================================
|
|
397
|
+
const agent = new Agent({
|
|
398
|
+
runFunction: run,
|
|
399
|
+
stopFunction: stop
|
|
400
|
+
});
|
|
475
401
|
|
|
476
|
-
|
|
477
|
-
} catch (error) {
|
|
478
|
-
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
|
|
479
|
-
}
|
|
480
|
-
};
|
|
402
|
+
export default agent.getExport();
|
|
481
403
|
```
|
|
482
404
|
|
|
405
|
+
That's it! The boilerplate code automatically handles the rest
|
|
483
406
|
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
### Barebones Agent
|
|
487
|
-
>This is the wireframe structure all agents need to have (executionFunction, stopFunction, and export default agent.getWorkerExport()). The main thing an agent dev needs to focus on is the execution logic, and any cleanup logic that would need to be ran whenever a user decides to stop an agent session.
|
|
407
|
+
### Deploy to Circuit
|
|
488
408
|
|
|
489
|
-
```
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
const executionFunction: ExecutionFunctionContract = async (request) => {
|
|
494
|
-
console.log(`π Agent execution called for session ${request.sessionId}`);
|
|
495
|
-
|
|
496
|
-
const sdk = new AgentSdk({
|
|
497
|
-
sessionId: request.sessionId,
|
|
498
|
-
});
|
|
499
|
-
|
|
500
|
-
try {
|
|
501
|
-
// Get user's wallet address (use vitalik.eth for demo if no address provided)
|
|
502
|
-
const userAddress = request.sessionWalletAddress
|
|
503
|
-
|
|
504
|
-
await sdk.sendLog({
|
|
505
|
-
type: "observe",
|
|
506
|
-
shortMessage: `π Agent SDK v1.0 demo - Hello ${userAddress}`
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
return { success: true};
|
|
510
|
-
} catch (error) {
|
|
511
|
-
await sdk.sendLog({
|
|
512
|
-
type: "error",
|
|
513
|
-
shortMessage: `Agent execution error: ${error instanceof Error ? error.message : 'Unknown error'}`
|
|
514
|
-
});
|
|
515
|
-
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
|
|
516
|
-
}
|
|
517
|
-
};
|
|
518
|
-
|
|
519
|
-
const stopFunction: StopFunctionContract = async (request) => {
|
|
520
|
-
const sdk = new AgentSdk({
|
|
521
|
-
sessionId: request.sessionId,
|
|
522
|
-
testing: true
|
|
523
|
-
});
|
|
524
|
-
|
|
525
|
-
try {
|
|
526
|
-
await sdk.sendLog({
|
|
527
|
-
type: "observe",
|
|
528
|
-
shortMessage: "π Agent stopping with new SDK v1.0"
|
|
529
|
-
});
|
|
530
|
-
return { success: true };
|
|
531
|
-
} catch (error) {
|
|
532
|
-
return { success: false, error: error instanceof Error ? error.message : "Unknown error" };
|
|
533
|
-
}
|
|
534
|
-
};
|
|
409
|
+
```bash
|
|
410
|
+
circuit publish
|
|
411
|
+
```
|
|
412
|
+
> See the circuit cli docs for more details
|
|
535
413
|
|
|
536
|
-
// DONT MODIFY BELOW THIS
|
|
537
|
-
const agent = new Agent({ executionFunction, stopFunction });
|
|
538
414
|
|
|
539
|
-
|
|
540
|
-
export default agent.getWorkerExport();
|
|
415
|
+
### Test Locally
|
|
541
416
|
|
|
542
|
-
|
|
417
|
+
## π§ͺ Manual Instantiation (Testing)
|
|
543
418
|
|
|
419
|
+
For testing in scripts or Node.js REPL, you can manually create an `AgentContext`:
|
|
544
420
|
|
|
545
|
-
### Sample self sender
|
|
546
|
-
>This demonstrates a very basic structure of fetching balances and sending 1% of that amount to yourself. It highlights what stage in the transaction process you will "hand off" the transaction to the circuit infrastructure for signing and sending (broadcasting).
|
|
547
421
|
```typescript
|
|
548
|
-
import {
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
422
|
+
import { AgentContext } from "@circuitorg/agent-sdk";
|
|
423
|
+
|
|
424
|
+
// Create agent context with test data
|
|
425
|
+
// Tip: Get a real session ID and wallet from running 'circuit run -m local -x execute'
|
|
426
|
+
const SESSION_ID = 123; // <your-session-id>
|
|
427
|
+
const WALLET_ADDRESS = "your-wallet-address";
|
|
428
|
+
|
|
429
|
+
// Create sample position data - helpful for testing your agents treatment of different scenarios
|
|
430
|
+
// for example if you want to test some re-balancing logic, you can build a sample set of positions here
|
|
431
|
+
// In production, or when using the cli, these will be live values for the session
|
|
432
|
+
const SAMPLE_POSITION = {
|
|
433
|
+
network: "ethereum:137",
|
|
434
|
+
assetAddress: "0x4d97dcd97ec945f40cf65f87097ace5ea0476045",
|
|
435
|
+
tokenId: "86192057611122246511563653509192966169513312957180910360241289053249649036697",
|
|
436
|
+
avgUnitCost: "0.779812797920499100",
|
|
437
|
+
currentQty: "41282044"
|
|
563
438
|
};
|
|
564
439
|
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
})
|
|
570
|
-
// balanceOf(address) - ERC-20 standard
|
|
571
|
-
const data = `0x70a08231${params.address
|
|
572
|
-
.replace(/^0x/, "")
|
|
573
|
-
.padStart(64, "0")}`;
|
|
574
|
-
|
|
575
|
-
const balanceCall = {
|
|
576
|
-
jsonrpc: "2.0",
|
|
577
|
-
id: 1,
|
|
578
|
-
method: "eth_call",
|
|
579
|
-
params: [{ to: params.token, data }, "latest"],
|
|
580
|
-
} as const;
|
|
581
|
-
|
|
582
|
-
const balanceRes = await fetch(params.rpcUrl, {
|
|
583
|
-
method: "POST",
|
|
584
|
-
headers: { "content-type": "application/json" },
|
|
585
|
-
body: JSON.stringify(balanceCall),
|
|
586
|
-
});
|
|
587
|
-
|
|
588
|
-
const balanceJson = (await balanceRes.json()) as { result?: string };
|
|
589
|
-
const balHex = balanceJson.result || "0x0";
|
|
590
|
-
const amount = BigInt(balHex);
|
|
591
|
-
|
|
592
|
-
// decimals() - ERC-20 standard
|
|
593
|
-
const decimalsCall = {
|
|
594
|
-
jsonrpc: "2.0",
|
|
595
|
-
id: 2,
|
|
596
|
-
method: "eth_call",
|
|
597
|
-
params: [{ to: params.token, data: "0x313ce567" }, "latest"],
|
|
598
|
-
} as const;
|
|
599
|
-
|
|
600
|
-
const decimalsRes = await fetch(params.rpcUrl, {
|
|
601
|
-
method: "POST",
|
|
602
|
-
headers: { "content-type": "application/json" },
|
|
603
|
-
body: JSON.stringify(decimalsCall),
|
|
604
|
-
});
|
|
440
|
+
const agent = new AgentContext({
|
|
441
|
+
sessionId: SESSION_ID,
|
|
442
|
+
sessionWalletAddress: WALLET_ADDRESS,
|
|
443
|
+
currentPositions: [SAMPLE_POSITION]
|
|
444
|
+
});
|
|
605
445
|
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
: 18;
|
|
446
|
+
// Use it just like in production!
|
|
447
|
+
await agent.log("Testing agent functionality!");
|
|
448
|
+
await agent.memory.set("test_key", "test_value");
|
|
610
449
|
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
isToken: true,
|
|
615
|
-
};
|
|
450
|
+
const result = await agent.memory.get("test_key");
|
|
451
|
+
if (result.success && result.data) {
|
|
452
|
+
console.log(`Value: ${result.data.value}`);
|
|
616
453
|
}
|
|
454
|
+
```
|
|
617
455
|
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
"1": "β",
|
|
622
|
-
"2": "β",
|
|
623
|
-
"3": "β",
|
|
624
|
-
"4": "β",
|
|
625
|
-
"5": "β
",
|
|
626
|
-
"6": "β",
|
|
627
|
-
"7": "β",
|
|
628
|
-
"8": "β",
|
|
629
|
-
"9": "β",
|
|
630
|
-
};
|
|
631
|
-
return String(num)
|
|
632
|
-
.split("")
|
|
633
|
-
.map((c) => map[c] ?? c)
|
|
634
|
-
.join("");
|
|
635
|
-
};
|
|
456
|
+
**Key Points:**
|
|
457
|
+
- Use real session IDs from the CLI for proper testing
|
|
458
|
+
- All SDK methods work the same way as in production
|
|
636
459
|
|
|
637
|
-
|
|
638
|
-
amount: bigint,
|
|
639
|
-
decimals: number,
|
|
640
|
-
subscriptDecimals: number = 4,
|
|
641
|
-
standardDecimals: number = 6
|
|
642
|
-
): string => {
|
|
643
|
-
const sign = amount < 0n ? "-" : "";
|
|
644
|
-
const s = (amount < 0n ? -amount : amount).toString();
|
|
645
|
-
|
|
646
|
-
const hasFraction = decimals > 0;
|
|
647
|
-
const integerPart =
|
|
648
|
-
s.length > decimals ? s.slice(0, s.length - decimals) : "0";
|
|
649
|
-
const fractional = hasFraction
|
|
650
|
-
? s.length > decimals
|
|
651
|
-
? s.slice(s.length - decimals)
|
|
652
|
-
: s.padStart(decimals, "0")
|
|
653
|
-
: "";
|
|
654
|
-
|
|
655
|
-
const groupedInt = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
656
|
-
|
|
657
|
-
if (!hasFraction) return sign + groupedInt;
|
|
658
|
-
if (/^0+$/.test(fractional)) return sign + groupedInt;
|
|
659
|
-
|
|
660
|
-
const leadingZeros = fractional.match(/^0+/)?.[0].length ?? 0;
|
|
661
|
-
|
|
662
|
-
if (leadingZeros >= 3) {
|
|
663
|
-
// Use subscript notation for numbers with 3+ leading zeros
|
|
664
|
-
const rest = fractional.slice(leadingZeros);
|
|
665
|
-
const truncatedRest = rest.slice(0, subscriptDecimals);
|
|
666
|
-
const compressedFrac = `0${toSubscript(leadingZeros)}${truncatedRest}`;
|
|
667
|
-
return `${sign}${groupedInt}.${compressedFrac}`;
|
|
668
|
-
}
|
|
460
|
+
## π Working Examples
|
|
669
461
|
|
|
670
|
-
|
|
671
|
-
const truncatedFrac = fractional.slice(0, standardDecimals);
|
|
672
|
-
const trimmedFrac = truncatedFrac.replace(/0+$/, ""); // Remove trailing zeros
|
|
462
|
+
The SDK includes complete working examples to help you get started:
|
|
673
463
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
464
|
+
### [`demo-agent.ts`](./examples/demo-agent.ts)
|
|
465
|
+
An agent demonstrating all main features of the sdk:
|
|
466
|
+
- Memory operations (set, get, list, delete)
|
|
467
|
+
- Polymarket integration (market orders, position redemption)
|
|
468
|
+
- Swidge
|
|
469
|
+
- Self sending using sign and send
|
|
470
|
+
- Unified logging patterns
|
|
677
471
|
|
|
678
|
-
|
|
679
|
-
const executionFunction: ExecutionFunctionContract = async (request) => {
|
|
680
|
-
console.log(`π Agent execution called for session ${request.sessionId}`);
|
|
472
|
+
This is a great starting point for building your own agent.
|
|
681
473
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
"π Starting Agent SDK v1.0 comprehensive demo -- live test",
|
|
691
|
-
});
|
|
692
|
-
|
|
693
|
-
const PEPE_ARB = "0x25d887Ce7a35172C62FeBFD67a1856F20FaEbB00" as `0x${string}`;
|
|
694
|
-
const pepeBalance = await getEvmTokenBalance({
|
|
695
|
-
rpcUrl: "https://arb-mainnet.g.alchemy.com/v2/<YOUR_API_KEY>",
|
|
696
|
-
address: request.sessionWalletAddress,
|
|
697
|
-
token: PEPE_ARB,
|
|
698
|
-
});
|
|
699
|
-
|
|
700
|
-
const pepeBalanceFormatted = formatTokenAmount(
|
|
701
|
-
BigInt(pepeBalance.amount),
|
|
702
|
-
pepeBalance.decimals
|
|
703
|
-
);
|
|
704
|
-
|
|
705
|
-
await sdk.sendLog({
|
|
706
|
-
type: "observe",
|
|
707
|
-
shortMessage: `PEPE Balance (Arbitrum): ${pepeBalanceFormatted} PEPE`,
|
|
708
|
-
});
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
const abi = parseAbi([
|
|
712
|
-
"function transfer(address to, uint256 value) returns (bool)",
|
|
713
|
-
]);
|
|
714
|
-
const demoAmount = BigInt(pepeBalance.amount) / 100n;
|
|
715
|
-
|
|
716
|
-
const data = encodeFunctionData({
|
|
717
|
-
abi,
|
|
718
|
-
functionName: "transfer",
|
|
719
|
-
args: [request.sessionWalletAddress as `0x${string}`, demoAmount],
|
|
720
|
-
});
|
|
721
|
-
|
|
722
|
-
// Demo custom contract call
|
|
723
|
-
await sdk.signAndSend({
|
|
724
|
-
network: "ethereum:42161",
|
|
725
|
-
request: {
|
|
726
|
-
toAddress: PEPE_ARB,
|
|
727
|
-
data: data,
|
|
728
|
-
value: "0", // No ETH value for token transfers
|
|
729
|
-
},
|
|
730
|
-
message: "Custom PEPE transfer demo",
|
|
731
|
-
});
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
await sdk.sendLog({
|
|
735
|
-
type: "observe",
|
|
736
|
-
shortMessage:
|
|
737
|
-
"β
Agent SDK v1.0 comprehensive demo completed successfully!",
|
|
738
|
-
});
|
|
739
|
-
|
|
740
|
-
return { success: true };
|
|
741
|
-
} catch (error) {
|
|
742
|
-
console.error("π₯ Agent execution error:", error);
|
|
743
|
-
|
|
744
|
-
await sdk.sendLog({
|
|
745
|
-
type: "error",
|
|
746
|
-
shortMessage: `Agent execution error: ${
|
|
747
|
-
error instanceof Error ? error.message : "Unknown error"
|
|
748
|
-
}`,
|
|
749
|
-
});
|
|
750
|
-
|
|
751
|
-
// Optional - Return detailed error information for the CLI to display
|
|
752
|
-
return {
|
|
753
|
-
success: false,
|
|
754
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
755
|
-
errorDetails: {
|
|
756
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
757
|
-
message: error instanceof Error ? error.message : String(error),
|
|
758
|
-
stack: error instanceof Error ? error.stack : undefined,
|
|
759
|
-
timestamp: new Date().toISOString(),
|
|
760
|
-
sessionId: request.sessionId,
|
|
761
|
-
agentSlug: (globalThis as any).CIRCUIT_AGENT_SLUG || "unknown",
|
|
762
|
-
errorType: "AGENT_EXECUTION_ERROR",
|
|
763
|
-
},
|
|
764
|
-
};
|
|
765
|
-
}
|
|
766
|
-
};
|
|
474
|
+
### [`examples/kitchen-sink.ts`](./examples/kitchen-sink.ts)
|
|
475
|
+
A comprehensive script showing all SDK features:
|
|
476
|
+
- Manual AgentContext instantiation for testing
|
|
477
|
+
- All memory operations with examples
|
|
478
|
+
- Cross-chain swaps with Swidge (quotes, execution, price impact checks)
|
|
479
|
+
- Polymarket operations (buy/sell orders, redemptions)
|
|
480
|
+
- Custom transactions with signAndSend
|
|
481
|
+
- Logging patterns (standard, error, debug)
|
|
767
482
|
|
|
768
|
-
|
|
769
|
-
const sdk = new AgentSdk({
|
|
770
|
-
sessionId: request.sessionId,
|
|
771
|
-
testing: true,
|
|
772
|
-
});
|
|
483
|
+
Run this script to experiment with the SDK before deploying your agent.
|
|
773
484
|
|
|
774
|
-
|
|
775
|
-
await sdk.sendLog({
|
|
776
|
-
type: "observe",
|
|
777
|
-
shortMessage: "π Agent stopping with new SDK v1.0",
|
|
778
|
-
});
|
|
779
|
-
return { success: true };
|
|
780
|
-
} catch (error) {
|
|
781
|
-
console.error("π₯ Agent stop error:", error);
|
|
782
|
-
|
|
783
|
-
return {
|
|
784
|
-
success: false,
|
|
785
|
-
error: error instanceof Error ? error.message : "Unknown error",
|
|
786
|
-
errorDetails: {
|
|
787
|
-
name: error instanceof Error ? error.name : "Unknown",
|
|
788
|
-
message: error instanceof Error ? error.message : String(error),
|
|
789
|
-
stack: error instanceof Error ? error.stack : undefined,
|
|
790
|
-
timestamp: new Date().toISOString(),
|
|
791
|
-
sessionId: request.sessionId,
|
|
792
|
-
agentSlug: (globalThis as any).CIRCUIT_AGENT_SLUG || "unknown",
|
|
793
|
-
},
|
|
794
|
-
};
|
|
795
|
-
}
|
|
796
|
-
};
|
|
485
|
+
## π― Key Takeaways
|
|
797
486
|
|
|
798
|
-
|
|
799
|
-
|
|
487
|
+
1. **Single Interface**: Everything you need is in the `AgentContext` object
|
|
488
|
+
2. **No Return Values**: Functions return `void` - uncaught errors are handled automatically by circuit
|
|
489
|
+
3. **Unified Logging**: `agent.log()` with simple `debug` and `error` flags
|
|
490
|
+
4. **Check `.success`**: All SDK methods return response objects with `.success` and `.error_message`
|
|
800
491
|
|
|
801
|
-
|
|
802
|
-
export default agent.getWorkerExport();
|
|
492
|
+
## π Additional Resources
|
|
803
493
|
|
|
804
|
-
|
|
494
|
+
- [Circuit CLI](https://github.com/circuitorg/agents-cli) - Deploy and manage agents
|
|
495
|
+
- [`demo-agent.ts`](./examples/demo-agent.ts) - Production-ready agent template
|
|
496
|
+
- [`examples/kitchen-sink.ts`](./examples/kitchen-sink.ts) - Comprehensive SDK demo
|