πŸͺ™ Cryptocurrency Ebook
EN KO

Chapter 7: Phase 4 Integration - Exchanges & Custody πŸͺ™

7.1 Introduction to Integration Layer

The Integration Layer bridges the gap between cryptocurrency infrastructure and real-world financial systems. While protocols and APIs enable the technical functioning of cryptocurrency networks, integration determines how these systems connect with traditional finance, regulatory frameworks, and institutional requirements. Phase 4 of WIA-FIN-003 standardizes integration patterns for exchanges, custody solutions, payment processing, and compliance.

This chapter explores the critical integration points that enable cryptocurrency adoption: centralized exchanges (CEXs), decentralized exchanges (DEXs), institutional custody, payment gateways, and regulatory compliance systems. Understanding these integration patterns is essential for anyone building cryptocurrency services that serve real users and businesses.

Why Integration Standards Matter

7.2 Centralized Exchange Architecture

Centralized Exchanges (CEXs) are the primary on-ramp for most cryptocurrency users. These platforms custody user funds, provide trading infrastructure, and interface with traditional banking systems. Building a secure, scalable CEX requires careful architecture across multiple domains.

CEX Core Components

Component Function Critical Requirements
Hot Wallet Online funds for immediate withdrawals Multi-sig, rate limiting, monitoring
Cold Storage Offline storage for majority of funds Hardware wallets, geographic distribution
Matching Engine Order book management and trade execution Low latency (<1ms), high throughput
KYC/AML System User verification and compliance Identity verification, transaction monitoring
Risk Management Fraud detection and prevention Real-time analysis, automated responses
Banking Integration Fiat deposits/withdrawals SWIFT, ACH, card processing

Hot/Cold Wallet Architecture

// Exchange Wallet Management System
class ExchangeWalletSystem {
  private hotWallet: HotWallet;
  private coldStorage: ColdStorage[];
  private readonly hotWalletThreshold = 0.05;  // 5% of total funds

  async processWithdrawal(request: WithdrawalRequest): Promise {
    // 1. Verify user account and balance
    const user = await this.verifyUser(request.userId);
    if (user.balance < request.amount + request.fee) {
      throw new Error('Insufficient balance');
    }

    // 2. Check withdrawal limits (daily/monthly)
    const limits = await this.checkWithdrawalLimits(user, request.amount);
    if (!limits.allowed) {
      throw new Error(`Withdrawal limit exceeded: ${limits.reason}`);
    }

    // 3. Risk assessment
    const riskScore = await this.assessRisk(user, request);
    if (riskScore > 80) {
      await this.flagForManualReview(request);
      throw new Error('Withdrawal flagged for review');
    }

    // 4. Process from hot wallet if available
    if (this.hotWallet.balance >= request.amount) {
      const tx = await this.hotWallet.send({
        to: request.address,
        amount: request.amount,
        priority: request.priority
      });

      // Deduct from user balance
      await this.deductBalance(user.id, request.amount + request.fee);

      // Log withdrawal
      await this.logWithdrawal(user.id, tx.hash, request.amount);

      return tx;
    }

    // 5. Queue for cold storage transfer if hot wallet insufficient
    await this.queueColdStorageTransfer(request);
    throw new Error('Withdrawal queued - requires cold storage transfer');
  }

  async rebalanceWallets(): Promise {
    const totalFunds = await this.getTotalFunds();
    const hotWalletTarget = totalFunds * this.hotWalletThreshold;
    const currentHotBalance = this.hotWallet.balance;

    if (currentHotBalance < hotWalletTarget * 0.5) {
      // Hot wallet below 50% of target - refill from cold storage
      const transferAmount = hotWalletTarget - currentHotBalance;

      console.log(`Rebalancing: Transferring ${transferAmount} from cold to hot wallet`);

      // Requires manual signing from cold storage
      await this.initiateColdToHotTransfer(transferAmount);

    } else if (currentHotBalance > hotWalletTarget * 1.5) {
      // Hot wallet above 150% of target - move excess to cold storage
      const excessAmount = currentHotBalance - hotWalletTarget;

      console.log(`Rebalancing: Moving ${excessAmount} from hot to cold storage`);

      await this.hotWallet.sendToColdStorage(excessAmount);
    }
  }

  async assessRisk(user: User, request: WithdrawalRequest): Promise {
    let riskScore = 0;

    // Check 1: New user (< 30 days)
    if (user.accountAge < 30) riskScore += 20;

    // Check 2: First withdrawal
    if (user.withdrawalCount === 0) riskScore += 15;

    // Check 3: Large amount (> 10% of user's total deposits)
    if (request.amount > user.totalDeposits * 0.1) riskScore += 25;

    // Check 4: New withdrawal address
    if (!user.previousAddresses.includes(request.address)) riskScore += 20;

    // Check 5: High-risk jurisdiction
    if (await this.isHighRiskJurisdiction(request.address)) riskScore += 30;

    // Check 6: Suspicious pattern (multiple small deposits followed by large withdrawal)
    if (await this.detectSuspiciousPattern(user)) riskScore += 40;

    return Math.min(riskScore, 100);
  }
}

Exchange Security Best Practices

⚠️ Critical Security Measures

7.3 Decentralized Exchange (DEX) Integration

Decentralized Exchanges (DEXs) enable trading without centralized custody through smart contracts and automated market makers (AMMs). DEX integration allows applications to access decentralized liquidity while maintaining user control of funds.

AMM (Automated Market Maker) Model

Unlike traditional order books, AMMs use liquidity pools and mathematical formulas to determine prices. The most common formula is the constant product model: x * y = k

// Uniswap-style AMM Implementation
class AutomatedMarketMaker {
  private reserveA: number;  // Token A reserve
  private reserveB: number;  // Token B reserve
  private readonly feePercent = 0.3;  // 0.3% trading fee

  constructor(initialReserveA: number, initialReserveB: number) {
    this.reserveA = initialReserveA;
    this.reserveB = initialReserveB;
  }

  // Calculate output amount for a given input
  getAmountOut(amountIn: number, reserveIn: number, reserveOut: number): number {
    if (amountIn <= 0) throw new Error('Insufficient input amount');
    if (reserveIn <= 0 || reserveOut <= 0) throw new Error('Insufficient liquidity');

    // Apply trading fee (0.3%)
    const amountInWithFee = amountIn * (100 - this.feePercent) / 100;

    // Constant product formula: x * y = k
    // (x + Ξ”x) * (y - Ξ”y) = k
    // Ξ”y = y * Ξ”x / (x + Ξ”x)
    const numerator = amountInWithFee * reserveOut;
    const denominator = reserveIn + amountInWithFee;

    return numerator / denominator;
  }

  // Swap Token A for Token B
  swapAForB(amountA: number): number {
    const amountB = this.getAmountOut(amountA, this.reserveA, this.reserveB);

    // Update reserves
    this.reserveA += amountA;
    this.reserveB -= amountB;

    console.log(`Swapped ${amountA} Token A for ${amountB} Token B`);
    console.log(`New reserves: A=${this.reserveA}, B=${this.reserveB}`);

    return amountB;
  }

  // Add liquidity to the pool
  addLiquidity(amountA: number, amountB: number): number {
    // Calculate liquidity tokens to mint
    const totalLiquidity = Math.sqrt(this.reserveA * this.reserveB);
    const liquidityMinted = Math.sqrt(amountA * amountB);

    // Update reserves
    this.reserveA += amountA;
    this.reserveB += amountB;

    console.log(`Added liquidity: ${amountA} A + ${amountB} B`);
    console.log(`Minted ${liquidityMinted} LP tokens`);

    return liquidityMinted;
  }

  // Get current exchange rate
  getPrice(): number {
    return this.reserveB / this.reserveA;
  }

  // Calculate price impact of a trade
  getPriceImpact(amountIn: number): number {
    const currentPrice = this.getPrice();
    const amountOut = this.getAmountOut(amountIn, this.reserveA, this.reserveB);
    const executionPrice = amountOut / amountIn;

    const impact = Math.abs((executionPrice - currentPrice) / currentPrice) * 100;

    return impact;
  }
}

// Example usage
const pool = new AutomatedMarketMaker(1000000, 2000000);  // 1M Token A, 2M Token B

console.log(`Initial price: ${pool.getPrice()} B per A`);

// Small trade (low impact)
const smallTradeImpact = pool.getPriceImpact(1000);
console.log(`1,000 A trade price impact: ${smallTradeImpact.toFixed(4)}%`);

// Large trade (high impact)
const largeTradeImpact = pool.getPriceImpact(100000);
console.log(`100,000 A trade price impact: ${largeTradeImpact.toFixed(4)}%`);

DEX Aggregation

DEX aggregators route trades across multiple DEXs to find the best price and minimize slippage. This is essential for large trades that would experience significant price impact on a single pool.

// DEX Aggregator - finds best route across multiple DEXs
class DEXAggregator {
  private dexes: DEX[] = [];

  addDEX(dex: DEX): void {
    this.dexes.push(dex);
  }

  // Find best execution across all DEXs
  async getBestPrice(tokenIn: string, tokenOut: string, amountIn: number): Promise {
    const quotes = await Promise.all(
      this.dexes.map(dex =>
        dex.getQuote(tokenIn, tokenOut, amountIn)
      )
    );

    // Sort by output amount (descending)
    const bestQuote = quotes.sort((a, b) => b.amountOut - a.amountOut)[0];

    return {
      dex: bestQuote.dex,
      path: [tokenIn, tokenOut],
      amountIn,
      amountOut: bestQuote.amountOut,
      priceImpact: bestQuote.priceImpact,
      gas: bestQuote.estimatedGas
    };
  }

  // Split large trade across multiple DEXs to minimize price impact
  async optimizeRoute(tokenIn: string, tokenOut: string, amountIn: number): Promise {
    // For large trades, split across multiple pools
    if (amountIn > 100000) {
      const routes: Route[] = [];
      const numSplits = 3;  // Split into 3 routes
      const splitAmount = amountIn / numSplits;

      for (let i = 0; i < numSplits; i++) {
        const route = await this.getBestPrice(tokenIn, tokenOut, splitAmount);
        routes.push(route);
      }

      return routes;
    }

    // Small trade - single route
    return [await this.getBestPrice(tokenIn, tokenOut, amountIn)];
  }

  // Execute trade with slippage protection
  async executeTrade(
    tokenIn: string,
    tokenOut: string,
    amountIn: number,
    minAmountOut: number,
    maxSlippage: number = 0.5  // 0.5% max slippage
  ): Promise {
    const routes = await this.optimizeRoute(tokenIn, tokenOut, amountIn);

    const totalExpectedOut = routes.reduce((sum, route) => sum + route.amountOut, 0);

    // Check slippage
    const slippage = (amountIn / totalExpectedOut - 1) * 100;
    if (slippage > maxSlippage) {
      throw new Error(`Slippage ${slippage.toFixed(2)}% exceeds maximum ${maxSlippage}%`);
    }

    if (totalExpectedOut < minAmountOut) {
      throw new Error(`Expected output ${totalExpectedOut} below minimum ${minAmountOut}`);
    }

    // Execute all routes
    const txs = await Promise.all(
      routes.map(route => this.executeRoute(route))
    );

    return {
      hash: txs[0].hash,  // Primary transaction
      routes: txs.length,
      totalIn: amountIn,
      totalOut: totalExpectedOut
    };
  }
}

7.4 Institutional Custody Solutions

Institutional custody addresses the unique requirements of banks, hedge funds, and other large financial entities. These solutions must provide institutional-grade security, insurance, regulatory compliance, and integration with existing financial infrastructure.

Custody Architecture Tiers

Custody Tier Security Model Target Users Insurance
Self-Custody User controls private keys Individuals, power users None (user responsibility)
Qualified Custody Regulated custodian RIAs, family offices FDIC-style coverage ($250k+)
Prime Brokerage Multi-party computation (MPC) Hedge funds, prop traders Excess liability ($100M+)
Bank-Grade Custody HSM + geographic redundancy Banks, pension funds Lloyd's of London ($1B+)

Multi-Party Computation (MPC) Custody

MPC distributes key generation and signing across multiple parties, eliminating single points of failure. No single party ever possesses the complete private key.

// MPC Custody System (Simplified Threshold Signature Scheme)
class MPCCustody {
  private readonly threshold = 3;  // 3-of-5 signatures required
  private readonly totalParties = 5;
  private keyShares: Map = new Map();

  // Generate distributed key shares (happens once during setup)
  async generateDistributedKey(): Promise {
    console.log('Generating distributed key shares...');

    // Each party generates their secret share
    const shares: KeyShare[] = [];
    for (let i = 1; i <= this.totalParties; i++) {
      const share = await this.generateKeyShare(i);
      shares.push(share);
      this.keyShares.set(`party_${i}`, share);
    }

    // Combine public components to create address
    const publicKey = this.derivePublicKey(shares);

    console.log(`Distributed key generated: ${publicKey.address}`);
    console.log(`Threshold: ${this.threshold}-of-${this.totalParties}`);

    return publicKey;
  }

  // Sign transaction using threshold signatures
  async signTransaction(tx: Transaction, signingParties: string[]): Promise {
    if (signingParties.length < this.threshold) {
      throw new Error(`Insufficient signers: need ${this.threshold}, got ${signingParties.length}`);
    }

    console.log(`Initiating ${this.threshold}-of-${this.totalParties} signature...`);

    // Each party creates partial signature
    const partialSignatures: PartialSignature[] = [];
    for (const partyId of signingParties.slice(0, this.threshold)) {
      const keyShare = this.keyShares.get(partyId);
      if (!keyShare) throw new Error(`Unknown party: ${partyId}`);

      const partialSig = await this.createPartialSignature(tx, keyShare);
      partialSignatures.push(partialSig);

      console.log(`βœ“ Partial signature from ${partyId}`);
    }

    // Combine partial signatures into final signature
    const finalSignature = await this.combineSignatures(partialSignatures);

    console.log(`βœ“ Transaction signed successfully`);

    return finalSignature;
  }

  // Governance approval workflow
  async requestWithdrawal(request: WithdrawalRequest): Promise {
    // 1. Create approval request
    const approvalId = this.createApprovalRequest(request);

    // 2. Notify all parties
    await this.notifyParties(approvalId, request);

    // 3. Collect approvals
    const approvals = await this.collectApprovals(approvalId);

    if (approvals.length < this.threshold) {
      throw new Error('Insufficient approvals');
    }

    // 4. Build and sign transaction
    const tx = await this.buildTransaction(request);
    const signature = await this.signTransaction(tx, approvals);

    // 5. Broadcast transaction
    const txHash = await this.broadcast(tx, signature);

    return txHash;
  }

  // Key rotation (security best practice)
  async rotateKeys(): Promise {
    console.log('Initiating key rotation...');

    // Generate new distributed key
    const newPublicKey = await this.generateDistributedKey();

    // Transfer all funds to new address
    const balance = await this.getCurrentBalance();
    await this.requestWithdrawal({
      to: newPublicKey.address,
      amount: balance,
      reason: 'Key rotation'
    });

    console.log('Key rotation complete');
  }
}

Custody Security Requirements

Security Measure Retail Custody Institutional Custody
Key Storage Software wallet, cloud backup HSM, geographically distributed
Access Control Password + 2FA Multi-party approval + biometrics
Insurance Optional, limited coverage Mandatory, $100M+ coverage
Audit Frequency None required SOC 2 Type II, annual
Disaster Recovery User responsibility RPO: 0 min, RTO: <4 hours
Compliance Basic KYC Full AML/KYC/CFT program

7.5 Payment Gateway Integration

Payment gateways enable merchants to accept cryptocurrency payments alongside traditional payment methods. These integrations must handle price volatility, settlement times, and fiat conversion while providing a simple checkout experience.

Payment Gateway Architecture

// Cryptocurrency Payment Gateway
class CryptoPaymentGateway {
  private readonly settlementDelay = 6;  // Wait for 6 confirmations
  private readonly priceValidityWindow = 15 * 60 * 1000;  // 15 minutes

  // Create payment request
  async createPayment(order: Order): Promise {
    // 1. Get current exchange rate
    const rate = await this.getExchangeRate(order.currency, 'USD');

    // 2. Calculate cryptocurrency amount
    const cryptoAmount = order.amountUSD / rate;

    // 3. Generate unique payment address
    const paymentAddress = await this.generatePaymentAddress(order.id);

    // 4. Create payment request with expiry
    const payment: PaymentRequest = {
      id: `pay_${generateId()}`,
      orderId: order.id,
      currency: order.currency,
      amountCrypto: cryptoAmount,
      amountFiat: order.amountUSD,
      rate: rate,
      address: paymentAddress,
      status: 'pending',
      createdAt: Date.now(),
      expiresAt: Date.now() + this.priceValidityWindow
    };

    // 5. Monitor address for incoming payment
    this.monitorAddress(paymentAddress, payment);

    return payment;
  }

  // Monitor payment address
  private async monitorAddress(address: string, payment: PaymentRequest): Promise {
    const checkInterval = setInterval(async () => {
      // Check if payment expired
      if (Date.now() > payment.expiresAt) {
        clearInterval(checkInterval);
        await this.expirePayment(payment.id);
        return;
      }

      // Check for incoming transaction
      const txs = await this.getIncomingTransactions(address);

      if (txs.length > 0) {
        const tx = txs[0];

        // Validate amount (allow 1% tolerance for network fees)
        if (tx.amount >= payment.amountCrypto * 0.99) {
          clearInterval(checkInterval);

          // Update payment status
          payment.status = 'detected';
          payment.txHash = tx.hash;
          payment.confirmations = tx.confirmations;

          // Notify merchant
          await this.notifyMerchant(payment, 'payment_detected');

          // Wait for confirmations
          await this.waitForConfirmations(tx.hash, payment);
        }
      }
    }, 10000);  // Check every 10 seconds
  }

  // Wait for sufficient confirmations
  private async waitForConfirmations(txHash: string, payment: PaymentRequest): Promise {
    const checkInterval = setInterval(async () => {
      const tx = await this.getTransaction(txHash);

      payment.confirmations = tx.confirmations;

      if (tx.confirmations >= this.settlementDelay) {
        clearInterval(checkInterval);

        // Payment confirmed
        payment.status = 'confirmed';
        payment.confirmedAt = Date.now();

        // Process settlement
        await this.settlePayment(payment);
      }
    }, 60000);  // Check every minute
  }

  // Settle payment (convert to fiat if merchant prefers)
  private async settlePayment(payment: PaymentRequest): Promise {
    const merchant = await this.getMerchant(payment.orderId);

    if (merchant.settlementPreference === 'fiat') {
      // Convert to fiat
      const fiatAmount = await this.convertToFiat(
        payment.amountCrypto,
        payment.currency,
        'USD'
      );

      // Transfer to merchant bank account
      await this.transferToBank(merchant.bankAccount, fiatAmount);

      payment.settlementAmount = fiatAmount;
      payment.settlementCurrency = 'USD';

    } else {
      // Keep in cryptocurrency
      await this.transferCrypto(merchant.cryptoAddress, payment.amountCrypto);

      payment.settlementAmount = payment.amountCrypto;
      payment.settlementCurrency = payment.currency;
    }

    payment.status = 'settled';
    payment.settledAt = Date.now();

    // Notify merchant
    await this.notifyMerchant(payment, 'payment_settled');

    // Mark order as paid
    await this.completeOrder(payment.orderId);
  }

  // Handle underpayment
  private async handleUnderpayment(payment: PaymentRequest, actualAmount: number): Promise {
    const shortfall = payment.amountCrypto - actualAmount;
    const percentShort = (shortfall / payment.amountCrypto) * 100;

    if (percentShort < 2) {
      // Accept payment with <2% shortfall
      console.log(`Accepting underpayment: ${percentShort.toFixed(2)}% short`);
      await this.settlePayment(payment);
    } else {
      // Request additional payment
      payment.status = 'underpaid';
      payment.additionalRequired = shortfall;

      await this.notifyMerchant(payment, 'underpayment_detected');
    }
  }
}

7.6 Regulatory Compliance Integration

Compliance systems enable cryptocurrency businesses to meet regulatory requirements including KYC (Know Your Customer), AML (Anti-Money Laundering), and CFT (Combating Financing of Terrorism). Proper compliance integration is mandatory for licensed operations.

Compliance Workflow

// Compliance Management System
class ComplianceSystem {
  private riskThresholds = {
    low: 1000,      // $1,000
    medium: 10000,  // $10,000
    high: 100000    // $100,000
  };

  // KYC verification levels
  async verifyUser(user: User): Promise {
    // Level 1: Email + Phone
    if (!user.emailVerified || !user.phoneVerified) {
      return 'none';
    }

    // Level 2: Basic KYC (Name, DOB, Address)
    if (!user.identityVerified) {
      return 'basic';
    }

    // Level 3: Enhanced KYC (Government ID, Selfie)
    if (!user.documentVerified) {
      return 'intermediate';
    }

    // Level 4: Full KYC (Source of funds, Utility bill)
    if (!user.sourceOfFundsVerified) {
      return 'enhanced';
    }

    return 'full';
  }

  // Transaction monitoring for suspicious activity
  async monitorTransaction(tx: Transaction): Promise {
    const alerts: ComplianceAlert[] = [];

    // Check 1: Transaction amount
    if (tx.amount > this.riskThresholds.high) {
      alerts.push({
        type: 'HIGH_VALUE',
        severity: 'high',
        message: `Large transaction: $${tx.amount.toLocaleString()}`,
        requiresReview: true
      });
    }

    // Check 2: Sanctioned addresses
    if (await this.isSanctionedAddress(tx.toAddress)) {
      alerts.push({
        type: 'SANCTIONED_ADDRESS',
        severity: 'critical',
        message: 'Transaction to sanctioned address',
        requiresReview: true,
        blockTransaction: true
      });
    }

    // Check 3: Structuring detection (smurfing)
    const recentTxs = await this.getRecentTransactions(tx.fromAddress, 24);
    if (this.detectStructuring(recentTxs)) {
      alerts.push({
        type: 'STRUCTURING',
        severity: 'high',
        message: 'Potential structuring detected',
        requiresReview: true
      });
    }

    // Check 4: Rapid movement (possible tumbling)
    if (await this.detectRapidMovement(tx)) {
      alerts.push({
        type: 'RAPID_MOVEMENT',
        severity: 'medium',
        message: 'Funds moved through multiple addresses quickly',
        requiresReview: true
      });
    }

    // Check 5: High-risk jurisdiction
    const jurisdiction = await this.getJurisdiction(tx.toAddress);
    if (this.isHighRiskJurisdiction(jurisdiction)) {
      alerts.push({
        type: 'HIGH_RISK_JURISDICTION',
        severity: 'medium',
        message: `Transaction to ${jurisdiction}`,
        requiresReview: true
      });
    }

    // File SAR if critical alerts
    if (alerts.some(a => a.severity === 'critical')) {
      await this.fileSAR(tx, alerts);
    }

    return alerts;
  }

  // Suspicious Activity Report (SAR) filing
  private async fileSAR(tx: Transaction, alerts: ComplianceAlert[]): Promise {
    const report: SAR = {
      id: `SAR-${Date.now()}`,
      timestamp: new Date(),
      transaction: tx,
      alerts: alerts,
      filingEntity: 'WIA Crypto Exchange',
      regulatoryBody: 'FinCEN',
      status: 'filed'
    };

    // Submit to regulatory authority
    await this.submitToFinCEN(report);

    // Freeze account if necessary
    if (alerts.some(a => a.blockTransaction)) {
      await this.freezeAccount(tx.fromAddress);
    }

    console.log(`SAR filed: ${report.id}`);
  }

  // Travel Rule compliance (FATF)
  async applyTravelRule(tx: Transaction): Promise {
    // Travel Rule requires originator/beneficiary information for txs >$1000
    if (tx.amount >= 1000) {
      if (!tx.originatorInfo || !tx.beneficiaryInfo) {
        throw new Error('Travel Rule: Missing originator/beneficiary information');
      }

      // Exchange information with receiving VASP
      await this.exchangeVASPInfo(tx);
    }

    return true;
  }
}

Chapter Summary

Key Takeaways:

  1. Exchange Architecture: CEXs require hot/cold wallet separation, multi-sig security, risk management, and careful balance between security and operational efficiency for withdrawals.
  2. DEX Integration: Automated Market Makers (AMMs) enable decentralized trading through liquidity pools, with aggregators optimizing routes across multiple DEXs to minimize price impact and slippage.
  3. Institutional Custody: Enterprise-grade custody uses Multi-Party Computation (MPC), Hardware Security Modules (HSMs), and geographic redundancy to eliminate single points of failure while maintaining $100M+ insurance coverage.
  4. Payment Integration: Cryptocurrency payment gateways handle price volatility through time-limited quotes, monitor confirmations, and provide merchants with fiat settlement options.
  5. Compliance Systems: Tiered KYC verification, transaction monitoring, SAR filing, and Travel Rule compliance are mandatory for regulated cryptocurrency operations.

Review Questions

  1. Explain the hot/cold wallet architecture. What percentage of funds should be kept in each, and what security measures protect hot wallets?
  2. How do Automated Market Makers (AMMs) determine prices? Describe the constant product formula and explain price impact.
  3. What is Multi-Party Computation (MPC) custody? How does it eliminate single points of failure compared to traditional multi-sig wallets?
  4. Design a cryptocurrency payment gateway that handles price volatility. How long should price quotes be valid, and how many confirmations should be required?
  5. Describe transaction monitoring for AML compliance. What patterns indicate potential money laundering, and when should a SAR be filed?
  6. Compare centralized and decentralized exchanges. What are the security, regulatory, and user experience tradeoffs of each model?

Looking Ahead

Chapter 8 concludes our ebook with Implementation and WIA Certification. We'll explore how to implement the complete WIA-FIN-003 standard, achieve certification, and build production-ready cryptocurrency systems that meet institutional requirements while advancing the philosophy of εΌ˜η›ŠδΊΊι–“ (Benefit All Humanity).

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ β€” totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology β€” 70+ Korean standardization-related laws.