PHP WebShell

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

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

<?php
// models/crypto/wallets.php

/* =========================================================
   CREATE WALLET HANDLERS (unchanged)
   ========================================================= */

// Handle Create TRX & USDT wallet request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_trx_address'])) {
    try {
        $creator = new \Models\Crypto\CreateTronWallet($conn);
        $result  = $creator->create((int)$user_id);

        if (!empty($result['success'])) {
            $_SESSION['flash_success'] = ($result['message'] ?? 'Wallet created.') . ' Address: ' . ($result['address'] ?? '');
        } else {
            $_SESSION['flash_error'] = $result['message'] ?? 'Unable to create TRX wallet.';
        }
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = 'Error creating TRX wallet: ' . $e->getMessage();
    }

    header('Location: index.php');
    exit;
}

// Handle Create SOL wallet request (assign from reserved_wallet)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_sol_address'])) {
    try {
        $creator = new \Models\Crypto\CreateSolUserAddress($conn);
        $result  = $creator->create((int)$user_id);

        if (!empty($result['success'])) {
            $_SESSION['flash_success'] = ($result['message'] ?? 'Wallet created.') . ' Address: ' . ($result['address'] ?? '');
        } else {
            $_SESSION['flash_error'] = $result['message'] ?? 'Unable to create SOL wallet.';
        }
    } catch (\Throwable $e) {
        $_SESSION['flash_error'] = 'Error creating SOL wallet: ' . $e->getMessage();
    }

    header('Location: index.php');
    exit;
}


/* =========================================================
   UI HELPERS
   ========================================================= */

function coin_decimals_ui(string $coin): int {
    $coin = strtoupper($coin);
    return match ($coin) {
        'BTC' => 8,
        'ETH' => 10,
        'SOL' => 9,
        'TRX' => 6,
        'USDT', 'USDC' => 6,
        'NGN', 'USD' => 2,
        default => 8,
    };
}

function fmt_coin_amount($amount, string $coin): string {
    $scale = coin_decimals_ui($coin);
    return number_format((float)$amount, $scale, '.', '');
}

/**
 * Normalize symbol to match online_coin_rates.coin (your original behavior),
 * BUT we still allow TRX to also check TRX row if it exists.
 */
function balance_norm_coin(string $coin): string {
    $coin = strtoupper(trim($coin));
    $map = [
        'USDT-TRC20' => 'USDT',
        'TRX'        => 'TRON', // primary mapping
    ];
    return $map[$coin] ?? $coin;
}

/**
 * For a given wallet coin, return possible rate keys to try in online_coin_rates.
 * This fixes TRX conversion showing $15 for 15 TRX (wrong rate lookup / wrong key).
 */
function rate_keys(string $coin): array {
    $coin = strtoupper(trim($coin));

    if ($coin === 'USDT-TRC20') return ['USDT'];

    // TRX: try both TRON and TRX (whichever exists and is valid)
    if ($coin === 'TRX') return ['TRON', 'TRX'];
    if ($coin === 'TRON') return ['TRON', 'TRX'];

    // default: try normalized then raw
    $norm = balance_norm_coin($coin);
    return ($norm !== $coin) ? [$norm, $coin] : [$coin];
}

function get_usd_rate(array $usdPrice, string $coin): float {
    foreach (rate_keys($coin) as $k) {
        $k = strtoupper($k);
        $r = (float)($usdPrice[$k] ?? 0.0);
        if ($r > 0) return $r;
    }
    return 0.0;
}


/* =========================================================
   BALANCES + EQUIVALENTS
   - Defines: $wallets, $totalNgn, $totalUsd
   - Adds per wallet:
       usd_equiv  (float|null)  => USD equivalent for crypto
       equiv_text (string)      => what to show under raw balance
         • NGN: ₦ balance again (naira twice)
         • Crypto: $ USD equivalent
   ========================================================= */

$totalNgn = 0.0;
$totalUsd = 0.0;
$wallets  = [];

/* 1) Load user wallets */
$stmt = $conn->prepare("
    SELECT wallet_id, coin, label, wallet_add, balance, type, icon
    FROM user_wallets
    WHERE user_id=?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

$need = [];

while ($w = $res->fetch_assoc()) {
    $w['coin'] = strtoupper($w['coin']);
    $coin = $w['coin'];
    $bal  = (float)($w['balance'] ?? 0);

    $wallets[$coin] = $w;

    if ($coin === 'NGN') {
        $totalNgn += $bal;
        continue;
    }

    // Collect ALL possible rate keys we might need for this coin
    foreach (rate_keys($coin) as $k) {
        $need[strtoupper($k)] = true;
    }
}
$stmt->close();

/* 2) Fetch USD prices from online_coin_rates.rate */
$usdPrice = [];
$coins = array_keys($need);

if (!empty($coins)) {
    $placeholders = implode(',', array_fill(0, count($coins), '?'));
    $types = str_repeat('s', count($coins));

    $sql = "SELECT UPPER(coin) AS coin, rate FROM online_coin_rates WHERE UPPER(coin) IN ($placeholders)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$coins);
    $stmt->execute();
    $r2 = $stmt->get_result();

    while ($row = $r2->fetch_assoc()) {
        $usdPrice[strtoupper($row['coin'])] = (float)($row['rate'] ?? 0);
    }
    $stmt->close();
}

/* 3) Compute totalUsd (NON-NGN only) */
foreach ($wallets as $coin => $w) {
    $coin = strtoupper($coin);
    if ($coin === 'NGN') continue;

    $bal = (float)($w['balance'] ?? 0);

    $p = get_usd_rate($usdPrice, $coin);

    // ONLY stablecoin fallback. Never apply fallback to TRX/TRON.
    if ($p <= 0 && in_array($coin, ['USDT', 'USDT-TRC20'], true)) {
        $p = 1.0;
    }

    $totalUsd += ($p > 0) ? ($bal * $p) : 0.0;
}

/* 4) Per-wallet equivalent fields for UI */
foreach ($wallets as $coin => &$w) {
    $coin = strtoupper($coin);
    $bal  = (float)($w['balance'] ?? 0);

    $w['usd_equiv']  = null;
    $w['equiv_text'] = '';

    if ($coin === 'NGN') {
        // You want NGN to show NGN twice (raw + under it)
        $w['equiv_text'] = '₦' . number_format($bal, 2, '.', ',');
        continue;
    }

    $p = get_usd_rate($usdPrice, $coin);

    if ($p <= 0 && in_array($coin, ['USDT', 'USDT-TRC20'], true)) {
        $p = 1.0;
    }

    if ($p > 0) {
        $usd = $bal * $p;
        $w['usd_equiv']  = $usd;
        $w['equiv_text'] = '$' . number_format($usd, 2, '.', ',');
    }
}
unset($w);

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


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