Volcano API

💡 Examples & Tutorials

Real-world examples and step-by-step tutorials for Card Market API

Examples & Tutorials

Learn how to integrate Card Market API with real-world examples and comprehensive tutorials.

Basic Examples

User Authentication Flow

Here's a complete example of implementing user authentication:

JavaScript

class CardMarketAuth {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.market.decenctype.com';
    this.userToken = null;
  }

  async sendVerificationCode(email) {
    const response = await fetch(`${this.baseUrl}/auth/register/code`, {
      method: 'POST',
      headers: {
        'X-API-KEY': this.apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email })
    });

    if (!response.ok) {
      throw new Error(`Failed to send verification code: ${response.statusText}`);
    }

    return await response.json();
  }

  async registerUser(userData) {
    const response = await fetch(`${this.baseUrl}/auth/register`, {
      method: 'POST',
      headers: {
        'X-API-KEY': this.apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userData)
    });

    if (!response.ok) {
      throw new Error(`Registration failed: ${response.statusText}`);
    }

    return await response.json();
  }

  async loginUser(email, password) {
    const response = await fetch(`${this.baseUrl}/auth/login`, {
      method: 'POST',
      headers: {
        'X-API-KEY': this.apiKey,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ email, password })
    });

    if (!response.ok) {
      throw new Error(`Login failed: ${response.statusText}`);
    }

    const data = await response.json();
    this.userToken = data.data.token;
    return data;
  }

  async getUserProfile() {
    if (!this.userToken) {
      throw new Error('User not authenticated');
    }

    const response = await fetch(`${this.baseUrl}/user`, {
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to get user profile: ${response.statusText}`);
    }

    return await response.json();
  }
}

// Usage example
async function authExample() {
  const auth = new CardMarketAuth('your-api-key-here');

  try {
    // Step 1: Send verification code
    await auth.sendVerificationCode('user@example.com');
    console.log('Verification code sent!');

    // Step 2: Register user (after receiving code)
    const registrationData = {
      email: 'user@example.com',
      password: 'securePassword123',
      username: 'newuser',
      code: '123456', // Code from email
      inviteCode: 'optional-invite-code'
    };

    await auth.registerUser(registrationData);
    console.log('User registered successfully!');

    // Step 3: Login
    const loginResult = await auth.loginUser('user@example.com', 'securePassword123');
    console.log('Login successful:', loginResult.data.user);

    // Step 4: Get user profile
    const profile = await auth.getUserProfile();
    console.log('User profile:', profile.data);

  } catch (error) {
    console.error('Authentication error:', error.message);
  }
}

Python

import requests
import json

class CardMarketAuth:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = 'https://api.market.decenctype.com'
        self.user_token = None
        self.session = requests.Session()
        self.session.headers.update({
            'X-API-KEY': self.api_key,
            'Content-Type': 'application/json'
        })

    def send_verification_code(self, email):
        response = self.session.post(
            f'{self.base_url}/auth/register/code',
            json={'email': email}
        )
        response.raise_for_status()
        return response.json()

    def register_user(self, user_data):
        response = self.session.post(
            f'{self.base_url}/auth/register',
            json=user_data
        )
        response.raise_for_status()
        return response.json()

    def login_user(self, email, password):
        response = self.session.post(
            f'{self.base_url}/auth/login',
            json={'email': email, 'password': password}
        )
        response.raise_for_status()
        
        data = response.json()
        self.user_token = data['data']['token']
        return data

    def get_user_profile(self):
        if not self.user_token:
            raise ValueError('User not authenticated')
        
        headers = {'Authorization': f'Bearer {self.user_token}'}
        response = requests.get(
            f'{self.base_url}/user',
            headers=headers
        )
        response.raise_for_status()
        return response.json()

# Usage example
def auth_example():
    auth = CardMarketAuth('your-api-key-here')
    
    try:
        # Step 1: Send verification code
        auth.send_verification_code('user@example.com')
        print('Verification code sent!')
        
        # Step 2: Register user
        registration_data = {
            'email': 'user@example.com',
            'password': 'securePassword123',
            'username': 'newuser',
            'code': '123456',  # Code from email
            'inviteCode': 'optional-invite-code'
        }
        
        auth.register_user(registration_data)
        print('User registered successfully!')
        
        # Step 3: Login
        login_result = auth.login_user('user@example.com', 'securePassword123')
        print(f'Login successful: {login_result["data"]["user"]}')
        
        # Step 4: Get user profile
        profile = auth.get_user_profile()
        print(f'User profile: {profile["data"]}')
        
    except requests.RequestException as e:
        print(f'Authentication error: {e}')

cURL

#!/bin/bash

API_KEY="your-api-key-here"
BASE_URL="https://api.market.decenctype.com"
EMAIL="user@example.com"
PASSWORD="securePassword123"

# Step 1: Send verification code
echo "Sending verification code..."
curl -X POST "$BASE_URL/auth/register/code" \
  -H "X-API-KEY: $API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$EMAIL\"}"

echo -e "\n\nEnter the verification code from your email:"
read VERIFICATION_CODE

# Step 2: Register user
echo "Registering user..."
curl -X POST "$BASE_URL/auth/register" \
  -H "X-API-KEY: $API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"password\": \"$PASSWORD\",
    \"username\": \"newuser\",
    \"code\": \"$VERIFICATION_CODE\"
  }"

# Step 3: Login and get token
echo -e "\n\nLogging in..."
LOGIN_RESPONSE=$(curl -s -X POST "$BASE_URL/auth/login" \
  -H "X-API-KEY: $API_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$EMAIL\", \"password\": \"$PASSWORD\"}")

# Extract token (requires jq)
TOKEN=$(echo $LOGIN_RESPONSE | jq -r '.data.token')

# Step 4: Get user profile
echo -e "\n\nGetting user profile..."
curl -X GET "$BASE_URL/user" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json"

Card Trading Example

Here's how to implement a complete card trading workflow:

class CardMarketTrading {
  constructor(apiKey, userToken) {
    this.apiKey = apiKey;
    this.userToken = userToken;
    this.baseUrl = 'https://api.market.decenctype.com';
  }

  async getAvailableCards(filters = {}) {
    const queryParams = new URLSearchParams(filters).toString();
    const url = `${this.baseUrl}/cards${queryParams ? '?' + queryParams : ''}`;

    const response = await fetch(url, {
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to get cards: ${response.statusText}`);
    }

    return await response.json();
  }

  async createBuyOrder(cardId, quantity, maxPrice) {
    const response = await fetch(`${this.baseUrl}/orders`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'buy',
        cardId,
        quantity,
        price: maxPrice
      })
    });

    if (!response.ok) {
      throw new Error(`Failed to create order: ${response.statusText}`);
    }

    return await response.json();
  }

  async createSellOrder(cardId, quantity, minPrice) {
    const response = await fetch(`${this.baseUrl}/orders`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'sell',
        cardId,
        quantity,
        price: minPrice
      })
    });

    if (!response.ok) {
      throw new Error(`Failed to create order: ${response.statusText}`);
    }

    return await response.json();
  }

  async getOrderHistory(status = null) {
    const params = status ? `?status=${status}` : '';
    const response = await fetch(`${this.baseUrl}/orders${params}`, {
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to get orders: ${response.statusText}`);
    }

    return await response.json();
  }

  async cancelOrder(orderId) {
    const response = await fetch(`${this.baseUrl}/orders/${orderId}/cancel`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.userToken}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error(`Failed to cancel order: ${response.statusText}`);
    }

    return await response.json();
  }
}

// Usage example
async function tradingExample() {
  const trading = new CardMarketTrading('your-api-key', 'user-bearer-token');

  try {
    // Get available cards
    const cards = await trading.getAvailableCards({
      rarity: 'rare',
      minPrice: 10,
      maxPrice: 100
    });
    console.log('Available cards:', cards.data);

    // Create a buy order for the first card
    if (cards.data.length > 0) {
      const card = cards.data[0];
      const buyOrder = await trading.createBuyOrder(card.id, 1, 50);
      console.log('Buy order created:', buyOrder.data);

      // Check order status after some time
      setTimeout(async () => {
        const orders = await trading.getOrderHistory('pending');
        console.log('Pending orders:', orders.data);
      }, 5000);
    }

  } catch (error) {
    console.error('Trading error:', error.message);
  }
}

Wallet Management Example

Complete wallet operations including address generation and transaction monitoring:

import requests
import time
from typing import Optional, Dict, Any

class CardMarketWallet:
    def __init__(self, api_key: str, user_token: str):
        self.api_key = api_key
        self.user_token = user_token
        self.base_url = 'https://api.market.decenctype.com'
        
    def _make_request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Dict[Any, Any]:
        url = f'{self.base_url}{endpoint}'
        headers = {
            'Authorization': f'Bearer {self.user_token}',
            'Content-Type': 'application/json'
        }
        
        response = requests.request(method, url, headers=headers, json=data)
        response.raise_for_status()
        return response.json()
    
    def get_wallet_address(self, address_type: str, chain_type: str) -> Dict[Any, Any]:
        """Get wallet address for specified type and chain"""
        params = f'?type={address_type}&chainType={chain_type}'
        return self._make_request('GET', f'/wallet/address{params}')
    
    def get_wallet_balance(self, chain_type: str) -> Dict[Any, Any]:
        """Get wallet balance for specified chain"""
        params = f'?chainType={chain_type}'
        return self._make_request('GET', f'/wallet/balance{params}')
    
    def create_withdrawal(self, amount: float, to_address: str, chain_type: str) -> Dict[Any, Any]:
        """Create a withdrawal transaction"""
        data = {
            'amount': amount,
            'toAddress': to_address,
            'chainType': chain_type
        }
        return self._make_request('POST', '/wallet/withdraw', data)
    
    def get_transaction_history(self, chain_type: Optional[str] = None, 
                              limit: int = 50, page: int = 1) -> Dict[Any, Any]:
        """Get transaction history"""
        params = f'?limit={limit}&page={page}'
        if chain_type:
            params += f'&chainType={chain_type}'
        return self._make_request('GET', f'/transactions{params}')
    
    def monitor_transaction(self, transaction_id: str, timeout: int = 300) -> Dict[Any, Any]:
        """Monitor transaction until completion or timeout"""
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            try:
                result = self._make_request('GET', f'/transactions/{transaction_id}')
                status = result['data']['status']
                
                if status in ['confirmed', 'completed']:
                    return result
                elif status == 'failed':
                    raise Exception(f'Transaction failed: {result["data"].get("errorMessage", "Unknown error")}')
                
                time.sleep(10)  # Wait 10 seconds before next check
                
            except requests.RequestException as e:
                print(f'Error checking transaction status: {e}')
                time.sleep(10)
        
        raise TimeoutError(f'Transaction monitoring timed out after {timeout} seconds')

# Usage example
def wallet_example():
    wallet = CardMarketWallet('your-api-key', 'user-bearer-token')
    
    try:
        # Get USDT wallet address
        address_info = wallet.get_wallet_address('user', 'USDT')
        print(f'USDT Address: {address_info["data"]["address"]}')
        
        # Check wallet balance
        balance_info = wallet.get_wallet_balance('USDT')
        print(f'USDT Balance: {balance_info["data"]["balance"]}')
        
        # Get transaction history
        history = wallet.get_transaction_history('USDT', limit=10)
        print(f'Recent transactions: {len(history["data"]["transactions"])}')
        
        # Create withdrawal (example)
        if float(balance_info["data"]["balance"]) > 10:
            withdrawal = wallet.create_withdrawal(
                amount=10.0,
                to_address='recipient-wallet-address',
                chain_type='USDT'
            )
            print(f'Withdrawal created: {withdrawal["data"]["transactionId"]}')
            
            # Monitor the withdrawal
            final_status = wallet.monitor_transaction(
                withdrawal["data"]["transactionId"],
                timeout=600  # 10 minutes
            )
            print(f'Withdrawal completed: {final_status["data"]["status"]}')
            
    except Exception as e:
        print(f'Wallet error: {e}')

Advanced Integration Patterns

Error Handling and Retry Logic

class ApiClient {
  constructor(apiKey, options = {}) {
    this.apiKey = apiKey;
    this.baseUrl = options.baseUrl || 'https://api.market.decenctype.com';
    this.maxRetries = options.maxRetries || 3;
    this.retryDelay = options.retryDelay || 1000;
  }

  async makeRequest(endpoint, options = {}) {
    const url = `${this.baseUrl}${endpoint}`;
    const config = {
      ...options,
      headers: {
        'X-API-KEY': this.apiKey,
        'Content-Type': 'application/json',
        ...options.headers
      }
    };

    for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
      try {
        const response = await fetch(url, config);
        
        if (response.status === 429) {
          // Rate limited - wait and retry
          const retryAfter = response.headers.get('Retry-After') || this.retryDelay / 1000;
          await this.delay(retryAfter * 1000);
          continue;
        }
        
        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}));
          throw new ApiError(response.status, errorData.error?.message || response.statusText, errorData);
        }
        
        return await response.json();
        
      } catch (error) {
        if (attempt === this.maxRetries || !this.shouldRetry(error)) {
          throw error;
        }
        
        await this.delay(this.retryDelay * Math.pow(2, attempt - 1)); // Exponential backoff
      }
    }
  }

  shouldRetry(error) {
    // Retry on network errors or 5xx server errors
    return error.name === 'TypeError' || (error.status >= 500 && error.status < 600);
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}

class ApiError extends Error {
  constructor(status, message, data) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
    this.data = data;
  }
}

Webhook Verification

const crypto = require('crypto');

class WebhookHandler {
  constructor(secret) {
    this.secret = secret;
  }

  verifySignature(payload, signature) {
    const expectedSignature = crypto
      .createHmac('sha256', this.secret)
      .update(payload, 'utf8')
      .digest('hex');
    
    const providedSignature = signature.replace('sha256=', '');
    
    return crypto.timingSafeEqual(
      Buffer.from(expectedSignature, 'hex'),
      Buffer.from(providedSignature, 'hex')
    );
  }

  handleWebhook(req, res) {
    const signature = req.headers['x-webhook-signature'];
    const payload = JSON.stringify(req.body);
    
    if (!this.verifySignature(payload, signature)) {
      return res.status(401).json({ error: 'Invalid signature' });
    }
    
    const event = req.body;
    
    switch (event.type) {
      case 'order.completed':
        this.handleOrderCompleted(event.data);
        break;
      case 'transaction.confirmed':
        this.handleTransactionConfirmed(event.data);
        break;
      case 'kyc.approved':
        this.handleKycApproved(event.data);
        break;
      default:
        console.log(`Unhandled event type: ${event.type}`);
    }
    
    res.status(200).json({ received: true });
  }

  handleOrderCompleted(orderData) {
    console.log('Order completed:', orderData);
    // Implement your order completion logic
  }

  handleTransactionConfirmed(transactionData) {
    console.log('Transaction confirmed:', transactionData);
    // Implement your transaction confirmation logic
  }

  handleKycApproved(userData) {
    console.log('KYC approved:', userData);
    // Implement your KYC approval logic
  }
}

Next Steps

Ready to build more complex integrations? Check out these resources: