> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chipipay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# DeFi Intelligence

> AI portfolio advisor with real-time signals, plus on-chain swap execution on Starknet.

Base URL: `https://api.chipipay.com/v1`

## When to use

`/ai/think` and `/ai/execute` work together to power autonomous DeFi agents. Think decides **what** to do; Execute builds the **how**.

|                  | `/ai/think`                                                                            | `/ai/execute`                                                               |
| ---------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| **What it does** | Analyzes a portfolio with live market signals and returns a decision (hold, buy, sell) | Builds unsigned swap calldata from AVNU (Starknet DEX aggregator)           |
| **Best for**     | Autonomous agents, portfolio advisors, risk-managed bots                               | Executing the decision — turning a "buy ETH" signal into a real transaction |
| **Input**        | Portfolio balances + risk score                                                        | Token pair + USD amount + wallet address                                    |
| **Output**       | Structured JSON: action, reason, confidence, risk params                               | Unsigned transaction calls ready to sign and submit                         |
| **Cost**         | Per token (same as /chat)                                                              | \$0.002 flat per call                                                       |

### What you can build

* **Autonomous DeFi agent** — `/think` runs on a schedule (hourly, daily), if it says "buy" → `/execute` builds the swap → your agent signs and submits via session key. Fully automated, gasless.
* **Portfolio advisor app** — Show users a dashboard with AI recommendations. `/think` with their real balances + chosen risk level. They review the suggestion and approve manually.
* **Risk-managed vault** — A smart contract-backed strategy where `/think` enforces risk params (max drawdown, min stablecoins) before any rebalance.
* **Telegram trading bot** — User sends portfolio snapshot, bot calls `/think`, replies with the recommendation and a "execute" button that triggers `/execute`.
* **Yield optimizer** — `/think` includes DeFi yield data from DefiLlama. An agent can compare swap gains vs. yield APY and pick the better move.

<Note>
  `/think` automatically fetches live signals (RSI, MACD, Fear & Greed, yields) — you don't need to call `/signals` first. Just send the portfolio.
</Note>

***

## POST /ai/think

DeFi portfolio advisor. Analyzes your portfolio with real-time market signals (RSI, MACD, Fear & Greed, yields) and returns a structured JSON decision: **hold**, **buy**, or **sell** — with confidence and reasoning.

**Cost:** Per token (same as /chat — the model call is the cost)

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST https://api.chipipay.com/v1/ai/think \
    -H "Authorization: Bearer sk_prod_YOUR_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "haiku",
      "portfolio": {
        "USDC": {"balance": 100, "usd": 100},
        "ETH": {"balance": 0.04, "usd": 88},
        "STRK": {"balance": 500, "usd": 17}
      },
      "riskScore": 7,
      "chain": "starknet"
    }'
  ```

  ```json Response (201) theme={null}
  {
    "decision": {
      "action": "hold",
      "reason": "ETH RSI at 45 (neutral), Fear & Greed at 16 (Extreme Fear). No signal exceeds minSignalStrength threshold of 0.38.",
      "confidence": 0.4
    },
    "riskParams": {
      "riskScore": 7,
      "maxSingleTradePercent": 38,
      "minStablecoinPercent": 15,
      "maxDrawdownPercent": 29.5,
      "minSignalStrength": 0.38,
      "minExpectedGainPercent": 0.57
    },
    "model": "haiku",
    "provider": "anthropic",
    "usage": {"inputTokens": 369, "outputTokens": 102, "totalTokens": 471},
    "cost": {"charged": 0.001231, "currency": "USD"},
    "latencyMs": 1507
  }
  ```
</CodeGroup>

### Request body

| Field       | Type   | Default      | Description                                                                       |
| ----------- | ------ | ------------ | --------------------------------------------------------------------------------- |
| `portfolio` | object | Required     | Token balances and USD values. Keys are symbols, values have `balance` and `usd`. |
| `riskScore` | number | 5            | 1 (ultra conservative) to 10 (max risk). All thresholds scale with this score.    |
| `chain`     | string | `"starknet"` | Chain for yield data in signals.                                                  |
| `model`     | string | `"haiku"`    | Any model from [Models & Pricing](/services/ai-api/models).                       |

### Risk parameter overrides

All optional. Defaults scale linearly with `riskScore`. Override any individual param without affecting others.

| Field                    | Type   | Description                         |
| ------------------------ | ------ | ----------------------------------- |
| `maxSingleTradePercent`  | number | Max % of portfolio per trade        |
| `minStablecoinPercent`   | number | Min % to keep in stablecoins        |
| `maxDrawdownPercent`     | number | Max acceptable drawdown %           |
| `minSignalStrength`      | number | Min signal strength to act (0-1)    |
| `minExpectedGainPercent` | number | Min expected gain to justify a swap |

### How risk scoring works

Risk parameters scale with `riskScore` from conservative (1) to aggressive (10):

| Parameter           | riskScore = 1 | riskScore = 5 | riskScore = 10 |
| ------------------- | ------------- | ------------- | -------------- |
| Max single trade    | 14%           | 30%           | 50%            |
| Min stablecoins     | 45%           | 25%           | 5%             |
| Max drawdown        | 8.5%          | 22.5%         | 40%            |
| Min signal strength | 0.74          | 0.50          | 0.20           |
| Min expected gain   | 1.11%         | 0.75%         | 0.30%          |

<Note>
  The `/think` endpoint automatically injects live market data (signals, yields, Fear & Greed) into the AI prompt. You don't need to fetch signals separately — just send the portfolio and risk score.
</Note>

***

<h2 id="execute-a-swap">
  POST /ai/execute
</h2>

Build unsigned swap calldata from AVNU (Starknet DEX aggregator). Returns the transaction calls — you sign and submit via session key or wallet.

**Cost:** \$0.002 per call (flat, not per token)

<CodeGroup>
  ```bash Request theme={null}
  curl -X POST https://api.chipipay.com/v1/ai/execute \
    -H "Authorization: Bearer sk_prod_YOUR_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "chain": "starknet",
      "action": "swap",
      "from": "USDC",
      "to": "ETH",
      "amountUsd": 10,
      "walletAddress": "0x0189e2ebb955fc19bf37bd8fc0400de24c123363e7955282bcfb99679a773e61",
      "slippage": 0.005
    }'
  ```

  ```json Response (201) theme={null}
  {
    "calls": [
      {
        "contractAddress": "0x033068f6...",
        "entrypoint": "approve",
        "calldata": ["0x...", "0x..."]
      },
      {
        "contractAddress": "0x042ab...",
        "entrypoint": "multi_route_swap",
        "calldata": ["0x...", "0x..."]
      }
    ],
    "quote": {
      "sellToken": "USDC",
      "buyToken": "ETH",
      "sellAmount": "10000000",
      "buyAmount": "4500000000000000",
      "sellAmountUsd": 10.0,
      "buyAmountUsd": 9.98,
      "priceImpactPct": 0.12,
      "route": "AVNU best route"
    },
    "cost": {"charged": 0.002, "currency": "USD"}
  }
  ```
</CodeGroup>

### Request body

| Field           | Type   | Default  | Description                                                       |
| --------------- | ------ | -------- | ----------------------------------------------------------------- |
| `chain`         | string | Required | `"starknet"` (more chains coming soon).                           |
| `action`        | string | Required | `"swap"` (more actions coming soon).                              |
| `from`          | string | Required | Sell token symbol: USDC, ETH, STRK, WBTC, USDT, DAI.              |
| `to`            | string | Required | Buy token symbol: USDC, ETH, STRK, WBTC, USDT, DAI.               |
| `amountUsd`     | number | Required | USD amount to swap (converted to token amount using live prices). |
| `walletAddress` | string | Required | Your Starknet wallet address.                                     |
| `slippage`      | number | 0.005    | Slippage tolerance. Default: 0.5%. Max: 50%.                      |

<Warning>
  `/execute` returns **unsigned calls**. It does NOT submit the transaction.
  You sign with your wallet or session key and submit via the Chipi paymaster (gasless).
  Swaps with more than 3% price impact are rejected.
</Warning>

### Putting it together: Think + Execute

A typical DeFi agent flow:

1. **Think** — send portfolio + risk score, get a decision
2. If decision is `buy` or `sell` → **Execute** — get unsigned swap calldata
3. Sign the calls with your wallet or session key
4. Submit via Chipi's gasless paymaster

```typescript theme={null}
// 1. Get AI decision
const decision = await fetch("https://api.chipipay.com/v1/ai/think", {
  method: "POST",
  headers: { "Authorization": "Bearer sk_prod_YOUR_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({
    portfolio: { USDC: { balance: 100, usd: 100 }, ETH: { balance: 0.04, usd: 88 } },
    riskScore: 7,
  }),
}).then(r => r.json());

// 2. If actionable, build swap calldata
if (decision.decision.action !== "hold") {
  const swap = await fetch("https://api.chipipay.com/v1/ai/execute", {
    method: "POST",
    headers: { "Authorization": "Bearer sk_prod_YOUR_KEY", "Content-Type": "application/json" },
    body: JSON.stringify({
      chain: "starknet",
      action: "swap",
      from: "USDC",
      to: "ETH",
      amountUsd: 10,
      walletAddress: "0x...",
    }),
  }).then(r => r.json());

  // 3. Sign swap.calls with your wallet and submit
  console.log("Calls to sign:", swap.calls);
}
```
