Code Examples

Learn how to integrate QuasarFlow API into your applications with these practical examples.

Basic Wallet Operations

Learn the fundamentals of creating wallets, checking balances, and managing assets.

Complete Wallet Lifecycle

Complete Wallet Lifecycle
1#!/bin/bash
2
3# Set your API base URL
4API_BASE="https://quasarflow.dev/api"
5
6# 1. Login and get token
7echo "🔐 Logging in..."
8TOKEN=$(curl -s -X POST $API_BASE/auth/login \
9  -H "Content-Type: application/json" \
10  -d '{"username": "admin", "password": "admin123"}' | jq -r '.data.token')
11
12if [ "$TOKEN" = "null" ]; then
13  echo "❌ Login failed"
14  exit 1
15fi
16
17echo "✅ Login successful"
18
19# 2. Create a new wallet
20echo "💰 Creating wallet..."
21WALLET_RESPONSE=$(curl -s -X POST $API_BASE/api/v1/wallets \
22  -H "Authorization: Bearer $TOKEN" \
23  -H "Content-Type: application/json" \
24  -d '{"network": "local"}')
25
26WALLET_ID=$(echo $WALLET_RESPONSE | jq -r '.data.id')
27PUBLIC_KEY=$(echo $WALLET_RESPONSE | jq -r '.data.public_key')
28
29echo "✅ Wallet created: $WALLET_ID"
30echo "🔑 Public key: $PUBLIC_KEY"
31
32# 3. Fund the wallet (development only)
33echo "💸 Funding wallet..."
34curl -s -X POST $API_BASE/api/v1/wallets/$WALLET_ID/fund \
35  -H "Authorization: Bearer $TOKEN" > /dev/null
36
37echo "✅ Wallet funded"
38
39# 4. Check balance
40echo "📊 Checking balance..."
41BALANCE=$(curl -s $API_BASE/api/v1/wallets/$WALLET_ID/balance \
42  -H "Authorization: Bearer $TOKEN")
43
44echo "💰 Balance:"
45echo $BALANCE | jq '.data.balances[] | "(.asset): (.amount)"'
46
47# 5. Get transaction history
48echo "📜 Transaction history..."
49HISTORY=$(curl -s $API_BASE/api/v1/wallets/$WALLET_ID/transactions \
50  -H "Authorization: Bearer $TOKEN")
51
52echo "📋 Recent transactions:"
53echo $HISTORY | jq '.data.transactions[] | "(.type): (.amount) (.asset) - (.status)"'

Payment Flow

Complete example of sending payments between wallets with error handling.

Send Payment with Validation

#!/bin/bash

# Payment configuration
API_BASE="https://quasarflow.dev/api"
FROM_WALLET_ID="wallet_123"
TO_PUBLIC_KEY="GDEF456..."
AMOUNT="10.5"
ASSET="XLM"
MEMO="Payment for services"

# Login
TOKEN=$(curl -s -X POST $API_BASE/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin123"}' | jq -r '.data.token')

# Check sender balance before payment
echo "📊 Checking sender balance..."
BALANCE_RESPONSE=$(curl -s $API_BASE/api/v1/wallets/$FROM_WALLET_ID/balance \
  -H "Authorization: Bearer $TOKEN")

CURRENT_BALANCE=$(echo $BALANCE_RESPONSE | jq -r '.data.balances[] | select(.asset=="'$ASSET'") | .amount')

if [ "$CURRENT_BALANCE" = "null" ]; then
  echo "❌ No $ASSET balance found"
  exit 1
fi

echo "💰 Current $ASSET balance: $CURRENT_BALANCE"

# Validate sufficient balance
if (( $(echo "$CURRENT_BALANCE < $AMOUNT" | bc -l) )); then
  echo "❌ Insufficient balance. Required: $AMOUNT, Available: $CURRENT_BALANCE"
  exit 1
fi

# Send payment
echo "💸 Sending payment..."
PAYMENT_RESPONSE=$(curl -s -X POST $API_BASE/api/v1/wallets/$FROM_WALLET_ID/payment \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "'$TO_PUBLIC_KEY'",
    "amount": "'$AMOUNT'",
    "asset": "'$ASSET'",
    "memo": "'$MEMO'"
  }')

# Check if payment was successful
if echo $PAYMENT_RESPONSE | jq -e '.success' > /dev/null; then
  TX_HASH=$(echo $PAYMENT_RESPONSE | jq -r '.data.transaction_hash')
  echo "✅ Payment sent successfully!"
  echo "🔗 Transaction hash: $TX_HASH"
  
  # Wait a moment and check transaction status
  sleep 2
  echo "🔍 Checking transaction status..."
  
  # Get updated transaction history
  HISTORY=$(curl -s $API_BASE/api/v1/wallets/$FROM_WALLET_ID/transactions \
    -H "Authorization: Bearer $TOKEN")
  
  TX_STATUS=$(echo $HISTORY | jq -r '.data.transactions[] | select(.hash=="'$TX_HASH'") | .status')
  echo "📊 Transaction status: $TX_STATUS"
  
else
  echo "❌ Payment failed:"
  echo $PAYMENT_RESPONSE | jq '.error'
fi

External Wallet Verification

Verify ownership of existing Stellar wallets using SEP-10 standards.

Challenge-Response Verification

#!/bin/bash

# External wallet verification
API_BASE="https://quasarflow.dev/api"
PUBLIC_KEY="GABC123..."  # User's existing Stellar wallet

echo "🔐 Starting external wallet verification for: $PUBLIC_KEY"

# 1. Generate challenge
echo "📝 Generating challenge..."
CHALLENGE_RESPONSE=$(curl -s $API_BASE/api/v1/accounts/$PUBLIC_KEY/challenge)

if ! echo $CHALLENGE_RESPONSE | jq -e '.success' > /dev/null; then
  echo "❌ Failed to generate challenge:"
  echo $CHALLENGE_RESPONSE | jq '.error'
  exit 1
fi

CHALLENGE=$(echo $CHALLENGE_RESPONSE | jq -r '.data.challenge')
EXPIRES_AT=$(echo $CHALLENGE_RESPONSE | jq -r '.data.expires_at')

echo "✅ Challenge generated"
echo "⏰ Expires at: $EXPIRES_AT"

# 2. Sign challenge (this would be done client-side with Stellar SDK)
echo "✍️  Signing challenge..."
echo "Note: In a real application, this would be done client-side with the Stellar SDK"
echo "Challenge to sign: $CHALLENGE"

# For demo purposes, we'll simulate a signature
# In reality, you would use the Stellar SDK to sign with the private key
SIGNATURE="simulated_signature_$(date +%s)"

echo "🔏 Signature: $SIGNATURE"

# 3. Verify ownership
echo "🔍 Verifying ownership..."
VERIFY_RESPONSE=$(curl -s -X POST $API_BASE/api/v1/accounts/$PUBLIC_KEY/verify-ownership \
  -H "Content-Type: application/json" \
  -d '{
    "signature": "'$SIGNATURE'",
    "message": "'$CHALLENGE'"
  }')

if echo $VERIFY_RESPONSE | jq -e '.success' > /dev/null; then
  VERIFIED=$(echo $VERIFY_RESPONSE | jq -r '.data.verified')
  if [ "$VERIFIED" = "true" ]; then
    echo "✅ Wallet ownership verified successfully!"
    echo "🔑 Public key: $PUBLIC_KEY"
    echo "⏰ Verified at: $(echo $VERIFY_RESPONSE | jq -r '.data.verified_at')"
  else
    echo "❌ Wallet ownership verification failed"
  fi
else
  echo "❌ Verification request failed:"
  echo $VERIFY_RESPONSE | jq '.error'
fi

Transaction-Based Verification

#!/bin/bash

# Alternative verification using recent transaction
API_BASE="https://quasarflow.dev/api"
PUBLIC_KEY="GABC123..."
TRANSACTION_HASH="abc123def456..."  # Recent transaction from the wallet

echo "🔐 Verifying wallet ownership via transaction: $TRANSACTION_HASH"

# Verify using transaction proof
VERIFY_RESPONSE=$(curl -s -X POST $API_BASE/api/v1/accounts/$PUBLIC_KEY/verify-transaction \
  -H "Content-Type: application/json" \
  -d '{
    "transaction_hash": "'$TRANSACTION_HASH'"
  }')

if echo $VERIFY_RESPONSE | jq -e '.success' > /dev/null; then
  VERIFIED=$(echo $VERIFY_RESPONSE | jq -r '.data.verified')
  if [ "$VERIFIED" = "true" ]; then
    echo "✅ Wallet ownership verified via transaction!"
    echo "🔑 Public key: $PUBLIC_KEY"
    echo "🔗 Transaction: $TRANSACTION_HASH"
  else
    echo "❌ Transaction verification failed"
  fi
else
  echo "❌ Verification request failed:"
  echo $VERIFY_RESPONSE | jq '.error'
fi

JavaScript SDK

Use QuasarFlow API in your JavaScript/Node.js applications.

Installation

Setup
1# Note: SDKs are planned for future releases
2# For now, use direct HTTP requests or build your own client
3
4# Clone the API repository
5git clone https://github.com/QuasarAPI/quasarflow-api.git
6cd quasarflow-api
7
8# Start the API server
9docker-compose up -d

Basic Usage (HTTP Client)

JavaScript Example
1// Using fetch API or axios for HTTP requests
2const API_BASE = 'https://quasarflow.dev/api';
3
4async function walletExample() {
5  try {
6    // Login
7    const loginResponse = await fetch(`${API_BASE}/auth/login`, {
8      method: 'POST',
9      headers: { 'Content-Type': 'application/json' },
10      body: JSON.stringify({
11        username: 'admin',
12        password: 'admin123'
13      })
14    });
15    
16    const { data: { token } } = await loginResponse.json();
17    console.log('✅ Logged in successfully');
18
19    // Create wallet
20    const walletResponse = await fetch(`${API_BASE}/api/v1/wallets`, {
21      method: 'POST',
22      headers: {
23        'Authorization': `Bearer ${token}`,
24        'Content-Type': 'application/json'
25      },
26      body: JSON.stringify({ network: 'testnet' })
27    });
28    
29    const { data: wallet } = await walletResponse.json();
30    console.log('💰 Wallet created:', wallet.id);
31
32    // Fund wallet (development only)
33    await fetch(`${API_BASE}/api/v1/wallets/${wallet.id}/fund`, {
34      method: 'POST',
35      headers: { 'Authorization': `Bearer ${token}` }
36    });
37    console.log('💸 Wallet funded');
38
39    // Check balance
40    const balanceResponse = await fetch(`${API_BASE}/api/v1/wallets/${wallet.id}/balance`, {
41      headers: { 'Authorization': `Bearer ${token}` }
42    });
43    const { data: balance } = await balanceResponse.json();
44    console.log('📊 Balance:', balance);
45
46    // Send payment
47    const paymentResponse = await fetch(`${API_BASE}/api/v1/wallets/${wallet.id}/payment`, {
48      method: 'POST',
49      headers: {
50        'Authorization': `Bearer ${token}`,
51        'Content-Type': 'application/json'
52      },
53      body: JSON.stringify({
54        to: 'GDEF456...',
55        amount: '10.5',
56        asset: 'XLM',
57        memo: 'Payment for services'
58      })
59    });
60    
61    const { data: payment } = await paymentResponse.json();
62    console.log('💸 Payment sent:', payment.transaction_hash);
63
64  } catch (error) {
65    console.error('❌ Error:', error.message);
66  }
67}
68
69walletExample();

External Wallet Verification

import { QuasarFlowClient } from 'quasarflow-sdk';
import { Keypair } from 'stellar-sdk';

const client = new QuasarFlowClient({
  baseUrl: 'https://quasarflow.dev/api'
});

async function verifyExternalWallet() {
  try {
    const publicKey = 'GABC123...';
    const privateKey = 'S...'; // User's private key (keep secure!)

    // Generate challenge
    const challenge = await client.accounts.generateChallenge(publicKey);
    console.log('📝 Challenge generated');

    // Sign challenge with Stellar SDK
    const keypair = Keypair.fromSecret(privateKey);
    const signature = keypair.sign(challenge.challenge);

    // Verify ownership
    const verification = await client.accounts.verifyOwnership(publicKey, {
      signature: signature.toString('base64'),
      message: challenge.challenge
    });

    if (verification.verified) {
      console.log('✅ Wallet ownership verified!');
    } else {
      console.log('❌ Verification failed');
    }

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

verifyExternalWallet();

Python SDK

Use QuasarFlow API in your Python applications.

Installation

# Note: Python SDK is planned for future releases
# For now, use requests library for HTTP calls

pip install requests

Basic Usage

from quasarflow import QuasarFlowClient

# Initialize client
client = QuasarFlowClient(
    base_url='https://quasarflow.dev/api',
    username='admin',
    password='admin123'
)

async def wallet_example():
    try:
        # Login
        await client.auth.login()
        print('✅ Logged in successfully')

        # Create wallet
        wallet = await client.wallets.create(network='testnet')
        print(f'💰 Wallet created: {wallet.id}')

        # Fund wallet (development only)
        await client.wallets.fund(wallet.id)
        print('💸 Wallet funded')

        # Check balance
        balance = await client.wallets.get_balance(wallet.id)
        print(f'📊 Balance: {balance}')

        # Send payment
        payment = await client.wallets.send_payment(wallet.id, {
            'to': 'GDEF456...',
            'amount': '10.5',
            'asset': 'XLM',
            'memo': 'Payment for services'
        })
        print(f'💸 Payment sent: {payment.transaction_hash}')

        # Get transaction history
        transactions = await client.wallets.get_transactions(wallet.id)
        print(f'📜 Transactions: {transactions}')

    except Exception as error:
        print(f'❌ Error: {error}')

# Run the example
import asyncio
asyncio.run(wallet_example())

Go SDK

Use QuasarFlow API in your Go applications.

Installation

# Note: Go SDK is planned for future releases
# For now, use net/http package for HTTP calls

# No additional dependencies needed - use standard library

Basic Usage

package main

import (
    "fmt"
    "log"
    "github.com/QuasarAPI/quasarflow-go-sdk"
)

func main() {
    // Initialize client
    client := quasarflow.NewClient(&quasarflow.Config{
        BaseURL:  "https://quasarflow.dev/api",
        Username: "admin",
        Password: "admin123",
    })

    // Login
    err := client.Auth.Login()
    if err != nil {
        log.Fatalf("❌ Login failed: %v", err)
    }
    fmt.Println("✅ Logged in successfully")

    // Create wallet
    wallet, err := client.Wallets.Create(&quasarflow.CreateWalletRequest{
        Network: "testnet",
    })
    if err != nil {
        log.Fatalf("❌ Failed to create wallet: %v", err)
    }
    fmt.Printf("💰 Wallet created: %s\n", wallet.ID)

    // Fund wallet (development only)
    err = client.Wallets.Fund(wallet.ID)
    if err != nil {
        log.Fatalf("❌ Failed to fund wallet: %v", err)
    }
    fmt.Println("💸 Wallet funded")

    // Check balance
    balance, err := client.Wallets.GetBalance(wallet.ID)
    if err != nil {
        log.Fatalf("❌ Failed to get balance: %v", err)
    }
    fmt.Printf("📊 Balance: %+v\n", balance)

    // Send payment
    payment, err := client.Wallets.SendPayment(wallet.ID, &quasarflow.PaymentRequest{
        To:     "GDEF456...",
        Amount: "10.5",
        Asset:  "XLM",
        Memo:   "Payment for services",
    })
    if err != nil {
        log.Fatalf("❌ Failed to send payment: %v", err)
    }
    fmt.Printf("💸 Payment sent: %s\n", payment.TransactionHash)

    // Get transaction history
    transactions, err := client.Wallets.GetTransactions(wallet.ID)
    if err != nil {
        log.Fatalf("❌ Failed to get transactions: %v", err)
    }
    fmt.Printf("📜 Transactions: %+v\n", transactions)
}

Webhook Integration

Set up webhooks to receive real-time notifications about wallet events.

Webhook Endpoint Setup

from flask import Flask, request, jsonify
import hmac
import hashlib
import json

app = Flask(__name__)

# Your webhook secret (configured in QuasarFlow)
WEBHOOK_SECRET = "your_webhook_secret_here"

def verify_webhook_signature(payload, signature):
    """Verify webhook signature for security"""
    expected_signature = hmac.new(
        WEBHOOK_SECRET.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    
    return hmac.compare_digest(f"sha256={expected_signature}", signature)

@app.route('/webhook/quasarflow', methods=['POST'])
def handle_webhook():
    # Get the signature from headers
    signature = request.headers.get('X-QuasarFlow-Signature')
    if not signature:
        return jsonify({'error': 'Missing signature'}), 400
    
    # Verify signature
    if not verify_webhook_signature(request.data, signature):
        return jsonify({'error': 'Invalid signature'}), 401
    
    # Parse webhook payload
    payload = request.get_json()
    event_type = payload.get('type')
    
    print(f"📨 Received webhook: {event_type}")
    
    # Handle different event types
    if event_type == 'wallet.created':
        handle_wallet_created(payload['data'])
    elif event_type == 'payment.sent':
        handle_payment_sent(payload['data'])
    elif event_type == 'payment.received':
        handle_payment_received(payload['data'])
    elif event_type == 'transaction.confirmed':
        handle_transaction_confirmed(payload['data'])
    else:
        print(f"⚠️  Unknown event type: {event_type}")
    
    return jsonify({'status': 'success'})

def handle_wallet_created(data):
    """Handle wallet creation event"""
    wallet_id = data['id']
    public_key = data['public_key']
    print(f"💰 New wallet created: {wallet_id} ({public_key})")
    
    # Your business logic here
    # e.g., update database, send notification, etc.

def handle_payment_sent(data):
    """Handle payment sent event"""
    wallet_id = data['wallet_id']
    amount = data['amount']
    asset = data['asset']
    to = data['to']
    tx_hash = data['transaction_hash']
    
    print(f"💸 Payment sent from {wallet_id}: {amount} {asset} to {to}")
    print(f"🔗 Transaction: {tx_hash}")
    
    # Your business logic here

def handle_payment_received(data):
    """Handle payment received event"""
    wallet_id = data['wallet_id']
    amount = data['amount']
    asset = data['asset']
    from_addr = data['from']
    tx_hash = data['transaction_hash']
    
    print(f"💰 Payment received in {wallet_id}: {amount} {asset} from {from_addr}")
    print(f"🔗 Transaction: {tx_hash}")
    
    # Your business logic here

def handle_transaction_confirmed(data):
    """Handle transaction confirmation event"""
    tx_hash = data['transaction_hash']
    status = data['status']
    
    print(f"✅ Transaction confirmed: {tx_hash} (status: {status})")
    
    # Your business logic here

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

Webhook Configuration

# Configure webhook in QuasarFlow
curl -X POST https://quasarflow.dev/api/v1/webhooks \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://yourdomain.com/webhook/quasarflow",
    "events": [
      "wallet.created",
      "payment.sent",
      "payment.received",
      "transaction.confirmed"
    ],
    "secret": "your_webhook_secret_here"
  }'

Webhook Events

  • wallet.created - New wallet created
  • payment.sent - Payment sent from wallet
  • payment.received - Payment received in wallet
  • transaction.confirmed - Transaction confirmed on blockchain