<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
function scanwallet($address,$apiKey,$detailInfo){
$gda = new \GlobalData\Client('127.0.0.1:2207');
$client = new Client([
    'base_uri' => 'https://api.etherscan.io/v2/',
    'timeout'  => 3.0,
]);
// 想要遍历的链ID（参考官方链表）
$chains = [
    1 => 'Ethereum',
    56 => 'BNB Smart Chain',
    137 => 'Polygon',
    42161 => 'Arbitrum One',
    8453 => 'Base',
    43114 => 'Avalanche C-Chain',
    42220 => 'Celo',
    59144 => 'Linea',
    10 => 'OP',
    130 => 'Unichain',
    204 => 'opBNB',
    324 => 'zkSync'
];
$flag=false;
foreach ($chains as $chainId => $chainName) {
    $jump=0;
    if($detailInfo){
    echo "🔍[Wallet Sacnner] 正在{$chainName}({$chainId})查询{$address}...\n";
    }
    $secondToken=$gda->second_token;
    while($secondToken<1){
        if($detailInfo){
        echo "⏳[Wallet Sacnner] 1s QPS triggered, will sleep for one second.";
        }
        usleep(1000);
        $secondToken=$gda->second_token;
    }
    $minuteToken=$gda->minute_token;
    while($minuteToken<1){
        if($detailInfo){
        echo "⏳[Wallet Sacnner] 1min QPS triggered, will sleep for one minute.";
        }
        sleep(60);
        $minuteToken=$gda->minute_token;
    }
    $params = [
        'query' => [
            'module' => 'account',
            'action' => 'tokentx',
            'address' => $address,
            'startblock' => 0,
            'endblock' => 99999999,
            'page' => 1,
            'offset' => 5,
            'sort' => 'desc',
            'chainid' => $chainId,
            'apikey' => $apiKey
        ]
    ];
    // 尝试最多5次以应对429
    for ($attempt = 1; $attempt <= 5; $attempt++) {
        try {
            $response = $client->get('api', $params);
            $statusCode = $response->getStatusCode();

            if ($statusCode == 200) {
                $data = json_decode($response->getBody(), true);
                if ($data['status'] === '1' && count($data['result']) > 0) {
                    if($detailInfo){
                    echo "✅[Wallet Sacnner] 地址{$address}在 {$chainName} 上有交易记录\n";
                    }
                    return true; 
                } else {
                    if($detailInfo){
                    echo "❌[Wallet Sacnner] {$chainName} 无交易。\n";
                    }
                    break;
                }
            } elseif ($statusCode == 429) {
                // 太多请求，退让（指数退避）
                $delay = pow(2, $attempt);
                if($detailInfo){
                echo "⚠️[Wallet Sacnner]EtherScan 429 Too Many Requests，{$delay} 秒后重试...\n";
                }
                sleep($delay);
            } else {
                if($detailInfo){
                echo "❗[Wallet Sacnner]EtherScan HTTP错误 {$statusCode}\n";
                }
                break;
            }

        } catch (RequestException $e) {
            if($detailInfo){
            echo "\033[31m❌[Wallet Sacnner]EtherScan Http Request Failed: " . $e->getMessage() . "\033[0m\n";
            }
            sleep(pow(2, $attempt)); // 退让
        } catch (ConnectException  $e) {
            if($detailInfo){
            echo "\033[31m❌[Wallet Sacnner]EtherScan Http Request Failed: " . $e->getMessage() . "\033[0m\n";
            }
            sleep(pow(2, $attempt)); // 退让
        }
    }
}
#Additional Morph
$baselink='https://explorer-api.morphl2.io/api/v2/addresses/'.$address.'/counters';
if($detailInfo){
echo "🔍[Wallet Sacnner] 正在Morph查询{$address}...\n";
}
try {
    $client = new Client([
    'base_uri' => $baselink,
    'timeout'  => 3.0,
    'http_errors' => false,
]);
    $response = $client->get($baselink);
    $statusCode = $response->getStatusCode();
     if ($statusCode == 200) {
        $data = json_decode($response->getBody(), true);
        if($data['token_transfers_count']!=0){
            if($detailInfo){
            echo "✅[Wallet Sacnner] 地址{$address}在 Morph 上有交易记录\n";
            }
            return true; 
        } else {
            if($detailInfo){
            echo "❌[Wallet Sacnner] Morph 无交易。\n";
            }
        }
     }elseif($statusCode == 404){
        if($detailInfo){
        echo "❌[Wallet Sacnner] Morph 无交易。\n";
        }
     }else{
        if($detailInfo){
        echo "❗[Wallet Sacnner] Morph Explorer HTTP错误 {$statusCode}\n";
        }
     }
 } catch (RequestException $e) {
    if($detailInfo){
    echo "\033[31m❌[Wallet Sacnner] Morph Explorer Http Request Failed: " . $e->getMessage() . "\033[0m\n";
    }
} catch (ConnectException  $e) {
            if($detailInfo){
    echo "\033[31m❌[Wallet Sacnner] Morph Explorer Http Request Failed: " . $e->getMessage() . "\033[0m\n";
    }
        }

return false;
}