PHP WebShell

Текущая директория: /var/www/bitcardoApp/user/crypto

Просмотр файла: swap_old.php

<?php
/**
 * user/crypto/swap_old.php
 **/
      require_once "../../config/db_config.php";
      if (!isset($_SESSION)) {
        session_start();
      }
      
      if (!isset($_SESSION['user_id'])) {
        header("Location: ../../auth/login.php");
        exit();
      }

      $user_id = $_SESSION['user_id'];

      // === Handle AJAX swap quote ===
      if (isset($_GET['ajax']) && $_GET['ajax'] === 'quote') {
        header('Content-Type: application/json');

        $from = strtoupper($_GET['from'] ?? '');
        $to = strtoupper($_GET['to'] ?? '');
        $amount = floatval($_GET['amount'] ?? 0);

        if (!$from || !$to || $amount <= 0) {
          echo json_encode(['error' => 'Invalid input']);
          exit;
        }

        // Special logic for USDT <-> NGN
        if (($from === 'USDT' && $to === 'NGN') || ($from === 'NGN' && $to === 'USDT')) {
          if ($from === 'USDT' && $to === 'NGN') {
            // USDT to NGN: multiply by NGN sell_rate
            $stmt = $conn->prepare("SELECT sell_rate FROM coin_rates WHERE UPPER(coin) = 'NGN'");
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $rate = (float)($row['sell_rate'] ?? 0);
            $to_amount = $amount * $rate;
          } else {
            // NGN to USDT: divide by NGN buy_rate
            $stmt = $conn->prepare("SELECT buy_rate FROM coin_rates WHERE UPPER(coin) = 'NGN'");
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();
            $rate = (float)($row['buy_rate'] ?? 0);
            $to_amount = $rate > 0 ? $amount / $rate : 0;
          }
        } elseif ($to === 'USDT') {
          // Coin → USDT: use buy_rate of coin
          $stmt = $conn->prepare("SELECT buy_rate FROM coin_rates WHERE UPPER(coin) = ?");
          $stmt->bind_param("s", $from);
          $stmt->execute();
          $row = $stmt->get_result()->fetch_assoc();
          $rate = (float)($row['buy_rate'] ?? 0);
          $to_amount = $amount * $rate;
        } elseif ($from === 'USDT') {
          // USDT → Coin: use sell_rate of coin
          $stmt = $conn->prepare("SELECT sell_rate FROM coin_rates WHERE UPPER(coin) = ?");
          $stmt->bind_param("s", $to);
          $stmt->execute();
          $row = $stmt->get_result()->fetch_assoc();
          $rate = (float)($row['sell_rate'] ?? 0);
          $to_amount = $rate > 0 ? $amount / $rate : 0;
        } else {
          // Coin → Coin: from → USDT (buy_rate), then USDT → to (sell_rate)
          $stmt = $conn->prepare("SELECT buy_rate FROM coin_rates WHERE UPPER(coin) = ?");
          $stmt->bind_param("s", $from);
          $stmt->execute();
          $row = $stmt->get_result()->fetch_assoc();
          $buy_rate = (float)($row['buy_rate'] ?? 0);
          $usdt_value = $amount * $buy_rate;

          $stmt = $conn->prepare("SELECT sell_rate FROM coin_rates WHERE UPPER(coin) = ?");
          $stmt->bind_param("s", $to);
          $stmt->execute();
          $row = $stmt->get_result()->fetch_assoc();
          $sell_rate = (float)($row['sell_rate'] ?? 0);

          $to_amount = $sell_rate > 0 ? $usdt_value / $sell_rate : 0;
          $rate = $buy_rate && $sell_rate ? $buy_rate / $sell_rate : 0;
        }

        echo json_encode([
          'rate' => $rate,
          'to_amount' => round($to_amount, 8)
        ]);
        exit;
      }

      // === Fetch user wallet coins and balances ===
      $coins = [];
      $balances = [];
      $min_swaps = [];
      $query = "SELECT uw.coin, uw.balance, cr.min_swap 
                FROM user_wallets uw 
                LEFT JOIN coin_rates cr ON UPPER(uw.coin) = UPPER(cr.coin)
                WHERE uw.user_id = ?";
      $stmt = $conn->prepare($query);
      $stmt->bind_param("i", $user_id);
      $stmt->execute();
      $result = $stmt->get_result();
      while ($row = $result->fetch_assoc()) {
          $coin = strtoupper($row['coin']);
          $coins[] = $coin;
          $balances[$coin] = (float)$row['balance'];
          $min_swaps[$coin] = isset($row['min_swap']) ? (float)$row['min_swap'] : 0;
      }

      $directions = [];
      $dirQuery = "SELECT from_coin, to_coin FROM swap_directions WHERE is_active = 1";
      $dirResult = $conn->query($dirQuery);
      while ($row = $dirResult->fetch_assoc()) {
          $from = strtoupper($row['from_coin']);
          $to = strtoupper($row['to_coin']);
          if (!isset($directions[$from])) {
              $directions[$from] = [];
          }
          $directions[$from][] = $to;
      }
  ?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="containerx py-2">
  <h4 class="mb-3">Asset Swap</h4>
  <form action="../../models/crypto/swap.php" method="POST">
    <div class="mb-3">
      <label for="amountFrom" class="form-label ms-2 d-flex justify-content-between align-items-center">
        <span>You send</span>
        <span id="balanceMsg" class="text-danger small d-none">Insufficient balance</span>
      </label>
      <div class="input-group">
        <input type="number" name="fromAmount" id="amountFrom" class="form-control" placeholder="100.00" step="0.01" required>
        <button class="btn btn-white-outline btn-sm pyx-0 border" type="button" id="useMaxBtn">Max</button>
        <select id="currencyFrom" name="currencyFrom" class="form-select" onchange="updateCurrencyTo()" style="max-width: 100px;" required>
          <?php foreach ($coins as $index => $coin): ?>
            <option value="<?= $coin ?>" <?= $index === 0 ? 'selected' : '' ?>><?= $coin ?></option>
          <?php endforeach; ?>
        </select>
      </div>
    </div>

    <div class="mb-3 mt-3">
      <label for="amountFrom" class="form-label ms-2">You Get</label>
      <div class="input-group">
        <input type="number" id="amountTo" name="toAmount" class="form-control" placeholder="0.00" readonly>
        <select id="currencyTo" name="currencyTo" class="form-select" style="max-width: 100px;" required>
          <!-- JS will populate -->
        </select>
      </div>
    </div>

    <div class="d-grid mt-4">
      <button class="btn btn-primary" id="convertBtn">Convert</button>
    </div>
  </form>

  <script>
  const minSwaps = <?= json_encode($min_swaps) ?>;
  const allowedDirections = <?= json_encode($directions) ?>;
  const userBalances = <?= json_encode($balances) ?>;

  function updateCurrencyTo() {
    const from = document.getElementById("currencyFrom").value;
    const toSelect = document.getElementById("currencyTo");
    toSelect.innerHTML = "";

    const allowed = allowedDirections[from] || [];
    if (allowed.length === 0) {
      const opt = document.createElement("option");
      opt.value = "";
      opt.text = "Not available";
      opt.disabled = true;
      opt.selected = true;
      toSelect.appendChild(opt);
      return;
    }

    allowed.forEach(coin => {
      const opt = document.createElement("option");
      opt.value = coin;
      opt.text = coin;
      toSelect.appendChild(opt);
    });

    toSelect.value = allowed[0];
    getSwapQuote();
  }

  function getSwapQuote() {
    const from = document.getElementById("currencyFrom").value;
    const to = document.getElementById("currencyTo").value;
    const amountInput = document.getElementById("amountFrom");
    const amount = parseFloat(amountInput.value);
    const balance = parseFloat(userBalances[from] || 0);
    const minSwap = parseFloat(minSwaps[from] || 0); 
    const convertBtn = document.getElementById("convertBtn");
    const balanceMsg = document.getElementById("balanceMsg");

    if (!from || !to || isNaN(amount) || amount <= 0) {
      document.getElementById("amountTo").value = "";
      convertBtn.disabled = true;
      balanceMsg.classList.add("d-none");
      return;
    }

    // Enforce min swap on frontend
    if (minSwap > 0 && amount < minSwap) {
      convertBtn.disabled = true;
      balanceMsg.textContent = `Minimum swap: ${minSwap} ${from}`;
      balanceMsg.classList.remove("d-none");
      document.getElementById("amountTo").value = "";
      return;
    } else {
      balanceMsg.textContent = "Insufficient balance";
    }
    

    if (amount > balance) {
      balanceMsg.classList.remove("d-none");
      convertBtn.disabled = true;
      document.getElementById("amountTo").value = "";
      return;
    } else {
      balanceMsg.classList.add("d-none");
      convertBtn.disabled = false;
    }

    const url = `../crypto/swap.php?ajax=quote&from=${from}&to=${to}&amount=${amount}`;
    fetch(url)
      .then(res => res.json())
      .then(data => {
        document.getElementById("amountTo").value = data.to_amount ?? "0.00";
      })
      .catch(err => {
        console.error("Fetch error:", err);
      });
  }

  document.getElementById("amountFrom").addEventListener("input", getSwapQuote);
  document.getElementById("currencyFrom").addEventListener("change", getSwapQuote);
  document.getElementById("currencyTo").addEventListener("change", getSwapQuote);

  document.addEventListener("DOMContentLoaded", () => {
    setTimeout(updateCurrencyTo, 0);
  });

  document.getElementById("useMaxBtn").addEventListener("click", () => {
    const from = document.getElementById("currencyFrom").value;
    const balance = parseFloat(userBalances[from] || 0);
    document.getElementById("amountFrom").value = balance.toFixed(6);
    getSwapQuote();
  });

  </script>
</div>

Выполнить команду


Для локальной разработки. Не используйте в интернете!