Examples / Ví dụ

English | Tiếng Việt

English

Basic Examples

Simple Payment

import { OlymPaySDK } from '@olympay/sdk';

const olymPay = new OlymPaySDK({
  apiKey: 'your-api-key',
  network: 'mainnet'
});

// Create and execute a simple payment
async function makePayment() {
  try {
    const payment = await olymPay.createPayment({
      amount: '100.00',
      currency: 'USD',
      recipient: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
      description: 'Payment for services'
    });

    const result = await payment.execute();
    
    if (result.success) {
      console.log('Payment successful:', result.transactionHash);
    } else {
      console.error('Payment failed:', result.error);
    }
  } catch (error) {
    console.error('Error:', error.message);
  }
}

makePayment();

Wallet Connection

// Connect wallet and get balance
async function connectWallet() {
  try {
    const wallet = await olymPay.connectWallet();
    const address = wallet.getAddress();
    const balance = await wallet.getBalance();
    
    console.log('Connected wallet:', address);
    console.log('Balance:', balance);
    
    return { address, balance };
  } catch (error) {
    console.error('Wallet connection failed:', error.message);
  }
}

connectWallet();

E-commerce Examples

Online Store Integration

class OnlineStore {
  constructor(olymPay) {
    this.olymPay = olymPay;
    this.merchantWallet = '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6';
  }

  async processOrder(order) {
    try {
      // Create payment for order
      const payment = await this.olymPay.createPayment({
        amount: order.total.toString(),
        currency: 'USD',
        recipient: this.merchantWallet,
        description: `Order #${order.id}`,
        metadata: {
          orderId: order.id,
          customerId: order.customerId,
          items: order.items
        }
      });

      // Execute payment
      const result = await payment.execute();

      if (result.success) {
        // Update order status
        await this.updateOrderStatus(order.id, 'paid');
        
        // Send confirmation email
        await this.sendConfirmationEmail(order.customerId, result.transactionHash);
        
        return {
          success: true,
          transactionHash: result.transactionHash,
          orderId: order.id
        };
      } else {
        throw new Error(result.error.message);
      }
    } catch (error) {
      console.error('Order processing failed:', error);
      return { success: false, error: error.message };
    }
  }

  async updateOrderStatus(orderId, status) {
    // Your order status update logic
    console.log(`Order ${orderId} status updated to ${status}`);
  }

  async sendConfirmationEmail(customerId, transactionHash) {
    // Your email sending logic
    console.log(`Confirmation email sent to customer ${customerId} for transaction ${transactionHash}`);
  }
}

// Usage
const store = new OnlineStore(olymPay);
const order = {
  id: 'order-123',
  total: 150.00,
  customerId: 'customer-456',
  items: [
    { name: 'Product A', price: 100.00 },
    { name: 'Product B', price: 50.00 }
  ]
};

store.processOrder(order);

DeFi Examples

Liquidity Pool Management

class LiquidityManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async createPool(tokenA, tokenB, amountA, amountB) {
    try {
      const pool = await this.olymPay.createLiquidityPool({
        tokenA: tokenA,
        tokenB: tokenB,
        amountA: amountA,
        amountB: amountB,
        fee: '0.3%'
      });

      console.log('Pool created:', pool.poolId);
      return pool;
    } catch (error) {
      console.error('Pool creation failed:', error);
      throw error;
    }
  }

  async addLiquidity(poolId, amountA, amountB) {
    try {
      const liquidity = await this.olymPay.addLiquidity({
        poolId: poolId,
        amountA: amountA,
        amountB: amountB
      });

      console.log('Liquidity added:', liquidity.liquidityTokens);
      return liquidity;
    } catch (error) {
      console.error('Add liquidity failed:', error);
      throw error;
    }
  }

  async removeLiquidity(poolId, liquidityTokens) {
    try {
      const result = await this.olymPay.removeLiquidity({
        poolId: poolId,
        liquidityTokens: liquidityTokens
      });

      console.log('Liquidity removed:', result.amounts);
      return result;
    } catch (error) {
      console.error('Remove liquidity failed:', error);
      throw error;
    }
  }
}

// Usage
const liquidityManager = new LiquidityManager(olymPay);

// Create USDC/ETH pool
liquidityManager.createPool('USDC', 'ETH', '10000.00', '5.0');

// Add liquidity
liquidityManager.addLiquidity('pool-123', '1000.00', '0.5');

Yield Farming

class YieldFarmer {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async startFarming(strategy, asset, amount) {
    try {
      const farming = await this.olymPay.earning.yield.start({
        strategy: strategy,
        asset: asset,
        amount: amount
      });

      console.log('Farming started:', farming.farmingId);
      return farming;
    } catch (error) {
      console.error('Farming start failed:', error);
      throw error;
    }
  }

  async checkRewards(farmingId) {
    try {
      const rewards = await this.olymPay.earning.yield.getRewards(farmingId);
      console.log('Current rewards:', rewards);
      return rewards;
    } catch (error) {
      console.error('Get rewards failed:', error);
      throw error;
    }
  }

  async claimRewards(farmingId) {
    try {
      const result = await this.olymPay.earning.yield.claimRewards(farmingId);
      console.log('Rewards claimed:', result.amount);
      return result;
    } catch (error) {
      console.error('Claim rewards failed:', error);
      throw error;
    }
  }
}

// Usage
const farmer = new YieldFarmer(olymPay);

// Start yield farming
farmer.startFarming('supply', 'USDC', '1000.00');

// Check and claim rewards
setInterval(async () => {
  const rewards = await farmer.checkRewards('farming-123');
  if (rewards.amount > 0) {
    await farmer.claimRewards('farming-123');
  }
}, 3600000); // Check every hour

Cross-Chain Examples

CCIP Cross-Chain Transfer

class CrossChainManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async transferTokens(sourceChain, destinationChain, token, amount, recipient) {
    try {
      const transfer = await this.olymPay.ccip.createTransfer({
        sourceChain: sourceChain,
        destinationChain: destinationChain,
        token: token,
        amount: amount,
        recipient: recipient
      });

      const result = await transfer.execute();
      
      console.log('Cross-chain transfer initiated:', result.transferId);
      return result;
    } catch (error) {
      console.error('Cross-chain transfer failed:', error);
      throw error;
    }
  }

  async checkTransferStatus(transferId) {
    try {
      const status = await this.olymPay.ccip.getTransferStatus(transferId);
      console.log('Transfer status:', status);
      return status;
    } catch (error) {
      console.error('Get transfer status failed:', error);
      throw error;
    }
  }
}

// Usage
const crossChain = new CrossChainManager(olymPay);

// Transfer USDC from Ethereum to Polygon
crossChain.transferTokens(
  'ethereum',
  'polygon',
  'USDC',
  '100.00',
  '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6'
);

Earning Platform Examples

Quest System

class QuestManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async startQuest(questType, category, difficulty) {
    try {
      const quest = await this.olymPay.earning.quest.start({
        questType: questType,
        category: category,
        difficulty: difficulty
      });

      console.log('Quest started:', quest.questId);
      return quest;
    } catch (error) {
      console.error('Quest start failed:', error);
      throw error;
    }
  }

  async completeQuestStep(questId, stepId) {
    try {
      const result = await this.olymPay.earning.quest.completeStep({
        questId: questId,
        stepId: stepId
      });

      console.log('Quest step completed:', result);
      return result;
    } catch (error) {
      console.error('Complete quest step failed:', error);
      throw error;
    }
  }

  async getQuestProgress(questId) {
    try {
      const progress = await this.olymPay.earning.quest.getProgress(questId);
      console.log('Quest progress:', progress);
      return progress;
    } catch (error) {
      console.error('Get quest progress failed:', error);
      throw error;
    }
  }
}

// Usage
const questManager = new QuestManager(olymPay);

// Start a DeFi quiz
questManager.startQuest('challenger', 'defi', 'beginner');

// Complete quiz steps
questManager.completeQuestStep('quest-123', 'step-1');
questManager.completeQuestStep('quest-123', 'step-2');

Error Handling Examples

Comprehensive Error Handling

class ErrorHandler {
  static async handlePaymentError(error) {
    switch (error.code) {
      case 'INSUFFICIENT_BALANCE':
        return {
          message: 'Insufficient balance for this transaction',
          action: 'Please add funds to your wallet',
          retry: false
        };
      
      case 'NETWORK_ERROR':
        return {
          message: 'Network connection error',
          action: 'Please check your internet connection',
          retry: true,
          retryAfter: 5000
        };
      
      case 'RATE_LIMIT_EXCEEDED':
        return {
          message: 'Too many requests',
          action: 'Please wait and try again',
          retry: true,
          retryAfter: 60000
        };
      
      default:
        return {
          message: 'An unexpected error occurred',
          action: 'Please try again or contact support',
          retry: true,
          retryAfter: 10000
        };
    }
  }

  static async retryOperation(operation, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await operation();
      } catch (error) {
        const errorInfo = await this.handlePaymentError(error);
        
        if (!errorInfo.retry || i === maxRetries - 1) {
          throw error;
        }
        
        console.log(`Retry ${i + 1}/${maxRetries} after ${errorInfo.retryAfter}ms`);
        await new Promise(resolve => setTimeout(resolve, errorInfo.retryAfter));
      }
    }
  }
}

// Usage
async function makePaymentWithRetry() {
  try {
    const result = await ErrorHandler.retryOperation(async () => {
      const payment = await olymPay.createPayment({
        amount: '100.00',
        currency: 'USD',
        recipient: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
        description: 'Payment with retry'
      });
      
      return await payment.execute();
    });
    
    console.log('Payment successful:', result);
  } catch (error) {
    console.error('Payment failed after retries:', error);
  }
}

makePaymentWithRetry();

Tiếng Việt

Ví dụ Cơ bản

Thanh toán Đơn giản

import { OlymPaySDK } from '@olympay/sdk';

const olymPay = new OlymPaySDK({
  apiKey: 'your-api-key',
  network: 'mainnet'
});

// Tạo và thực hiện thanh toán đơn giản
async function makePayment() {
  try {
    const payment = await olymPay.createPayment({
      amount: '100.00',
      currency: 'USD',
      recipient: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
      description: 'Thanh toán cho dịch vụ'
    });

    const result = await payment.execute();
    
    if (result.success) {
      console.log('Thanh toán thành công:', result.transactionHash);
    } else {
      console.error('Thanh toán thất bại:', result.error);
    }
  } catch (error) {
    console.error('Lỗi:', error.message);
  }
}

makePayment();

Kết nối Ví

// Kết nối ví và lấy số dư
async function connectWallet() {
  try {
    const wallet = await olymPay.connectWallet();
    const address = wallet.getAddress();
    const balance = await wallet.getBalance();
    
    console.log('Ví đã kết nối:', address);
    console.log('Số dư:', balance);
    
    return { address, balance };
  } catch (error) {
    console.error('Kết nối ví thất bại:', error.message);
  }
}

connectWallet();

Ví dụ Thương mại điện tử

Tích hợp Cửa hàng Trực tuyến

class OnlineStore {
  constructor(olymPay) {
    this.olymPay = olymPay;
    this.merchantWallet = '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6';
  }

  async processOrder(order) {
    try {
      // Tạo thanh toán cho đơn hàng
      const payment = await this.olymPay.createPayment({
        amount: order.total.toString(),
        currency: 'USD',
        recipient: this.merchantWallet,
        description: `Đơn hàng #${order.id}`,
        metadata: {
          orderId: order.id,
          customerId: order.customerId,
          items: order.items
        }
      });

      // Thực hiện thanh toán
      const result = await payment.execute();

      if (result.success) {
        // Cập nhật trạng thái đơn hàng
        await this.updateOrderStatus(order.id, 'paid');
        
        // Gửi email xác nhận
        await this.sendConfirmationEmail(order.customerId, result.transactionHash);
        
        return {
          success: true,
          transactionHash: result.transactionHash,
          orderId: order.id
        };
      } else {
        throw new Error(result.error.message);
      }
    } catch (error) {
      console.error('Xử lý đơn hàng thất bại:', error);
      return { success: false, error: error.message };
    }
  }

  async updateOrderStatus(orderId, status) {
    // Logic cập nhật trạng thái đơn hàng của bạn
    console.log(`Trạng thái đơn hàng ${orderId} được cập nhật thành ${status}`);
  }

  async sendConfirmationEmail(customerId, transactionHash) {
    // Logic gửi email của bạn
    console.log(`Email xác nhận đã gửi cho khách hàng ${customerId} cho giao dịch ${transactionHash}`);
  }
}

// Sử dụng
const store = new OnlineStore(olymPay);
const order = {
  id: 'order-123',
  total: 150.00,
  customerId: 'customer-456',
  items: [
    { name: 'Sản phẩm A', price: 100.00 },
    { name: 'Sản phẩm B', price: 50.00 }
  ]
};

store.processOrder(order);

Ví dụ DeFi

Quản lý Pool Thanh khoản

class LiquidityManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async createPool(tokenA, tokenB, amountA, amountB) {
    try {
      const pool = await this.olymPay.createLiquidityPool({
        tokenA: tokenA,
        tokenB: tokenB,
        amountA: amountA,
        amountB: amountB,
        fee: '0.3%'
      });

      console.log('Pool đã tạo:', pool.poolId);
      return pool;
    } catch (error) {
      console.error('Tạo pool thất bại:', error);
      throw error;
    }
  }

  async addLiquidity(poolId, amountA, amountB) {
    try {
      const liquidity = await this.olymPay.addLiquidity({
        poolId: poolId,
        amountA: amountA,
        amountB: amountB
      });

      console.log('Đã thêm thanh khoản:', liquidity.liquidityTokens);
      return liquidity;
    } catch (error) {
      console.error('Thêm thanh khoản thất bại:', error);
      throw error;
    }
  }

  async removeLiquidity(poolId, liquidityTokens) {
    try {
      const result = await this.olymPay.removeLiquidity({
        poolId: poolId,
        liquidityTokens: liquidityTokens
      });

      console.log('Đã rút thanh khoản:', result.amounts);
      return result;
    } catch (error) {
      console.error('Rút thanh khoản thất bại:', error);
      throw error;
    }
  }
}

// Sử dụng
const liquidityManager = new LiquidityManager(olymPay);

// Tạo pool USDC/ETH
liquidityManager.createPool('USDC', 'ETH', '10000.00', '5.0');

// Thêm thanh khoản
liquidityManager.addLiquidity('pool-123', '1000.00', '0.5');

Yield Farming

class YieldFarmer {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async startFarming(strategy, asset, amount) {
    try {
      const farming = await this.olymPay.earning.yield.start({
        strategy: strategy,
        asset: asset,
        amount: amount
      });

      console.log('Đã bắt đầu farming:', farming.farmingId);
      return farming;
    } catch (error) {
      console.error('Bắt đầu farming thất bại:', error);
      throw error;
    }
  }

  async checkRewards(farmingId) {
    try {
      const rewards = await this.olymPay.earning.yield.getRewards(farmingId);
      console.log('Phần thưởng hiện tại:', rewards);
      return rewards;
    } catch (error) {
      console.error('Lấy phần thưởng thất bại:', error);
      throw error;
    }
  }

  async claimRewards(farmingId) {
    try {
      const result = await this.olymPay.earning.yield.claimRewards(farmingId);
      console.log('Đã nhận phần thưởng:', result.amount);
      return result;
    } catch (error) {
      console.error('Nhận phần thưởng thất bại:', error);
      throw error;
    }
  }
}

// Sử dụng
const farmer = new YieldFarmer(olymPay);

// Bắt đầu yield farming
farmer.startFarming('supply', 'USDC', '1000.00');

// Kiểm tra và nhận phần thưởng
setInterval(async () => {
  const rewards = await farmer.checkRewards('farming-123');
  if (rewards.amount > 0) {
    await farmer.claimRewards('farming-123');
  }
}, 3600000); // Kiểm tra mỗi giờ

Ví dụ Chuỗi chéo

Chuyển Chuỗi chéo CCIP

class CrossChainManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async transferTokens(sourceChain, destinationChain, token, amount, recipient) {
    try {
      const transfer = await this.olymPay.ccip.createTransfer({
        sourceChain: sourceChain,
        destinationChain: destinationChain,
        token: token,
        amount: amount,
        recipient: recipient
      });

      const result = await transfer.execute();
      
      console.log('Đã bắt đầu chuyển chuỗi chéo:', result.transferId);
      return result;
    } catch (error) {
      console.error('Chuyển chuỗi chéo thất bại:', error);
      throw error;
    }
  }

  async checkTransferStatus(transferId) {
    try {
      const status = await this.olymPay.ccip.getTransferStatus(transferId);
      console.log('Trạng thái chuyển:', status);
      return status;
    } catch (error) {
      console.error('Lấy trạng thái chuyển thất bại:', error);
      throw error;
    }
  }
}

// Sử dụng
const crossChain = new CrossChainManager(olymPay);

// Chuyển USDC từ Ethereum sang Polygon
crossChain.transferTokens(
  'ethereum',
  'polygon',
  'USDC',
  '100.00',
  '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6'
);

Ví dụ Nền tảng Earning

Hệ thống Quest

class QuestManager {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async startQuest(questType, category, difficulty) {
    try {
      const quest = await this.olymPay.earning.quest.start({
        questType: questType,
        category: category,
        difficulty: difficulty
      });

      console.log('Đã bắt đầu quest:', quest.questId);
      return quest;
    } catch (error) {
      console.error('Bắt đầu quest thất bại:', error);
      throw error;
    }
  }

  async completeQuestStep(questId, stepId) {
    try {
      const result = await this.olymPay.earning.quest.completeStep({
        questId: questId,
        stepId: stepId
      });

      console.log('Đã hoàn thành bước quest:', result);
      return result;
    } catch (error) {
      console.error('Hoàn thành bước quest thất bại:', error);
      throw error;
    }
  }

  async getQuestProgress(questId) {
    try {
      const progress = await this.olymPay.earning.quest.getProgress(questId);
      console.log('Tiến độ quest:', progress);
      return progress;
    } catch (error) {
      console.error('Lấy tiến độ quest thất bại:', error);
      throw error;
    }
  }
}

// Sử dụng
const questManager = new QuestManager(olymPay);

// Bắt đầu quiz DeFi
questManager.startQuest('challenger', 'defi', 'beginner');

// Hoàn thành các bước quiz
questManager.completeQuestStep('quest-123', 'step-1');
questManager.completeQuestStep('quest-123', 'step-2');

Ví dụ Xử lý Lỗi

Xử lý Lỗi Toàn diện

class ErrorHandler {
  static async handlePaymentError(error) {
    switch (error.code) {
      case 'INSUFFICIENT_BALANCE':
        return {
          message: 'Số dư không đủ cho giao dịch này',
          action: 'Vui lòng thêm tiền vào ví của bạn',
          retry: false
        };
      
      case 'NETWORK_ERROR':
        return {
          message: 'Lỗi kết nối mạng',
          action: 'Vui lòng kiểm tra kết nối internet',
          retry: true,
          retryAfter: 5000
        };
      
      case 'RATE_LIMIT_EXCEEDED':
        return {
          message: 'Quá nhiều yêu cầu',
          action: 'Vui lòng đợi và thử lại',
          retry: true,
          retryAfter: 60000
        };
      
      default:
        return {
          message: 'Đã xảy ra lỗi không mong muốn',
          action: 'Vui lòng thử lại hoặc liên hệ hỗ trợ',
          retry: true,
          retryAfter: 10000
        };
    }
  }

  static async retryOperation(operation, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await operation();
      } catch (error) {
        const errorInfo = await this.handlePaymentError(error);
        
        if (!errorInfo.retry || i === maxRetries - 1) {
          throw error;
        }
        
        console.log(`Thử lại ${i + 1}/${maxRetries} sau ${errorInfo.retryAfter}ms`);
        await new Promise(resolve => setTimeout(resolve, errorInfo.retryAfter));
      }
    }
  }
}

// Sử dụng
async function makePaymentWithRetry() {
  try {
    const result = await ErrorHandler.retryOperation(async () => {
      const payment = await olymPay.createPayment({
        amount: '100.00',
        currency: 'USD',
        recipient: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
        description: 'Thanh toán với thử lại'
      });
      
      return await payment.execute();
    });
    
    console.log('Thanh toán thành công:', result);
  } catch (error) {
    console.error('Thanh toán thất bại sau khi thử lại:', error);
  }
}

makePaymentWithRetry();