# CDP Wallet & Onramp Kit

Complete toolkit for integrating Coinbase Developer Platform (CDP) Embedded Wallets and Onramp functionality into your Next.js applications. This package combines comprehensive documentation, reusable React components, utilities, and API templates to get you up and running quickly.

## Features

🎯 **All-in-One Solution**: Embedded wallets + onramp in one package  
📚 **Comprehensive Docs**: Complete integration guides and examples  
⚛️ **React Components**: Pre-built, customizable UI components  
🔧 **Utilities & Helpers**: Authentication, validation, and API utilities  
🚀 **Quick Setup**: CLI commands to scaffold your project  
💼 **Production Ready**: Error handling, validation, and best practices  

## Quick Start

### 1. Install Documentation & Components

```bash
# Install the package
npm install cdp-wallet-onramp-kit

# Set up documentation in your project
npx cdp-wallet-onramp-kit setup

# Or initialize a new project with API routes and examples
npx cdp-wallet-onramp-kit init
```

### 2. Environment Setup

Create `.env.local`:

```bash
# Required for both wallet and onramp
NEXT_PUBLIC_CDP_PROJECT_ID=your-project-id-here

# Required for onramp (server-side only)  
CDP_API_KEY_PRIVATE_KEY=your-private-key-here
CDP_API_KEY_NAME=your-key-name-here
```

### 3. Configure CORS

Visit [CDP Portal](https://portal.cdp.coinbase.com/products/embedded-wallets/cors) and add your domains:
- Development: `http://localhost:3000`
- Production: `https://yourdomain.com`

### 4. Use the Components

```tsx
"use client";

import { CDPProvider, WalletAuth, OnrampButton } from 'cdp-wallet-onramp-kit';
import { useEvmAddress } from '@coinbase/cdp-hooks';

const cdpConfig = {
  projectId: process.env.NEXT_PUBLIC_CDP_PROJECT_ID!,
  debugging: process.env.NODE_ENV === 'development',
};

const appConfig = {
  name: "My App",
  logoUrl: "/logo.png",
};

function WalletSection() {
  const evmAddress = useEvmAddress();

  return (
    <div className="space-y-4">
      <WalletAuth />
      {evmAddress && (
        <OnrampButton
          walletAddress={evmAddress || undefined}
          defaultAsset="USDC"
          presetFiatAmount={50}
        >
          Buy $50 USDC
        </OnrampButton>
      )}
    </div>
  );
}

export default function App() {
  return (
    <CDPProvider config={cdpConfig} app={appConfig}>
      <WalletSection />
    </CDPProvider>
  );
}
```

## Components

### Providers

- **`CDPProvider`** - Full React components provider
- **`CDPHooksProvider`** - Hooks-only provider for custom UIs

### Authentication

- **`WalletAuth`** - Simple pre-built auth button
- **`CustomWalletAuth`** - Full control auth component with email/OTP flow

### Onramp

- **`OnrampButton`** - Simple buy crypto button
- **`OnrampWidget`** - Complete purchase widget with auth integration

## Utilities

### Authentication & API

```typescript
import { 
  generateJWT, 
  createSessionToken, 
  generateOnrampUrl 
} from 'cdp-wallet-onramp-kit/lib';

// Generate JWT for CDP API
const jwt = await generateJWT();

// Create session token for onramp
const sessionToken = await createSessionToken(jwt, {
  addresses: [{ address: walletAddress, blockchains: ['base'] }],
  assets: ['USDC', 'ETH']
});

// Generate complete onramp URL
const onrampUrl = await generateOnrampUrl({
  addresses: [{ address: walletAddress, blockchains: ['base'] }],
  defaultAsset: 'USDC',
  presetFiatAmount: 50
});
```

### Validation

```typescript
import { 
  validateRequest, 
  sessionTokenSchema,
  validateEnvironment 
} from 'cdp-wallet-onramp-kit/lib';

// Validate API requests
const validatedData = validateRequest(sessionTokenSchema, requestBody);

// Check environment variables
const envCheck = validateEnvironment();
```

## API Routes (Templates)

The package includes ready-to-use API route templates:

- `app/api/onramp/session/route.ts` - Session token creation
- `app/api/onramp/url/route.ts` - Onramp URL generation

Copy these from the templates or use `npx cdp-wallet-onramp-kit init`.

## Documentation

After running `npx cdp-wallet-onramp-kit setup`, you'll have:

- **Integration Guides**: Step-by-step instructions for AI coding agents
- **API Documentation**: Complete CDP Onramp and Embedded Wallet docs
- **Examples**: Working code examples and patterns
- **Best Practices**: Security, error handling, and production considerations

## Dependencies

### Required Peer Dependencies

```json
{
  "@coinbase/cdp-core": ">=0.0.18",
  "@coinbase/cdp-hooks": ">=0.0.18", 
  "@coinbase/cdp-react": ">=0.0.18",
  "@coinbase/cdp-sdk": ">=1.33.0",
  "react": ">=18.0.0",
  "react-dom": ">=18.0.0",
  "next": ">=14.0.0"
}
```

### Optional Dependencies

For enhanced UI:
- `lucide-react` - Icons
- `framer-motion` - Animations
- `tailwindcss` - Styling (components use Tailwind classes)

## CLI Commands

```bash
# Set up documentation
npx cdp-wallet-onramp-kit setup [--dir ./docs] [--force]

# Initialize new project
npx cdp-wallet-onramp-kit init [--template basic|complete] [--dir .]
```

## Examples

### Guest Checkout (No Wallet Required)

```tsx
<OnrampButton
  defaultAsset="USDC"
  presetFiatAmount={25}
>
  Buy $25 USDC (Guest)
</OnrampButton>
```

### Complete Widget with Authentication

```tsx
<OnrampWidget
  title="Buy Crypto"
  description="Purchase crypto with your credit card"
  presetAmounts={[10, 25, 50, 100]}
  defaultAmount={50}
  theme="dark"
/>
```

### Custom Authentication Flow

```tsx
<CustomWalletAuth 
  theme="dark"
  showDebugInfo={true}
  onSignedIn={(user, address) => {
    console.log('User signed in:', user, address);
  }}
/>
```

## Support

- 📖 **Documentation**: Check the `doc/` folder after setup
- 🏗️ **CDP Portal**: [portal.cdp.coinbase.com](https://portal.cdp.coinbase.com)
- 📚 **Official Docs**: [docs.cdp.coinbase.com](https://docs.cdp.coinbase.com)

## License

MIT

---

Built for developers who want to integrate crypto payments and wallets without the complexity. Get your users buying crypto in minutes, not days.