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

# thirdweb

> Managed infrastructure with thirdweb's x402 payment wrapper

This example demonstrates integration using **thirdweb's x402 payment wrapper API**. Perfect for applications already using the thirdweb ecosystem.

## Overview

Integrate Snack Money payments using thirdweb's x402 fetch wrapper, which handles payment negotiation through thirdweb's managed infrastructure.

## Features

* ✅ **Base network** support
* ✅ **Managed infrastructure** - thirdweb handles x402 flow
* ✅ **x402 wrapper via API** - Automatic payment negotiation
* ✅ **Server-side wallet** - Secure key management
* ✅ **thirdweb ecosystem** - Works with other thirdweb tools

## Prerequisites

* Node.js 18+
* thirdweb account ([Sign up](https://thirdweb.com/))
* thirdweb Secret Key
* thirdweb server wallet with USDC balance on Base

## Installation

```bash theme={null}
npm install dotenv
```

## Quick Start

### 1. Get thirdweb Credentials

1. Visit [thirdweb Dashboard](https://thirdweb.com/dashboard)
2. Create a new project
3. Get your Client ID and Secret Key
4. Create a wallet and fund with USDC

### 2. Set Up Environment

Create a `.env` file:

```bash theme={null}
THIRDWEB_SECRET_KEY=your_secret_key
WALLET_ADDRESS=your_thirdweb_server_wallet_address
RECEIVER=your_x_username
AMOUNT=0.01
```

<Note>
  **Important**: The `WALLET_ADDRESS` should be your thirdweb server wallet address that has USDC on Base network.
</Note>

### 3. Implement Payment

Create `base-send.ts`:

```typescript theme={null}
import { config } from "dotenv";

config();

async function sendPayment() {
  const receiver = process.env.RECEIVER as string;
  const amount = parseFloat(process.env.AMOUNT || "0.01");
  const secretKey = process.env.THIRDWEB_SECRET_KEY as string;
  const walletAddress = process.env.WALLET_ADDRESS as string;

  if (!receiver || !secretKey || !walletAddress) {
    console.error("Missing required environment variables: RECEIVER, THIRDWEB_SECRET_KEY, and WALLET_ADDRESS");
    process.exit(1);
  }

  console.log("🚀 Starting Snack Money payment with thirdweb\n");
  console.log(`📍 Wallet Address: ${walletAddress}`);
  console.log(`💡 Check balance: https://basescan.org/address/${walletAddress}\n`);

  const url = "https://api.snack.money/payments/x/pay";
  const encodedUrl = encodeURIComponent(url);
  const usdcAddress = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"; // USDC on Base
  const chainId = 8453; // Base network
  const maxValue = 1000000; // 1 USDC in smallest units (6 decimals)

  console.log(`💸 Sending ${amount} USDC to @${receiver} on X...\n`);

  // Use thirdweb's x402 fetch wrapper
  const response = await fetch(
    `https://api.thirdweb.com/v1/payments/x402/fetch?from=${walletAddress}&url=${encodedUrl}&method=POST&chainId=${chainId}&maxValue=${maxValue}&asset=${usdcAddress}`,
    {
      method: "POST",
      headers: {
        "x-secret-key": secretKey,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        amount,
        currency: "USDC",
        receiver,
        description: "Payment via thirdweb x402 wrapper"
      })
    }
  );

  const data = await response.json();

  if (response.status === 200) {
    console.log("✅ Payment successful!");
    console.log("\n📊 Response:", JSON.stringify(data, null, 2));
  } else {
    console.error("❌ Payment failed");
    console.error("Status:", response.status);
    console.error("Response:", JSON.stringify(data, null, 2));
  }
}

sendPayment();
```

### 4. Run the Example

```bash theme={null}
npm run base
# or
npx tsx base-send.ts
```

## Expected Output

```
🚀 Starting Snack Money payment with thirdweb

✅ Initialized thirdweb client
💸 Sending 0.01 USDC to @username on X...

✅ Payment successful!

📊 Response: {
  "code": 200,
  "msg": "0.01 USDC sent successfully",
  "data": {
    "txn_id": "0xabc...def",
    "amount": 0.01,
    "receipt": "https://snack.money/x/username?txn=..."
  }
}
```

## How It Works

1. **Initialize thirdweb**: Create client with API credentials
2. **Create Wallet**: Load wallet from private key
3. **Convert Account**: Convert to viem format for x402
4. **Wrap Axios**: Add payment interceptor
5. **Send Payment**: Make payment request

## Why thirdweb?

### Benefits

* **Managed Infrastructure**: thirdweb handles blockchain complexity
* **Ecosystem Integration**: Works with other thirdweb services
* **Developer Experience**: Simple, consistent APIs
* **Multi-Chain Support**: Easy to extend to other chains

### Best For

* Apps already using thirdweb
* Need thirdweb ecosystem features
* Want managed infrastructure
* Building multi-chain apps

## Supported Platforms

```typescript theme={null}
// X (Twitter)
await api.post("/payments/x/pay", {
  amount: 0.01,
  receiver: "username",
  currency: "USDC"
});

// Farcaster
await api.post("/payments/farcaster/pay", {
  amount: 0.5,
  receiver: "username",
  currency: "USDC"
});

// GitHub
await api.post("/payments/github/pay", {
  amount: 1.0,
  receiver: "username",
  currency: "USDC"
});
```

## thirdweb Features

### Using thirdweb Wallets

```typescript theme={null}
import { inAppWallet } from "thirdweb/wallets";

// Create in-app wallet for users
const wallet = inAppWallet();
await wallet.connect({
  client,
  strategy: "email",
  email: "user@example.com"
});
```

### Smart Wallets

```typescript theme={null}
import { smartWallet } from "thirdweb/wallets";

const wallet = smartWallet({
  chain: base,
  gasless: true
});
```

## Error Handling

```typescript theme={null}
try {
  const response = await api.post("/payments/x/pay", {
    amount: 0.01,
    currency: "USDC",
    receiver: "username"
  });
  console.log("Success:", response.data);
} catch (error) {
  console.error("Payment failed:", error);
}
```

## Full Example Repository

[View on GitHub →](https://github.com/snack-money/snack-money-examples/tree/main/thirdweb)

Includes:

* Complete implementation
* thirdweb configuration
* Environment setup
* Detailed README

## Next Steps

* [**Try Crossmint**](/examples/crossmint) - Smart wallet features
* [**thirdweb Docs**](https://portal.thirdweb.com/) - Learn more about thirdweb
* [**API Reference**](/api-reference/introduction) - Complete API docs

## Dependencies

```json theme={null}
{
  "dependencies": {
    "thirdweb": "^5.0.0",
    "axios": "^1.6.0",
    "x402-axios": "latest",
    "viem": "^2.0.0"
  }
}
```

## Learn More

* [thirdweb Documentation](https://portal.thirdweb.com/)
* [x402 Protocol](https://github.com/coinbase/x402)
* [thirdweb SDK Reference](https://portal.thirdweb.com/typescript/v5)
