@agent-shield/sdk 0.1.4 → 0.1.6

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 (2) hide show
  1. package/README.md +146 -31
  2. package/package.json +19 -8
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # @agent-shield/sdk
2
2
 
3
- TypeScript SDK for AgentShield — permission-guarded DeFi access for AI agents on Solana.
3
+ TypeScript SDK for AgentShield — permission-guarded DeFi access for AI agents on Solana. This is the **Level 3 (on-chain vault)** tier of AgentShield's security model, providing cryptographic guarantees via PDA vaults, on-chain policy enforcement, and atomic transaction composition.
4
+
5
+ For most use cases, start with [`@agent-shield/solana`](https://www.npmjs.com/package/@agent-shield/solana) (Level 1 — client-side wrapper). Upgrade to this SDK when you need on-chain enforcement that cannot be bypassed even by compromised agent software.
4
6
 
5
7
  ## Installation
6
8
 
@@ -55,27 +57,53 @@ const sig = await client.executeJupiterSwap({
55
57
  });
56
58
  ```
57
59
 
60
+ ## On-Chain Account Model
61
+
62
+ AgentShield uses 4 PDA account types:
63
+
64
+ | Account | Seeds | Description |
65
+ |---------|-------|-------------|
66
+ | **AgentVault** | `[b"vault", owner, vault_id]` | Holds owner/agent pubkeys, vault status, fee destination |
67
+ | **PolicyConfig** | `[b"policy", vault]` | Spending caps, token/protocol whitelists, leverage limits |
68
+ | **SpendTracker** | `[b"tracker", vault]` | Rolling 24h spend entries + bounded audit log (max 50 txs) |
69
+ | **SessionAuthority** | `[b"session", vault, agent]` | Ephemeral PDA for atomic transaction validation (expires after 20 slots) |
70
+
71
+ ## Instruction Composition Pattern
72
+
73
+ The SDK uses **atomic multi-instruction transactions** to avoid Solana's 4-level CPI depth limit:
74
+
75
+ ```
76
+ Transaction = [
77
+ SetComputeUnitLimit(1_400_000),
78
+ ValidateAndAuthorize, // AgentShield: check policy, create session PDA
79
+ ...DeFi instructions, // Jupiter swap / Flash Trade open / etc.
80
+ FinalizeSession // AgentShield: audit, fees, close session PDA
81
+ ]
82
+ ```
83
+
84
+ All instructions succeed or fail atomically. If the DeFi instruction fails, the session is never finalized and no spend is recorded.
85
+
58
86
  ## API Reference
59
87
 
60
88
  ### Vault Management
61
89
 
62
- | Method | Description |
63
- |--------|-------------|
64
- | `createVault(params)` | Create a new vault with policy, tracker, and fee destination |
65
- | `deposit(vault, mint, amount)` | Deposit SPL tokens into the vault |
66
- | `registerAgent(vault, agent)` | Register an agent signing key on the vault |
67
- | `updatePolicy(vault, params)` | Update policy fields (owner only) |
68
- | `revokeAgent(vault)` | Freeze the vault kill switch |
69
- | `reactivateVault(vault, newAgent?)` | Unfreeze and optionally rotate agent key |
70
- | `withdraw(vault, mint, amount)` | Withdraw tokens to owner (owner only) |
71
- | `closeVault(vault)` | Close vault and reclaim rent |
90
+ | Method | Description | Signer |
91
+ |--------|-------------|--------|
92
+ | `createVault(params)` | Create a new vault with policy, tracker, and fee destination | Owner |
93
+ | `deposit(vault, mint, amount)` | Deposit SPL tokens into the vault | Owner |
94
+ | `registerAgent(vault, agent)` | Register an agent signing key on the vault | Owner |
95
+ | `updatePolicy(vault, params)` | Update policy fields (partial update — only set fields change) | Owner |
96
+ | `revokeAgent(vault)` | Freeze the vault (kill switch) | Owner |
97
+ | `reactivateVault(vault, newAgent?)` | Unfreeze vault and optionally rotate agent key | Owner |
98
+ | `withdraw(vault, mint, amount)` | Withdraw tokens to owner | Owner |
99
+ | `closeVault(vault)` | Close vault and reclaim rent | Owner |
72
100
 
73
101
  ### Permission Engine
74
102
 
75
- | Method | Description |
76
- |--------|-------------|
77
- | `authorizeAction(vault, params)` | Validate an agent action against policy and create a session |
78
- | `finalizeSession(vault, agent, success, ...)` | Close session, record audit, collect fees |
103
+ | Method | Description | Signer |
104
+ |--------|-------------|--------|
105
+ | `authorizeAction(vault, params)` | Validate agent action against policy, create session PDA | Agent |
106
+ | `finalizeSession(vault, agent, success, ...)` | Close session, record audit, collect fees | Agent |
79
107
 
80
108
  ### Transaction Composition
81
109
 
@@ -94,7 +122,7 @@ These methods build atomic transactions in the pattern `[ValidateAndAuthorize, D
94
122
  |--------|-------------|
95
123
  | `getJupiterQuote(params)` | Fetch a swap quote from Jupiter V6 API |
96
124
  | `jupiterSwap(params)` | Build an unsigned `VersionedTransaction` for a Jupiter swap |
97
- | `executeJupiterSwap(params, signers?)` | Quote, compose, sign, send, and confirm |
125
+ | `executeJupiterSwap(params, signers?)` | Quote, compose, sign, send, and confirm in one call |
98
126
 
99
127
  ### Flash Trade Integration
100
128
 
@@ -120,11 +148,12 @@ const [sessionPDA] = client.getSessionPDA(vaultPDA, agent);
120
148
  ### Account Fetchers
121
149
 
122
150
  ```typescript
151
+ // Fetch by owner + vault ID
123
152
  const vault = await client.fetchVault(owner, vaultId);
124
153
  const policy = await client.fetchPolicy(vaultPDA);
125
154
  const tracker = await client.fetchTracker(vaultPDA);
126
155
 
127
- // Or fetch by address directly
156
+ // Fetch by PDA address directly
128
157
  const vault = await client.fetchVaultByAddress(vaultPDA);
129
158
  const policy = await client.fetchPolicyByAddress(policyPDA);
130
159
  const tracker = await client.fetchTrackerByAddress(trackerPDA);
@@ -141,15 +170,28 @@ const tracker = await client.fetchTrackerByAddress(trackerPDA);
141
170
 
142
171
  ### Account Types
143
172
 
144
- - **`AgentVaultAccount`** — owner, agent, feeDestination, vaultId, status, stats
145
- - **`PolicyConfigAccount`** — caps, whitelists, leverage limits, fee BPS
146
- - **`SpendTrackerAccount`** — rolling spends, recent transactions
147
- - **`SessionAuthorityAccount`** — ephemeral session with action type and expiry
173
+ - **`AgentVaultAccount`** — owner, agent, feeDestination, vaultId, status, stats (totalTransactions, totalVolume)
174
+ - **`PolicyConfigAccount`** — dailySpendingCap, maxTransactionSize, allowedTokens, allowedProtocols, maxLeverageBps, maxConcurrentPositions, developerFeeRate
175
+ - **`SpendTrackerAccount`** — spendEntries (rolling), recentTransactions (audit log, max 50)
176
+ - **`SessionAuthorityAccount`** — vault, agent, actionType, expiresAt
148
177
 
149
178
  ### Enums
150
179
 
151
- - **`VaultStatus`** — `{ active: {} }`, `{ frozen: {} }`, `{ closed: {} }`
152
- - **`ActionType`** — `{ swap: {} }`, `{ openPosition: {} }`, `{ closePosition: {} }`, `{ increasePosition: {} }`, `{ decreasePosition: {} }`, `{ deposit: {} }`, `{ withdraw: {} }`
180
+ ```typescript
181
+ // Vault status
182
+ VaultStatus.active // Normal operation
183
+ VaultStatus.frozen // Kill switch activated
184
+ VaultStatus.closed // Vault closed
185
+
186
+ // Action types (for validation + audit)
187
+ ActionType.swap
188
+ ActionType.openPosition
189
+ ActionType.closePosition
190
+ ActionType.increasePosition
191
+ ActionType.decreasePosition
192
+ ActionType.deposit
193
+ ActionType.withdraw
194
+ ```
153
195
 
154
196
  ## Constants
155
197
 
@@ -164,18 +206,91 @@ import {
164
206
 
165
207
  ## Architecture
166
208
 
167
- The SDK uses **instruction composition** rather than CPI wrapping. This avoids Solana's 4-level CPI depth limit and keeps the compute budget manageable:
209
+ ```
210
+ Owner creates vault with policy → Agent operates within policy constraints
211
+
212
+ ┌─────────────────────────────────────────────────────────────┐
213
+ │ Transaction (atomic — all succeed or all revert) │
214
+ │ │
215
+ │ 1. SetComputeUnitLimit(1,400,000) │
216
+ │ 2. ValidateAndAuthorize │
217
+ │ • Check vault status (Active) │
218
+ │ • Check agent is registered │
219
+ │ • Check token/protocol whitelists │
220
+ │ • Check spending cap (rolling 24h) │
221
+ │ • Check leverage limits (if perp) │
222
+ │ • Create SessionAuthority PDA │
223
+ │ 3. DeFi Instruction (Jupiter swap, Flash Trade, etc.) │
224
+ │ 4. FinalizeSession │
225
+ │ • Record in audit log │
226
+ │ • Update open positions counter │
227
+ │ • Collect protocol + developer fees │
228
+ │ • Close SessionAuthority PDA (reclaim rent) │
229
+ └─────────────────────────────────────────────────────────────┘
230
+ ```
231
+
232
+ ### Key Design Decisions
233
+
234
+ | Decision | Rationale |
235
+ |----------|-----------|
236
+ | One agent per vault | Multiple agents = multiple vaults. Simplifies permission model. |
237
+ | Rolling 24h window | Not calendar-day. Prevents edge-case burst at midnight. |
238
+ | Fees at finalization only | Not at authorization. Prevents fee charging on failed txs. |
239
+ | Immutable fee destination | Prevents owner from changing fee recipient after vault creation. |
240
+ | Bounded vectors | Max 10 tokens, 10 protocols, 100 spend entries, 50 audit records. |
241
+
242
+ ### Policy Constraints
243
+
244
+ | Field | Range | Description |
245
+ |-------|-------|-------------|
246
+ | `dailySpendingCap` | `u64` | Max total spend in rolling 24h window |
247
+ | `maxTransactionSize` | `u64` | Max single transaction value |
248
+ | `allowedTokens` | max 10 | Token mint whitelist |
249
+ | `allowedProtocols` | max 10 | Program ID whitelist |
250
+ | `maxLeverageBps` | `u16` | Max leverage in basis points |
251
+ | `maxConcurrentPositions` | `u8` | Max open positions |
252
+ | `developerFeeRate` | 0–500 | Developer fee in BPS (max 5%) |
253
+
254
+ ## Security Model
255
+
256
+ This is **Level 3** in AgentShield's three-tier architecture:
168
257
 
169
258
  ```
170
- Transaction = [
171
- SetComputeUnitLimit(1_400_000),
172
- ValidateAndAuthorize, // AgentShield: check policy, create session
173
- ...DeFi instructions, // Jupiter swap / Flash Trade open / etc.
174
- FinalizeSession // AgentShield: audit, fees, close session
175
- ]
259
+ Level 1: Client-Side Wrapper (@agent-shield/solana)
260
+ → Intercepted signTransaction, client-side policy checks
261
+ Can be bypassed by determined attacker with key access
262
+
263
+ Level 2: TEE-Backed Signing (coming soon)
264
+ → Private keys in Trusted Execution Environment
265
+ → Agent code never touches keys
266
+
267
+ Level 3: On-Chain Vault (this package)
268
+ → PDA vault with on-chain PolicyConfig
269
+ → Cannot be bypassed — policy enforced by Solana validators
270
+ → Cryptographic guarantees via atomic transactions
176
271
  ```
177
272
 
178
- All instructions in the transaction succeed or fail atomically.
273
+ **On-chain enforcement means:**
274
+ - Agent cannot exceed spending caps even if the agent software is compromised
275
+ - Owner can freeze the vault at any time (kill switch)
276
+ - All transactions are audited in the SpendTracker
277
+ - Session PDAs expire after 20 slots (~8 seconds)
278
+ - Fee destination is immutable after creation
279
+
280
+ ## Devnet
281
+
282
+ Program deployed to devnet at: `4ZeVCqnjUgUtFrHHPG7jELUxvJeoVGHhGNgPrhBPwrHL`
283
+
284
+ IDL account: `Ev3gSzxLw6RwExAMpTHUKvn2o9YVULxiWehrHee7aepP`
285
+
286
+ ## Related Packages
287
+
288
+ | Package | Description |
289
+ |---------|-------------|
290
+ | [`@agent-shield/solana`](https://www.npmjs.com/package/@agent-shield/solana) | Client-side wallet wrapper (Level 1) |
291
+ | [`@agent-shield/core`](https://www.npmjs.com/package/@agent-shield/core) | Pure TypeScript policy engine |
292
+ | [`@agent-shield/plugin-solana-agent-kit`](https://www.npmjs.com/package/@agent-shield/plugin-solana-agent-kit) | Solana Agent Kit integration |
293
+ | [`@agent-shield/plugin-elizaos`](https://www.npmjs.com/package/@agent-shield/plugin-elizaos) | ElizaOS integration |
179
294
 
180
295
  ## License
181
296
 
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "@agent-shield/sdk",
3
- "version": "0.1.4",
4
- "description": "TypeScript SDK for AgentShield — AI Agent Financial Middleware on Solana",
3
+ "version": "0.1.6",
4
+ "description": "TypeScript SDK for AgentShield — permission-guarded DeFi access for AI agents on Solana",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
- "files": ["dist", "README.md"],
8
+ "files": [
9
+ "dist",
10
+ "README.md"
11
+ ],
9
12
  "sideEffects": false,
10
- "scripts": {
11
- "build": "tsc",
12
- "clean": "rm -rf dist",
13
- "prepublishOnly": "npm run clean && npm run build"
13
+ "engines": {
14
+ "node": ">=18.0.0"
14
15
  },
15
16
  "dependencies": {
16
17
  "@solana/spl-token": "^0.4.0"
@@ -24,11 +25,21 @@
24
25
  },
25
26
  "devDependencies": {
26
27
  "@types/bn.js": "^5.1.5",
28
+ "@types/chai": "^4.3.11",
29
+ "@types/mocha": "^10.0.6",
30
+ "chai": "^4.4.1",
31
+ "mocha": "^10.3.0",
32
+ "ts-node": "^10.9.2",
27
33
  "typescript": "^5.3.3"
28
34
  },
29
35
  "license": "MIT",
30
36
  "repository": {
31
37
  "type": "git",
32
38
  "url": "https://github.com/agentshield/agent-middleware"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc",
42
+ "clean": "rm -rf dist",
43
+ "test": "mocha --require ts-node/register tests/**/*.test.ts --timeout 30000"
33
44
  }
34
- }
45
+ }