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

# Agents & Automation

> Build autonomous onchain agents that act on behalf of users

Build AI agents, trading bots, and automated systems that execute onchain transactions for users—securely, with user-defined limits, across any chain.

## The Agent Problem

Today's onchain agents face a fundamental challenge: **they need to transact, but users don't trust them with private keys.**

Traditional solutions are broken:

| Approach           | Problem                            |
| ------------------ | ---------------------------------- |
| Share private keys | Users won't do it (rightfully so)  |
| Custodial wallets  | Regulatory nightmare, trust issues |
| Approve max tokens | One exploit drains everything      |
| Sign every action  | Defeats the purpose of automation  |

## Smart Sessions: The Solution

Smart Sessions let users grant **scoped, time-limited, revocable permissions** to your agent. The agent can act autonomously within those bounds—enforced by smart contracts, not trust.

```
User grants permission → Agent acts within limits → Smart contract enforces rules
```

### What Users Control

<CardGroup cols={2}>
  <Card title="Which contracts" icon="file-contract">
    Agent can only call whitelisted addresses
  </Card>

  <Card title="Which functions" icon="code">
    Specific function selectors, not general access
  </Card>

  <Card title="How much" icon="coins">
    Spending caps per action and total
  </Card>

  <Card title="How long" icon="clock">
    Automatic expiration of permissions
  </Card>
</CardGroup>

## Agent Types & Use Cases

### 🤖 AI Trading Agents

Autonomous agents that execute trades based on market signals.

```typescript theme={null}
// Agent can only swap on Uniswap
// Max $500 per trade and Max $4000 limit
// Expires in 7 days

const functionSignature = toFunctionSelector(
  getAbiItem({ abi: UniswapRouterAbi, name: "exactInputSingle" })
);

const actions = mcNexus.buildSessionAction({
  type: "custom",
  data: {
    chainIds: [8453, 10],
    contractAddress: UNISWAP_ROUTER,
    functionSignature,
    policies: [
      {
        type: "timeframe",
        validAfter, // unix-timestamp when policy becomes active
        validUntil  // unix-timestamp when policy expires
      },
      {
        type: "universal",
        rules: [
          {
            condition: "lessThanOrEqual",
            calldataOffset: calldataArgument(2),
            comparisonValue: parseUnits("500", 6),
            isLimited: true,
            usage: { limit: parseUnits("4000", 6) }
          }
        ],
      }
    ]
  }
});

const permissions = { actions };
```

**Best policies:** Universal Action (spending limits) + Timeframe

***

### 📈 Yield Optimization Agents

Move funds to highest-yielding opportunities across protocols and chains.

```typescript theme={null}
// Agent can deposit/withdraw from approved protocols
// Morpho, Aave, Compound on Base, Optimism, Arbitrum
// Max 10,000 USDC total exposure

const [morphoAction] = mcNexus.buildSessionAction({ 
  type: "custom", data: { chainIds: [8453], contractAddress: MORPHO_BASE, ... } 
});

const [aaveAction] = mcNexus.buildSessionAction({ 
  type: "custom", data: { chainIds: [10], contractAddress: AAVE_OP, ... } 
});

const [compoundAction] = mcNexus.buildSessionAction({ 
  type: "custom", data: { chainIds: [42161], contractAddress: COMPOUND_ARB, ... } 
});

const permissions = {
  actions: [morphoAction, aaveAction, compoundAction]
};
```

**Best policies:** Usage Limit + No other restrictive policies (for trusted protocols)

***

### 🔄 Portfolio Rebalancing Agents

Maintain target allocations by automatically trading when drift exceeds threshold.

```typescript theme={null}
// Agent can swap between ETH, BTC, stables
// Only rebalance when >5% drift
// Max 2% of portfolio per rebalance
```

**Best policies:** Universal Action (parameter rules for amounts)

***

### 💳 Subscription & Payments Agents

Automate recurring payments, subscriptions, and payroll.

```typescript theme={null}
// Agent can send up to 100 USDC
// Only to merchant address 0x...
// expires in 1 year and only 12 payments are allowed

// Chargeable on day one of the month
const dayOneTimeframePolicy = mcNexus.buildActionPolicy({
  type: "timeframe",
  validAfter: ..., // unix-timestamp Eg: 1-1-2026 00:00:00 in unix timestamp
  validUntil: ...  // unix-timestamp Eg: 1-1-2026 23:59:59 in unix timestamp
});

// Used only once per month
const usagePolicy = mcNexus.buildActionPolicy({
  type: "usageLimit",
  limit: 1n
});

// Only specific recipient and specific amount
const paymentPolicy = mcNexus.buildActionPolicy({
  type: "universal",
  rules: [
    // Only send to merchant
    {
      condition: "equal",
      calldataOffset: calldataArgument(1),
      comparisonValue: MERCHANT
    },
    // Max 100 USDC per payment
    {
      condition: "lessThanOrEqual",
      calldataOffset: calldataArgument(2),
      comparisonValue: parseUnits("100", 6),
    }
  ],
  // Configure spending limit for native token
  valueLimitPerUse: 0n,
});

const monthOnePaymentAction = mcNexus.buildSessionAction({
  type: "transfer",
  data: {
    chainIds: [8453, 10],
    contractAddress: USDC,
    policies: [dayOneTimeframePolicy, usagePolicy, paymentPolicy]
  }
});

// 10 similar actions for 10 months

const monthTwelvePaymentAction = mcNexus.buildSessionAction({
  type: "transfer",
  data: {
    chainIds: [8453, 10],
    contractAddress: USDC,
    policies: [dayOneTimeframePolicy, usagePolicy, paymentPolicy]
  }
});

// 12 actions which can be executed only once per month on day one for a year.

const permissions = {
  actions: [monthOnePaymentAction, ..., monthTwelvePaymentAction]
};
```

**Best policies:** Universal Action + Usage Limit + Timeframe

***

### 🎮 Gaming & Social Agents

Automate in-game actions, social interactions, or NFT operations.

```typescript theme={null}
// Agent can mint, transfer, and interact with game contract
// No value transfers allowed
// 1000 actions per day
```

**Best policies:** Usage Limit + No other restrictive policy

***

### 🏦 Treasury Management Agents

Institutional-grade automated treasury operations.

```typescript theme={null}
// Agent can move funds between approved vaults
// Requires 2-of-3 multisig for amounts over $100k
// Full audit trail
```

**Best policies:** Universal Action + custom multisig integration

## Quick Implementation

<Steps>
  <Step title="Generate Agent Key">
    ```typescript theme={null}
    import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";

    const agentKey = generatePrivateKey();
    const agentSigner = privateKeyToAccount(agentKey);
    // Store agentKey securely in your backend
    ```
  </Step>

  <Step title="User Prepares And Enable Permissions">
    ```typescript theme={null}
    const quote = await userClient.getSessionQuote({
      mode: "PREPARE",
      enableSession: {
        redeemer: agentSigner.address,
        actions: [/* your agent's allowed actions */],
        maxPaymentAmount: parseUnits("10", 6),
      },
      simulation: { simulate: true },
      // Can be sponsored if needed
      sponsorship: true,
      feeToken: { address: USDC, chainId: 8453 },
      trigger: {
        tokenAddress: USDC,
        chainId: 8453,
        amount: parseUnits("2", 6),
      },
    });

    if (quote) {
      const { hash } = await userClient.executeSessionQuote(quote);
      await userClient.waitForSupertransactionReceipt({ hash });

      if (quote.sessionDetails) // Store sessionDetails - agent needs this
    }
    ```
  </Step>

  <Step title="Agent Executes">
    ```typescript theme={null}
    // In your agent backend
    const quote = await agentClient.getSessionQuote({
      mode: "USE",
      sessionDetails,
      simulation: { simulate: true },
      feeToken: { address: USDC, chainId: 8453 },
      instructions: [/* agent's action */]
    });

    const { hash } = await agentClient.executeSessionQuote(quote);

    await agentClient.waitForSupertransactionReceipt({ hash });
    ```
  </Step>
</Steps>

## Why Biconomy?

<CardGroup cols={2}>
  <Card title="Multichain Native" icon="globe">
    Single permission works across all chains. No per-chain grants.
  </Card>

  <Card title="Works with EOAs" icon="wallet">
    Users keep their existing wallets. No migration needed.
  </Card>

  <Card title="Gas Abstracted" icon="gas-pump">
    Agents can pay gas in any token or have it sponsored.
  </Card>

  <Card title="On-Chain Enforcement" icon="shield">
    Smart contracts enforce limits. No trust required.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Choose Your Policy" icon="shield" href="/agents-automation/policies">
    Pick the right security model for your agent
  </Card>

  <Card title="Implementation Guide" icon="code" href="/agents-automation/implementation">
    Step-by-step code walkthrough
  </Card>
</CardGroup>
