package com.table.transfer.util.ether;

import jakarta.annotation.PostConstruct;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class Web3jManager {
    private static final String ethNode = "https://billowing-greatest-feather.quiknode.pro/591e36c78f14e843e629d72c07a3fb39c5955541";
    private static final String bscNode = "https://empty-quiet-sunset.bsc.quiknode.pro/69b72a1ee6e3efe4ad03d31b04a9a1b0c8a6e6d3";

    public static final Map<String, Web3j> web3jClients = new ConcurrentHashMap<>();

     static {
        // 假设你有多个链的节点配置
        registerWeb3j("ETH", ethNode);
        registerWeb3j("BSC", bscNode);
    }
    public static void registerWeb3j(String chain, String nodeUrl) {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(10, 60, TimeUnit.SECONDS))
                .retryOnConnectionFailure(true) // 对 GET 请求自动重试
                .build();

        HttpService httpService = new HttpService(nodeUrl, httpClient, false);
        Web3j web3j = Web3j.build(httpService);
        web3jClients.put(chain, web3j);
    }

    public static Web3j getWeb3j(String chain) {
        Web3j web3j = web3jClients.get(chain);
        if (web3j == null) {
            throw new IllegalArgumentException("不支持的链: " + chain);
        }
        return web3j;
    }

}
