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

# Integration Overview

> Choose the best integration pattern for your use case

## Integration Models

1tx supports **three integration patterns** to fit different use cases and technical requirements:

```mermaid theme={null}
graph TB
    subgraph "Model 1: Direct Blockchain"
        A1[Your App] -->|Web3 Provider| B1[Smart Contracts]
        B1 -->|Transactions| C1[User Wallet]
    end

    subgraph "Model 2: API + External Wallets"
        A2[Your App] -->|REST API| B2[1tx API]
        A2 -->|Web3 Provider| C2[Smart Contracts]
        C2 -->|Transactions| D2[User Wallet]
    end

    subgraph "Model 3: API + Embedded Wallets"
        A3[Your App] -->|REST API| B3[1tx API]
        A3 -->|Privy SDK| C3[Embedded Wallet]
        C3 -->|Session Keys| D3[Smart Contracts]
    end
```

## Model 1: Direct Blockchain Integration

<Card title="Best For" icon="wallet">
  DeFi protocols, wallets, and dApps that want full control over transactions
</Card>

### Overview

* **Integration:** Direct smart contract calls via Web3 library
* **Custody:** User's self-custody wallet (MetaMask, Coinbase Wallet, etc.)
* **Automation:** None - user signs every transaction
* **Complexity:** Medium

### Key Features

<CardGroup cols={2}>
  <Card title="Full Control" icon="gears">
    Complete control over transaction parameters and execution
  </Card>

  <Card title="Self-Custody" icon="shield">
    Users maintain full custody of their assets
  </Card>

  <Card title="No API Keys" icon="key">
    No need for API authentication
  </Card>

  <Card title="On-Chain Only" icon="chain">
    All logic executed on-chain
  </Card>
</CardGroup>

### Use Cases

* DeFi protocols accepting deposits in any token
* Wallet applications offering yield strategies
* dApps with existing Web3 integration
* Smart contract-based automated strategies

### Getting Started

<Steps>
  <Step title="Install Web3 Library">
    ```bash theme={null}
    npm install viem wagmi
    ```
  </Step>

  <Step title="Connect User Wallet">
    ```typescript theme={null}
    import { useConnect } from 'wagmi';

    const { connect, connectors } = useConnect();
    connect({ connector: connectors[0] });
    ```
  </Step>

  <Step title="Call Smart Contracts">
    ```typescript theme={null}
    // Execute a router buy.
    // buy(instrumentId, amount, minDepositedAmount, fastTransfer, maxFee, referralFeeBps, referralWallet)
    await d1txRouter.write.buy([
      instrumentId,
      amount,
      0n,
      false,
      0n,
      0,                                              // referralFeeBps (0-500)
      '0x0000000000000000000000000000000000000000',   // referralWallet
    ]);
    ```
  </Step>
</Steps>

<Card title="Quickstart" icon="book" href="/quickstart">
  Start from the on-chain quickstart example
</Card>

<Card title="Direct Contract Cookbook" icon="terminal" href="/integration/direct-contract-cookbook">
  See `viem` recipes for approve, buy, sell, and cross-chain monitoring
</Card>

***

## Model 2: API + External Wallets

<Card title="Best For" icon="building">
  Exchanges, platforms, and services with existing wallet infrastructure
</Card>

### Overview

* **Integration:** REST API for discovery + smart contracts for execution
* **Custody:** User's self-custody wallet
* **Automation:** None - user must be online to sign
* **Complexity:** Medium-High

### Key Features

<CardGroup cols={2}>
  <Card title="Instrument Discovery" icon="magnifying-glass">
    Query available instruments via API
  </Card>

  <Card title="Rich Metadata" icon="database">
    Access APY, TVL, historical data
  </Card>

  <Card title="Self-Custody" icon="shield">
    Users maintain control of assets
  </Card>

  <Card title="Hybrid Approach" icon="diagram-project">
    Best of API and blockchain
  </Card>
</CardGroup>

### Use Cases

* Centralized exchanges offering DeFi yield
* Investment platforms with portfolio management
* Financial advisors providing DeFi access
* Applications with custom UX requirements

### Getting Started

<Steps>
  <Step title="Get API Key">
    Sign up at [app.1tx.fi/api-keys](https://app.1tx.fi/api-keys)
  </Step>

  <Step title="Query Instruments">
    ```typescript theme={null}
    const response = await fetch('https://api.1tx.fi/api/v1/instruments', {
      headers: { 'x-api-key': apiKey },
    });
    const instruments = await response.json();
    ```
  </Step>

  <Step title="Build the Transaction Bundle">
    ```typescript theme={null}
    const selectedInstrument = instruments.data[0];

    const buildResponse = await fetch('https://api.1tx.fi/api/v1/transactions/buy', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${jwt}`,
        'x-api-key': apiKey,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        userAddress,
        instrumentId: selectedInstrument.instrumentId,
        amountUsdc: '1000.00',
      }),
    });

    const bundle = await buildResponse.json();
    console.log(bundle.transactions);
    ```
  </Step>

  <Step title="Execute and Monitor">
    Send the returned transactions in order with the user's wallet. If `bundle.isCrossChain` is `true`, poll:

    ```typescript theme={null}
    const relay = await fetch(
      `https://api.1tx.fi/api/v1/cctp/relay/tx/${sourceTxHash}`,
      { headers: { 'x-api-key': apiKey } }
    );
    ```

    until the returned status becomes `success` or `failed`.
  </Step>
</Steps>

<Card title="API Reference" icon="book" href="/api-reference/introduction">
  See the REST API endpoints and payloads
</Card>

<Card title="API Cookbook" icon="book-open" href="/integration/api-cookbook">
  Follow end-to-end API recipes for bundle building and cross-chain tracking
</Card>

***

## Model 3: API + Embedded Wallets

<Card title="Best For" icon="robot">
  AI agents, robo-advisors, fintechs, and automated yield strategies
</Card>

### Overview

* **Integration:** REST API + Privy embedded wallets
* **Custody:** User (via non-custodial embedded wallet)
* **Automation:** Yes - session keys enable automated trading
* **Complexity:** High

### Key Features

<CardGroup cols={2}>
  <Card title="Full Automation" icon="wand-magic-sparkles">
    Execute trades 24/7 without user interaction
  </Card>

  <Card title="Session Keys" icon="key">
    Time-limited, amount-limited permissions
  </Card>

  <Card title="Non-Custodial" icon="shield-halved">
    User owns the private key (via Privy)
  </Card>

  <Card title="Seamless UX" icon="face-smile">
    No wallet installation required
  </Card>
</CardGroup>

### Use Cases

* AI-powered yield optimizers
* Robo-advisors with automated rebalancing
* Fintechs offering DeFi savings accounts
* Telegram/Discord bots with trading capabilities
* Recurring DCA (Dollar Cost Averaging) strategies

### Getting Started

<Steps>
  <Step title="Set Up Privy">
    ```bash theme={null}
    npm install @privy-io/react-auth
    ```

    ```typescript theme={null}
    import { PrivyProvider } from '@privy-io/react-auth';

    <PrivyProvider appId="your-privy-app-id">
      <YourApp />
    </PrivyProvider>
    ```
  </Step>

  <Step title="Create Embedded Wallet">
    ```typescript theme={null}
    const { createWallet } = usePrivy();

    // Create wallet for user
    const wallet = await createWallet();
    console.log('Wallet address:', wallet.address);
    ```
  </Step>

  <Step title="Create Session Key">
    ```typescript theme={null}
    const { createSessionKey } = usePrivy();

    // Allow automated trading up to 10k USDC for 24 hours
    await createSessionKey({
      maxAmount: parseEther("10000"),
      expiry: Date.now() + 86400000, // 24 hours
    });
    ```
  </Step>

  <Step title="Automate Deposits">
    ```typescript theme={null}
    // Your backend can now execute trades automatically
    async function autoOptimizeYield(userId: string) {
      const bestInstrument = await findBestYield();

      await depositToInstrument(
        bestInstrument.id,
        amount,
        { sessionKey: await getSessionKey(userId) }
      );
    }
    ```
  </Step>
</Steps>

<Card title="AI Agent Use Case" icon="book" href="/use-cases/ai-agents">
  See an embedded-wallet oriented integration path
</Card>

***

## Comparison Matrix

| Feature                  | Model 1: Direct | Model 2: API + Wallet | Model 3: Embedded        |
| ------------------------ | --------------- | --------------------- | ------------------------ |
| **Control**              | Full            | Full                  | Delegated                |
| **Automation**           | ❌ No            | ❌ No                  | ✅ Yes                    |
| **Custody**              | Self-custody    | Self-custody          | Non-custodial            |
| **User Experience**      | Wallet required | Wallet required       | No wallet needed         |
| **Complexity**           | Medium          | Medium-High           | High                     |
| **Instrument Discovery** | Manual          | ✅ API                 | ✅ API                    |
| **Historical Data**      | ❌ No            | ✅ API                 | ✅ API                    |
| **24/7 Trading**         | ❌ No            | ❌ No                  | ✅ Yes                    |
| **Best For**             | dApps, wallets  | Exchanges, platforms  | AI agents, robo-advisors |

## Architecture Decision Tree

<Steps>
  <Step title="Do you need automated trading?">
    **Yes** → Model 3: Embedded Wallets

    **No** → Continue to next question
  </Step>

  <Step title="Do you need instrument discovery or analytics?">
    **Yes** → Model 2: API + External Wallets

    **No** → Model 1: Direct Blockchain
  </Step>

  <Step title="Do you have existing wallet infrastructure?">
    **Yes** → Model 2: API + External Wallets

    **No** → Consider Model 3 for better UX
  </Step>

  <Step title="Is your application a dApp or protocol?">
    **Yes** → Model 1: Direct Blockchain

    **No** → Model 2 or 3 depending on automation needs
  </Step>
</Steps>

## Hybrid Approaches

You can combine multiple models:

<AccordionGroup>
  <Accordion title="Model 1 + 2: Direct + API">
    Use API for discovery and metadata, direct contracts for execution:

    ```typescript theme={null}
    // 1. Query instruments via API
    const instruments = await api.instruments.list({ minApy: 5 });

    // 2. Execute buy via 1tx Router
    await d1txRouter.write.buy([
      instruments[0].instrumentId,
      amount,
      0n,
      false,
      0n,
      0,                                              // referralFeeBps
      '0x0000000000000000000000000000000000000000',   // referralWallet
    ]);
    ```

    **Benefits:** Rich discovery + full control
  </Accordion>

  <Accordion title="Model 2 + 3: API + Both Wallet Types">
    Support both external and embedded wallets:

    ```typescript theme={null}
    function useWallet() {
      const { address: externalAddress } = useAccount(); // Wagmi
      const { user } = usePrivy(); // Privy

      const wallet = externalAddress || user?.wallet?.address;

      return { wallet, type: externalAddress ? 'external' : 'embedded' };
    }
    ```

    **Benefits:** Flexibility for different user types
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="How It Works" icon="gears" href="/how-it-works">
    Understand the transaction flow
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Explore API endpoints
  </Card>

  <Card title="Use Cases" icon="lightbulb" href="/use-cases/wallets">
    View integration examples
  </Card>

  <Card title="Core Concepts" icon="book-open" href="/concepts/instrument-registry">
    Learn the fundamentals
  </Card>
</CardGroup>
