KKSU
2024-06-06 424ad35dcd1fafb51a0ba77523b11e6871f2858c
src/main/java/cc/mrbird/febs/dapp/chain/ChainService.java
@@ -1,71 +1,189 @@
package cc.mrbird.febs.dapp.chain;
import cc.mrbird.febs.common.exception.FebsException;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.data.repository.query.ParameterOutOfBoundsException;
import org.springframework.util.Base64Utils;
import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.websocket.WebSocketClient;
import org.web3j.protocol.websocket.WebSocketService;
import org.web3j.tx.gas.StaticGasProvider;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.rmi.activation.UnknownObjectException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @author wzy
 * @author
 * @date 2022-03-23
 **/
@Slf4j
public class ChainService {
    private final static Map<String, ContractChainService> contractMap = new HashMap<>();
    private final String ETH_PREFIX = "0x";
    private final EthService ETH = new EthService();
    private final TrxService TRX = TrxService.INSTANCE;
    static {
        for (ChainEnum chain : ChainEnum.values()) {
            if ("TRX".equals(chain.getChain())) {
                contractMap.put(chain.name(), new TrxService(chain.getAddress(), chain.getPrivateKey(), chain.getContractAddress(), chain.getApiKey()));
            } else {
                contractMap.put(chain.name(), new EthService(chain.getUrl(), chain.getAddress(), chain.getPrivateKey(), chain.getContractAddress()));
            }
        }
    }
    private ChainService() {}
    private ChainService() {
    }
    public final static ChainService INSTANCE = new ChainService();
    /**
     * 获取制定账号的USDT余额
     *
     * @param address
     * @return
     */
    public BigDecimal balanceOf(String address) {
        BigDecimal balance = BigDecimal.ZERO;
        if (address.contains(ETH_PREFIX)) {
            balance = ETH.tokenGetBalance(address);
        } else {
            balance = TRX.balanceOfDecimal(address);
    public static ContractChainService getInstance(String chainType) {
        ContractChainService contract = contractMap.get(chainType);
        if (contract == null) {
            throw new FebsException("参数错误");
        }
        return balance;
        return contract;
    }
    /**
     * 判断地址是否授权给制定账户
     * 监听合约事件
     *
     * @param address
     * @return
     * @param startBlock 开始区块
     */
    public boolean isAllowance(String address) {
        BigInteger result;
        if (address.indexOf(ETH_PREFIX) > 0) {
            result = ETH.ethAllowance(address);
        } else {
            result = TRX.allowance(address);
        }
        return result.intValue() != 0;
    public static void contractEventListener(BigInteger startBlock, ContractEventService event, String type) {
        contractEventListener(startBlock, null, event, type);
    }
    /**
     * 获取地址授权数量
     *
     * @param address
     * @return
     */
    public int allowanceCnt(String address) {
        String response = HttpUtil.get("https://apiasia.tronscan.io:5566/api/account/approve/list?address=" + address);
        String total = JSONObject.parseObject(response).getString("total");
        return Integer.parseInt(total);
    public static void contractEventListener(BigInteger startBlock, BigInteger endBlock, ContractEventService event, String type) {
        ChainEnum chain = ChainEnum.getValueByName(type);
        assert chain != null;
        EthUsdtContract contract = contract(chain.getPrivateKey(), chain.getContractAddress(), chain.getUrl());
        EthFilter filter = getFilter(startBlock, endBlock, chain.getContractAddress());
        Flowable<EthUsdtContract.TransferEventResponse> eventFlowable = contract.transferEventFlowable(filter);
        eventFlowable.subscribe(e -> {
            event.compile(e);
        }, error -> {
            log.error("合约监听启动报错", error);
        });
    }
    public static void wssContractEventListener(BigInteger startBlock, ContractEventService event, String type) {
        WebSocketService ws = null;
        WebSocketClient webSocketClient = null;
        Web3j web3j = null;
        try {
            webSocketClient = new WebSocketClient(new URI("wss://bsc-mainnet.nodereal.io/ws/v1/78074065950e4915aef4f12b6f357d16"));
            ws = new WebSocketService(webSocketClient, true);
            ws.connect();
            web3j = Web3j.build(ws);
            ChainEnum chain = ChainEnum.getValueByName(type);
            assert chain != null;
            EthUsdtContract ethUsdtContract = wssContract(chain.getPrivateKey(), chain.getContractAddress(), web3j);
            EthFilter filter = getFilter(startBlock, null, chain.getContractAddress());
            Flowable<EthUsdtContract.TransferEventResponse> eventFlowable = ethUsdtContract.transferEventFlowable(filter);
            Disposable subscribe = eventFlowable.subscribe(event::compile, error -> {
                log.error("币安监听异常", error);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static EthUsdtContract contract(String privateKey, String contractAddress, String url) {
        Credentials credentials = Credentials.create(privateKey);
        HttpService httpService = new HttpService(url);
//        httpService.addHeader("Authorization", "Bearer " + Base64.encode("tfc:tfc123".getBytes()));
//        httpService.addHeader("Authorization", "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJwdWJsaWMiLCJleHAiOjE2NTk5MzcxOTAsImp0aSI6IjRiMjNkYTVjLWRlZWEtNDYzNi04YjMwLWNmMmZmMjVkM2NlYyIsImlhdCI6MTY1OTkzMzU5MCwiaXNzIjoiQW5rciIsIm5iZiI6MTY1OTkzMzU5MCwic3ViIjoiZmNiNjY0YjItOGEwNC00N2E5LTg3ZjMtNTJhMjE2ODVlMzEzIn0.YfEwvDByU2MGHywsblZpEmKMIbjv4cWYkn5CaFglXY0TSANzd2pCSbIe40yU_R9_nV6xZeE8Uk74jJOdd_QvMpFyUgo-MMNWZP6uiEaYvK_K3tlpk5yzeZq9D4ruWaq8rFKggr-iaRGzu6coRSAOFv2prWll3a7NdEbmkM-y5Y85xYD6g1N-TPIpE_Y-_-WPf3JUavk744kG8YyHhGvAmk2IL0N2xePfC6CHesdJhwvmJJXzr_53dbPwit1y5KljS0iTZz3mGTML2bq4hGaEHbQxeY2fBpZOSm8sPMz-zB9IVJQKzH5-DXlPKz01mJ9XiBJlubfHsN72RdqFD-O2Tw");
        return EthUsdtContract.load(contractAddress,
                Web3j.build(httpService),
                credentials,
                new StaticGasProvider(BigInteger.valueOf(4500000L), BigInteger.valueOf(200000L)));
    }
    private static EthUsdtContract wssContract(String privateKey, String contractAddress, Web3j web3j) {
        Credentials credentials = Credentials.create(privateKey);
//        httpService.addHeader("Authorization", "Bearer " + Base64.encode("tfc:tfc123".getBytes()));
//        httpService.addHeader("Authorization", "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJwdWJsaWMiLCJleHAiOjE2NTk5MzcxOTAsImp0aSI6IjRiMjNkYTVjLWRlZWEtNDYzNi04YjMwLWNmMmZmMjVkM2NlYyIsImlhdCI6MTY1OTkzMzU5MCwiaXNzIjoiQW5rciIsIm5iZiI6MTY1OTkzMzU5MCwic3ViIjoiZmNiNjY0YjItOGEwNC00N2E5LTg3ZjMtNTJhMjE2ODVlMzEzIn0.YfEwvDByU2MGHywsblZpEmKMIbjv4cWYkn5CaFglXY0TSANzd2pCSbIe40yU_R9_nV6xZeE8Uk74jJOdd_QvMpFyUgo-MMNWZP6uiEaYvK_K3tlpk5yzeZq9D4ruWaq8rFKggr-iaRGzu6coRSAOFv2prWll3a7NdEbmkM-y5Y85xYD6g1N-TPIpE_Y-_-WPf3JUavk744kG8YyHhGvAmk2IL0N2xePfC6CHesdJhwvmJJXzr_53dbPwit1y5KljS0iTZz3mGTML2bq4hGaEHbQxeY2fBpZOSm8sPMz-zB9IVJQKzH5-DXlPKz01mJ9XiBJlubfHsN72RdqFD-O2Tw");
        return EthUsdtContract.load(contractAddress,
                web3j,
                credentials,
                new StaticGasProvider(BigInteger.valueOf(4500000L), BigInteger.valueOf(200000L)));
    }
    private static EthFilter getFilter(BigInteger startBlock, String contractAddress) {
        return getFilter(startBlock, null, contractAddress);
    }
    private static EthFilter getFilter(BigInteger startBlock, BigInteger endBlock, String contractAddress) {
        DefaultBlockParameter startParameterName = null;
        DefaultBlockParameter endParameterName = null;
        if (startBlock != null) {
            startParameterName = new DefaultBlockParameterNumber(startBlock);
        } else {
            startParameterName = DefaultBlockParameterName.EARLIEST;
        }
        if (endBlock != null) {
            endParameterName = new DefaultBlockParameterNumber(endBlock);
        } else {
            endParameterName = DefaultBlockParameterName.LATEST;
        }
        return new EthFilter(startParameterName, endParameterName, contractAddress);
    }
    public static void main(String[] args) {
//        System.out.println(new ChainService().isAllowance("TUy8XwDmdsDKPLDGUrGuNRVMhwSEKtkDcD"));
//        ChainEnum chain = ChainEnum.getValueByName(ChainEnum.BSC_TFC.name());
//        assert chain != null;
//
//        EthUsdtContract contract = contract(chain.getPrivateKey(), chain.getContractAddress(), chain.getUrl());
//        EthFilter filter = getFilter(new BigInteger("18097238"), chain.getContractAddress());
//
//        contract.transferEventFlowable(filter).subscribe(e -> {
//            System.out.println(1);
//        }, error -> {
//            log.error("--->", error);
//        });
        System.out.println(ChainService.getInstance(ChainEnum.BSC_TFC.name()).totalSupply());
    }
}