npm package: @intentfi/agent-sdk
Description: TypeScript SDK and CLI for the IntentFi agentic DeFi gateway — create, monitor, and execute intent-based workflows via REST or MCP
Author: IntentFi
Latest version: 0.1.2

# @intentfi/agent-sdk

> Execute complex DeFi strategies in one sentence.

IntentFi turns natural-language intent into fully orchestrated on-chain transactions — route planning, multi-step sequencing, cross-chain bridging, token approvals, and error recovery, handled for you. Say what you want; IntentFi figures out how.

This package provides the TypeScript SDK and CLI for agent integration via REST or MCP (Model Context Protocol).

## Why IntentFi

- **One sentence, multiple protocols.** Combine swaps, bridges, lending, and yield positions into a single intent. `swap ETH to USDC, then lend all on Aave` is one API call — IntentFi plans the route and sequences every step.
- **No routing logic required.** You don't choose DEXs, bridge providers, or gas parameters. IntentFi selects optimal routes across supported protocols and chains.
- **Stateless for your agent.** Create a workflow, poll its state, follow `nextAction.type`, act. No local state to manage, no complex retry logic.
- **Built-in safety.** Dry-run mode, manifest verification before signing, max-value guards, and idempotent retries — test safely, execute confidently.

## Installation

```bash
npm install @intentfi/agent-sdk
```

For the CLI globally:

```bash
npm install -g @intentfi/agent-sdk
```

## Common Agent Scenarios

These are real workflows you can run through IntentFi today:

| Scenario | Intent | What IntentFi handles for you |
|----------|--------|-------------------------------|
| Portfolio rebalance | `swap 50% ETH to USDC on Arbitrum, then lend all on Aave` | Route selection, swap execution, Aave approval + supply, step sequencing |
| Yield farming setup | `lend 1000 USDC on Aave Arbitrum, borrow 0.5 WETH, then swap to PT-WEETH on Pendle` | Three-protocol orchestration across Aave + Pendle in one workflow |
| Cross-chain move | `bridge all USDC from Base to Arbitrum, then lend on Aave` | Bridge route selection, wait for bridge confirmation, auto-proceed to lending |
| Token consolidation | `sweep all tokens into USDC on Arbitrum` | Identifies all token balances on chain, plans optimal swap routes, converts to your target |
| Leveraged position | `loop 1 WETH on Aave Arbitrum: 3 loops, target 70% LTV` | Recursive supply-borrow cycles with automatic LTV management |

## Quick Start

### As a Library

```typescript
import { IntentFiClient } from "@intentfi/agent-sdk";

const client = new IntentFiClient({
  baseUrl: "https://agentic.intentfi.io",
  apiKey: process.env.INTENTFI_API_KEY,
  transport: "rest", // or "mcp"
});

// Create a workflow from a natural-language intent
const workflow = await client.createWorkflow({
  intent: "swap 0.01 ETH to USDC on Base",
  chainId: 8453,
});

// Monitor workflow progress
const status = await client.getWorkflow({
  workflowId: workflow.workflowId,
  waitMs: 120000,
});
```

### As a CLI

```bash
# Set signer key from a secure source (recommended before auth/execute)
read -s INTENTFI_PRIVATE_KEY && export INTENTFI_PRIVATE_KEY

# Authenticate (one-time SIWE flow; reads INTENTFI_PRIVATE_KEY)
intentfi auth siwe --chain-id 8453

# Create and run a workflow
intentfi run "swap 0.01 ETH to USDC on Base" --chain-id 8453

# Watch workflow progress
intentfi watch <workflowId>

# Execute (prepare + sign + submit transactions; reads INTENTFI_PRIVATE_KEY)
intentfi execute <workflowId> --dry-run false
```

## Authentication

Agents authenticate by signing a SIWE (Sign-In with Ethereum) message with their wallet to mint an API key.

1. `POST /agent/v1/auth/siwe/challenge` — request a nonce.
2. Sign the returned message with your wallet.
3. `POST /agent/v1/auth/siwe/mint-key` — exchange signature for an API key. **Scopes are required** — provide at least one from: `workflow:create`, `workflow:read`, `batch:prepare`, `batch:submit`, `limits:read`.
4. **Store the key persistently** (env var, secrets manager, config file). It is long-lived and reusable — you only need to authenticate once.
5. Send `x-api-key: <key>` on all subsequent requests.

`Authorization: Bearer ifak_...` is also accepted.

## Payments (x402)

Some gateway routes may require payment via the x402 protocol. The SDK handles this automatically when you provide an `X402PaymentManager`:

```typescript
import { IntentFiClient, DefaultX402PaymentManager } from "@intentfi/agent-sdk";

const client = new IntentFiClient({
  baseUrl: "https://agentic.intentfi.io",
  apiKey: process.env.INTENTFI_API_KEY,
  transport: "rest",
  paymentManager: new DefaultX402PaymentManager({
    schemes: {
      exact: async ({ context }) => {
        // Sign and return payment payload for context.requirement
        return { /* signed payment fields */ };
      },
    },
    approve: ({ context }) => {
      // Optional gate: return false to reject a payment request
      return true;
    },
    policy: {
      maxAmountAtomic: 1000000n,        // optional: max per-payment
      allowedNetworks: ["base-sepolia"], // optional: restrict networks
    },
  }),
});
```

When configured:
- **REST:** the client catches `402` responses, signs payment, and retries with `PAYMENT-SIGNATURE` automatically.
- **MCP:** the client catches payment challenge tool results and retries with `_meta["x402/payment"]` automatically.
- **Settlement:** if your payment manager implements `onSettlement`, it receives confirmation with the on-chain transaction hash.

Follow-up coverage:
- Paid route support includes create + follow-up workflow operations (`getWorkflow`, `getActiveSubmissionContext`, prepare/submit/offchain submit/report/cancel), so agents can run x402-only end to end on those routes.
- For paid follow-up reads, the SDK sends stable idempotency keys automatically:
  - REST: `x-intentfi-paid-idempotency-key`
  - MCP: `_meta["x402/idempotency-key"]`

CLI note:
- For CLI x402 payment retries, configure `--x402-payer` and a signing key via `--x402-private-key` or `INTENTFI_X402_PRIVATE_KEY` (fallbacks: `INTENTFI_PRIVATE_KEY`, `AGENT_E2E_PRIVATE_KEY`).

If no `paymentManager` is set, payable routes that require payment will throw with `PAYMENT_REQUIRED`.

### x402 Types

The SDK exports these types for custom payment manager implementations:

- `X402PaymentManager` — interface: `buildPaymentPayload(...)`, `onSettlement?(...)`
- `X402PaymentRequired` — decoded payment challenge from the gateway
- `X402PaymentRequirement` — a single accepted payment option (scheme, network, amount, asset, payTo)
- `X402PaymentPayload` — signed payment sent back to the gateway
- `X402SettlementResponse` — settlement confirmation (success, transaction, payer)
- `X402PaymentApproval` — optional approval callback signature
- `X402PaymentPolicy` — optional policy constraints (maxAmountAtomic, allowedNetworks)
- `DefaultX402PaymentManager` — default implementation that delegates to per-scheme handlers

## SDK Methods

**Authentication:**
- `requestSiweChallenge({ address, walletType, chainId })`
- `mintApiKeyWithSiwe({ message, signature, walletType, scopes, label, expiresAtMs })`

**REST Workflow:**
- `createWorkflow({ intent, operationId, chainId })`
- `getWorkflow({ workflowId, waitMs })`
- `prepareActive({ workflowId, requestId, waitMs })`
- `getActiveSubmissionContext({ workflowId })`
- `submitActiveTransactions({ workflowId, requestId, manifestHash, transactions, waitMs })`
- `submitActiveSendCalls({ workflowId, requestId, bundleId, manifestHash, walletType, waitMs })`

**MCP:**
- `mcpInitialize()`
- `mcpToolCall(name, args, { stream? })`

## CLI Commands

```bash
intentfi auth siwe                    # Authenticate and mint API key
intentfi run "<intent>"               # Create and start a workflow
intentfi watch <workflowId>           # Watch workflow progress
intentfi execute <workflowId>         # Full execution (prepare + sign + submit)
```

**Global options:**
- `--base-url <url>` — API URL (default: `https://agentic.intentfi.io`)
- `--api-key <key>` — API key (or set `INTENTFI_API_KEY`)
- `--transport rest|mcp` — Transport mode (default: `rest`)

**Execute options:**
- `--dry-run true|false` — Dry run mode (default: `true`)
- `--max-value-wei <wei>` — Max transaction value guard
- `--wait-receipts` — Wait for on-chain receipts
- `--private-key <key>` — Optional local override for debugging; prefer `INTENTFI_PRIVATE_KEY`

For production agents, load signer secrets from your environment or secrets manager and avoid passing private keys as CLI arguments.

## Supported Intents

Agents send a plain natural-language string. There are no structured fields to fill out — just say what you want.

| Category | Intents | Example |
|----------|---------|---------|
| Trading | **Swap** | `swap 0.5 ETH for USDC on Arbitrum` |
| Trading | **Bridge** | `bridge 100 USDC from Arbitrum to Base` |
| Lending | **Lend / Supply** | `lend 1000 USDC on Aave Arbitrum` |
| Lending | **Borrow** | `borrow 500 USDC on Aave Arbitrum at variable rate` |
| Lending | **Repay** | `repay all WETH debt on Aave Base` |
| Advanced | **Loop / Leverage** | `loop 1 WETH on Aave Arbitrum: 3 loops, target 70% LTV` |
| Advanced | **Pendle Yield** | `swap 0.5 WETH for PT-WEETH on Pendle Arbitrum` |
| Utility | **Sweep** | `sweep all tokens into USDC on Arbitrum` |
| Compose | **Multi-Step** | `swap ETH to USDC on Arbitrum, then lend all on Aave` |

Amounts accept: absolute (`100`), percentage (`50%`, `all`), or dollar value (`$100 worth`).

## Supported Chains

| Chain | Chain ID |
|-------|----------|
| Ethereum | 1 |
| Optimism | 10 |
| BNB Chain | 56 |
| Polygon | 137 |
| Base | 8453 |
| Arbitrum | 42161 |
| Berachain | 80094 |

## Agent Integration Paths

| Transport | Endpoint | Best For |
|-----------|----------|----------|
| REST API | `https://agentic.intentfi.io/agent/v1` | Direct HTTP integration |
| MCP | `https://agentic.intentfi.io/mcp` | LLM tool-use (Model Context Protocol) |
| SDK / CLI | `@intentfi/agent-sdk` | TypeScript agents and terminal workflows |

## Environment Variables

| Variable | Description |
|----------|-------------|
| `INTENTFI_API_KEY` | API key for authenticated requests |
| `INTENTFI_BASE_URL` | Gateway base URL |
| `INTENTFI_TRANSPORT` | Transport mode (`rest` or `mcp`) |
| `INTENTFI_PRIVATE_KEY` | Preferred signer key source for CLI `auth siwe` and non-dry-run `execute` |

## Links

- Web app: [https://intentfi.io](https://intentfi.io)
- Support and feedback: [https://intentfi.io](https://intentfi.io) (Feedback button)
- [Full Agent Reference](https://intentfi.io/llms-full.txt)
- [OpenAPI Spec](https://intentfi.io/agent/v1/openapi.json)
- [Agent Discovery](https://intentfi.io/.well-known/agent.json)

## License

Apache-2.0