# API Integration

### Overview

The CyreneAI Bonding Curve API allows external users to create bonding curve configurations and token pools on the Solana blockchain. The API provides a secure, CORS-enabled interface for token launches using CyreneAI.

#### Key Features

* **API Key Authentication**: Secure API key management with wallet-based access control
* **CORS Enabled**: Public API endpoints accessible from any origin
* **Transaction Signing**: Server-side additional signer support for enhanced security
* **On-chain Verification**: Automatic validation of config existence before pool creation

#### Base URL

```
Production: https://cyreneai.com
```

***

### Getting Started

#### 1. Generate an API Key

API keys can be generated by visiting  `https://cyreneai.com/api-keys`. You must be connected your Solana wallet address to generate a key.

**Request:**

```http
POST https://cyreneai.com/api/api-keys
Authorization: Bearer <your_wallet_address>
Content-Type: application/json

{
  "name": "Production Key"  // Optional
}
```

**Response:**

```json
{
  "success": true,
  "apiKey": "e21cce3dd01b26f3cfaaaaaba07008ef1c45dfa617c8c989b251f117e8ec2980",
  "apiKeyId": "uuid-here",
  "walletAddress": "8MvWVMNMeH4fhCMAWw8NeZqPXZHyhWf3kBWAmS7KNeF8",
  "name": "Production Key",
  "createdAt": "2025-11-22T12:00:00Z"
}
```

⚠️ **Important**: Save your API key immediately. It will not be shown again if you refresh or close the page .

#### 2. List Your API Keys

**Request:**

```http
GET https://cyreneai.com/api/api-keys
Authorization: Bearer <your_wallet_address>
```

**Response:**

```json
{
  "success": true,
  "apiKeys": [
    {
      "id": "uuid-here",
      "name": "Production Key",
      "is_active": true,
      "usage_count": 42,
      "last_used_at": "2025-11-22T13:00:00Z",
      "created_at": "2025-11-22T12:00:00Z"
    }
  ]
}
```

#### 3. Revoke an API Key

**Request:**

```http
DELETE https://cyreneai.com/api/api-keys?id=<api_key_id>
Authorization: Bearer <your_wallet_address>
```

**Response:**

```json
{
  "success": true,
  "message": "API key revoked successfully"
}
```

***

### API Endpoints

#### Create Config

Creates a bonding curve configuration transaction. This must be sent and confirmed on-chain before creating a pool.

**Endpoint:** `POST /api/cyreneai-api/create-config`

**Headers:**

```http
x-api-key: <your_api_key>
Content-Type: application/json
```

**Request Body:**

```json
{
  "wallet": "8MvWVMNMeH4fhCMAWw8NeZqPXZHyhWf3kBWAmS7KNeF8",
  "cluster": "MAINNET",
  "totalTokenSupply": 1000000000,
  "percentageSupplyOnMigration": 20,
  "migrationQuoteThreshold": 20,
  "tokenQuoteDecimal": 9,
  "baseFeeParams": 240,
  "partnerLockedLpPercentage": 40,
  "creatorLockedLpPercentage": 60,
  "lockedVestingParam": {
    "totalLockedVestingAmount": 100000000,
    "numberOfVestingPeriod": 3,
    "cliffUnlockAmount": 50000000,
    "totalVestingDuration": 15552000,
    "cliffDurationFromMigrationTime": 7776000
  }
}
```

**Parameters:**

* `wallet` (required): Your Solana wallet public key (must match API key owner)
* `cluster` (optional): `"MAINNET"` or `"DEVNET"` (default: `"MAINNET"`)
* `totalTokenSupply` (required): Total supply of tokens (e.g., 1000000000)
* `percentageSupplyOnMigration` (optional): Percentage of supply on migration (default: 20)
* `migrationQuoteThreshold` (required): SOL amount threshold for migration (e.g., 20)
* `tokenQuoteDecimal` (optional): Quote token decimals - `9` for SOL, `6` for CYAI (default: 9)
* `baseFeeParams` (optional): Base fee in basis points (number) or full config object (default: 240)
* `partnerLockedLpPercentage` (optional): Partner locked LP percentage (default: 40)
* `creatorLockedLpPercentage` (optional): Creator locked LP percentage (default: 60)
* `lockedVestingParam` (optional): Custom vesting parameters object

**Response:**

```json
{
  "success": true,
  "message": "Config transaction created and partially signed",
  "data": {
    "serializedTransaction": "base64_encoded_transaction",
    "config": "73MroMwZPqpr2TLWGATt5C8HV5G1GcynHcPQctED1ysU"
  }
}
```

**Next Steps:**

1. Deserialize the `serializedTransaction` (base64)
2. Sign it with your wallet
3. Send it to the blockchain
4. Wait for confirmation
5. Use the `config` address in the create-pool endpoint

***

#### Create Pool

Creates a token pool transaction using a confirmed config address.

**Endpoint:** `POST /api/cyreneai-api/create-pool`

**Headers:**

```http
x-api-key: <your_api_key>
Content-Type: application/json
```

**Request Body:**

```json
{
  "wallet": "8MvWVMNMeH4fhCMAWw8NeZqPXZHyhWf3kBWAmS7KNeF8",
  "config": "73MroMwZPqpr2TLWGATt5C8HV5G1GcynHcPQctED1ysU",
  "name": "My Token",
  "symbol": "MTK",
  "uri": "https://ipfs.io/ipfs/Qm...",
  "cluster": "MAINNET",
  "baseMintPrivateKey": "base58_encoded_private_key",
  "enableFirstBuy": true,
  "firstBuyAmountSol": 0.1,
  "minimumTokensOut": 1000000
}
```

**Parameters:**

* `wallet` (required): Your Solana wallet public key (must match API key owner)
* `config` (required): Config address from create-config (must be confirmed on-chain)
* `name` (required): Token name
* `symbol` (required): Token symbol
* `uri` (required): Metadata URI (IPFS or HTTPS)
* `cluster` (optional): `"MAINNET"` or `"DEVNET"` (default: `"MAINNET"`)
* `baseMintPrivateKey` (required): Base mint private key (base58 string or JSON array)
* `enableFirstBuy` (optional): Enable first buy swap (default: false)
* `firstBuyAmountSol` (optional): SOL amount for first buy (required if enableFirstBuy is true)
* `minimumTokensOut` (optional): Minimum tokens out for first buy (required if enableFirstBuy is true)

**Response:**

```json
{
  "success": true,
  "message": "Pool transaction created and partially signed",
  "data": {
    "serializedTransaction": "base64_encoded_pool_transaction",
    "swapSerializedTransaction": "base64_encoded_swap_transaction",
    "baseMint": "BaseMintPublicKeyHere"
  }
}
```

**Note:** `swapSerializedTransaction` is only present if `enableFirstBuy` is true.

**Next Steps:**

1. Deserialize the `serializedTransaction` (base64)
2. Sign it with your wallet
3. Send it to the blockchain
4. If `swapSerializedTransaction` exists, repeat steps 1-3 for the swap transaction

***

### Implementation Guide

#### Transaction Flow

The API follows a two-step process:

1. **Create Config** → Get config transaction → Sign & Send → Wait for confirmation
2. **Create Pool** → Use confirmed config → Get pool transaction → Sign & Send

#### Code Example (JavaScript/TypeScript)

```javascript
import { Connection, PublicKey, VersionedTransaction } from '@solana/web3.js';

const API_BASE_URL = 'https://cyreneai.com';
const API_KEY = 'your_api_key_here';
const WALLET_ADDRESS = 'your_wallet_address';

// Helper: Base64 to Uint8Array
function base64ToUint8Array(base64) {
  const binaryString = atob(base64);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}

// Step 1: Create Config
async function createConfig() {
  const response = await fetch(`${API_BASE_URL}/api/cyreneai-api/create-config`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': API_KEY,
    },
    body: JSON.stringify({
      wallet: WALLET_ADDRESS,
      cluster: 'MAINNET',
      totalTokenSupply: 1000000000,
      migrationQuoteThreshold: 20,
      baseFeeParams: 240,
      partnerLockedLpPercentage: 40,
      creatorLockedLpPercentage: 60,
    }),
  });

  const data = await response.json();
  
  if (!data.success) {
    throw new Error(data.error);
  }

  return {
    configAddress: data.data.config,
    serializedTransaction: data.data.serializedTransaction,
  };
}

// Step 2: Sign and Send Config Transaction
async function signAndSendConfig(serializedTransaction, walletProvider) {
  // Deserialize transaction
  const transactionBytes = base64ToUint8Array(serializedTransaction);
  const transaction = VersionedTransaction.deserialize(transactionBytes);

  // Sign with wallet
  const signedTransaction = await walletProvider.signTransaction(transaction);

  // Send to blockchain
  const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=YOUR_HELIUS_KEY', 'confirmed');
  const signature = await connection.sendRawTransaction(signedTransaction.serialize(), {
    skipPreflight: false,
    maxRetries: 3,
  });

  // Wait for confirmation
  await connection.confirmTransaction(signature, 'confirmed');

  return signature;
}

// Step 3: Verify Config On-Chain
async function verifyConfigOnChain(configAddress) {
  const connection = new Connection('https://mainnet.helius-rpc.com/?api-key=YOUR_HELIUS_KEY', 'confirmed');
  const configPublicKey = new PublicKey(configAddress);
  const accountInfo = await connection.getAccountInfo(configPublicKey);
  
  if (!accountInfo) {
    throw new Error('Config not found on-chain');
  }
  
  return true;
}

// Step 4: Create Pool
async function createPool(configAddress) {
  const response = await fetch(`${API_BASE_URL}/api/cyreneai-api/create-pool`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-api-key': API_KEY,
    },
    body: JSON.stringify({
      wallet: WALLET_ADDRESS,
      config: configAddress,
      name: 'My Token',
      symbol: 'MTK',
      uri: 'https://ipfs.io/ipfs/Qm...',
      cluster: 'MAINNET',
      baseMintPrivateKey: 'your_base_mint_private_key',
      enableFirstBuy: true,
      firstBuyAmountSol: 0.1,
      minimumTokensOut: 1000000,
    }),
  });

  const data = await response.json();
  
  if (!data.success) {
    throw new Error(data.error);
  }

  return data.data;
}

// Full Flow
async function launchToken() {
  try {
    // 1. Create config
    const { configAddress, serializedTransaction } = await createConfig();
    console.log('Config created:', configAddress);

    // 2. Sign and send config
    const configSignature = await signAndSendConfig(serializedTransaction, walletProvider);
    console.log('Config sent:', configSignature);

    // 3. Verify config on-chain
    await verifyConfigOnChain(configAddress);
    console.log('Config verified on-chain');

    // 4. Create pool
    const poolData = await createPool(configAddress);
    console.log('Pool created:', poolData.baseMint);

    // 5. Sign and send pool transaction
    const poolSignature = await signAndSendConfig(poolData.serializedTransaction, walletProvider);
    console.log('Pool sent:', poolSignature);

    // 6. If swap transaction exists, send it too
    if (poolData.swapSerializedTransaction) {
      const swapSignature = await signAndSendConfig(poolData.swapSerializedTransaction, walletProvider);
      console.log('Swap sent:', swapSignature);
    }

    console.log('✅ Token launch complete!');
  } catch (error) {
    console.error('Error:', error);
  }
}
```

#### Using Helius RPC

The API uses Helius RPC for reliable blockchain interaction. For client-side transactions, use Helius RPC as well:

```javascript
const HELIUS_API_KEY = 'your_helius_api_key';
const rpcUrl = `https://mainnet.helius-rpc.com/?api-key=${HELIUS_API_KEY}`;
const connection = new Connection(rpcUrl, 'confirmed');
```

Get a free Helius API key at [helius.dev](https://helius.dev).

***

### User Guide

#### Quick Start with HTML Test Page

A test HTML page is available at `api-test.html` (or served at `https://cyreneai.com/api-test.html`). This page provides a complete UI for testing the API.

**Features:**

* Wallet connection (Phantom, Solflare, Backpack)
* API key generation and management
* Automatic transaction signing and sending
* Progress indicators
* Error handling and guidance

**Usage:**

1. Open the HTML page in your browser
2. Connect your Solana wallet
3. Generate an API key (or use an existing one)
4. Fill in token parameters
5. Click "Create Config & Pool"
6. The page will automatically:
   * Create the config transaction
   * Sign and send it with your wallet
   * Wait for confirmation
   * Create the pool transaction
   * Sign and send the pool transaction

#### Manual Workflow

If you prefer to integrate the API into your own application:

1. **Generate API Key**
   * Visit `https://cyreneai.com/api-keys`
   * Provide your wallet address
   * Save the API key securely
2. **Create Config**
   * Call `/api/cyreneai-api/create-config`
   * Get the `serializedTransaction` and `config` address
   * Sign and send the transaction
   * Wait for on-chain confirmation
3. **Create Pool**
   * Call `/api/cyreneai-api/create-pool` with the confirmed `config` address
   * Get the `serializedTransaction` (and `swapSerializedTransaction` if enabled)
   * Sign and send the transaction(s)

#### Base Fee Parameters

The `baseFeeParams` can be provided in two formats:

**Simple Number (Basis Points):**

```json
{
  "baseFeeParams": 240
}
```

This sets a fixed fee of 240 basis points (2.4%).

**Full Configuration Object:**

```json
{
  "baseFeeParams": {
    "baseFeeMode": 1,
    "feeSchedulerParam": {
      "startingFeeBps": 5000,
      "endingFeeBps": 200,
      "numberOfPeriod": 2,
      "totalDuration": 120
    }
  }
}
```

#### Vesting Parameters

Custom vesting can be configured with `lockedVestingParam`:

```json
{
  "lockedVestingParam": {
    "totalLockedVestingAmount": 100000000,
    "numberOfVestingPeriod": 3,
    "cliffUnlockAmount": 50000000,
    "totalVestingDuration": 15552000,
    "cliffDurationFromMigrationTime": 7776000
  }
}
```

If not provided, default vesting is applied:

* 10% of total supply locked
* 6 vesting periods
* 15552000 seconds total duration

***

### Error Handling

#### Common Errors

**401 Unauthorized**

```json
{
  "error": "API key is required. Provide it in x-api-key header or Authorization: Bearer <api_key>"
}
```

**Solution:** Include your API key in the `x-api-key` header.

**403 Forbidden**

```json
{
  "error": "Wallet address in request does not match API key owner"
}
```

**Solution:** Ensure the `wallet` parameter matches the wallet address used to generate the API key.

**400 Bad Request - Config Not Found**

```json
{
  "error": "Config not found on-chain. Please send and confirm the config transaction first before creating the pool."
}
```

**Solution:**

1. Make sure you've sent the config transaction from `create-config`
2. Wait for on-chain confirmation
3. Verify on Solscan: `https://solscan.io/account/<config_address>`
4. Then call `create-pool` again

**500 Internal Server Error**

```json
{
  "success": false,
  "error": "Error message here",
  "details": "Stack trace (in development)"
}
```

**Solution:** Check the error message and details. Common causes:

* Invalid RPC connection
* Invalid private key format
* Network issues

#### Error Response Format

All errors follow this format:

```json
{
  "success": false,
  "error": "Human-readable error message",
  "details": "Additional details (optional)"
}
```

***

### Best Practices

#### 1. API Key Security

* **Never expose API keys** in client-side code or public repositories
* Store API keys in environment variables or secure storage
* Rotate API keys regularly
* Revoke unused or compromised keys immediately

#### 2. Transaction Handling

* **Always wait for confirmation** before proceeding to pool creation
* Use Helius RPC for reliable transaction submission
* Implement retry logic for failed transactions
* Monitor transaction status on Solscan

#### 3. Error Handling

* Implement comprehensive error handling
* Provide user-friendly error messages
* Log errors for debugging (without exposing sensitive data)
* Handle network timeouts gracefully

#### 4. Rate Limiting

* The API may have rate limits. Implement exponential backoff for retries
* Cache API responses when appropriate
* Batch operations when possible

#### 5. Testing

* Always test on `DEVNET` first
* Use small amounts for initial testing
* Verify all transactions on Solscan before production use

#### 6. RPC Configuration

* Use Helius RPC for production (get free API key at [helius.dev](https://helius.dev))
* Public RPCs may have rate limits or 403 errors
* Configure RPC endpoints in your environment variables

***

### Support

For issues, questions, or feature requests:

* Review error messages and stack traces
* Verify your API key and wallet address match
* Ensure all transactions are confirmed on-chain
* Connect with us on our official Discord channel or email us at <support@cyreneai.com>
