Search in sources :

Example 11 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class IndexerHandle method initOffset.

@PostConstruct
public void initOffset() {
    localBlockOffset = elasticSearchHandler.getRemoteOffset();
    // update current handle header
    try {
        if (localBlockOffset != null) {
            Block block = blockRPCClient.getBlockByHeight(localBlockOffset.getBlockHeight());
            if (block != null) {
                currentHandleHeader = block.getHeader();
            } else {
                logger.error("init offset block not exist on chain: {}", localBlockOffset);
            }
        } else {
            logger.warn("offset is null,init reset to genesis");
            currentHandleHeader = blockRPCClient.getBlockByHeight(0).getHeader();
            localBlockOffset = new BlockOffset(0, currentHandleHeader.getBlockHash());
            elasticSearchHandler.setRemoteOffset(localBlockOffset);
            logger.info("init offset ok: {}", localBlockOffset);
        }
    } catch (JSONRPC2SessionException e) {
        logger.error("set current header error:", e);
    }
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) Block(org.starcoin.bean.Block) BlockOffset(org.starcoin.bean.BlockOffset) PostConstruct(javax.annotation.PostConstruct)

Example 12 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class RepairHandle method check.

public void check(long begin, long end) {
    for (long i = begin; i <= end; i++) {
        try {
            // get block from chain
            Block blockOnChain = blockRPCClient.getBlockByHeight(i);
            if (blockOnChain == null) {
                logger.warn("block not exist on chain: {}", i);
                continue;
            }
            // get block from es
            Block blockOnEs = elasticSearchHandler.getBlockId(i);
            if (blockOnEs != null) {
                if (!blockOnChain.getHeader().getBlockHash().equals(blockOnEs.getHeader().getBlockHash())) {
                    System.out.println("check:" + i);
                }
            } else {
                // logger.warn("es not exist block:{}", i);
                System.out.println("not exist: " + i);
            }
        } catch (JSONRPC2SessionException e) {
            logger.error("repair error:", e);
        }
    }
    logger.info("check ok");
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) Block(org.starcoin.bean.Block)

Example 13 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class SubscribeHandler method run.

@Override
public void run() {
    try {
        WebSocketService service = new WebSocketService("ws://" + seedHost + ":9870", true);
        service.connect();
        StarcoinSubscriber subscriber = new StarcoinSubscriber(service);
        Flowable<PendingTransactionNotification> flowableTxns = subscriber.newPendingTransactionsNotifications();
        TransactionRPCClient rpc = new TransactionRPCClient(new URL("http://" + seedHost + ":9850"));
        for (PendingTransactionNotification notifications : flowableTxns.blockingIterable()) {
            for (String notification : notifications.getParams().getResult()) {
                logger.info("notification: {}", notification);
                PendingTransaction transaction = rpc.getPendingTransaction(notification);
                elasticSearchHandler.savePendingTransaction(transaction);
            }
        }
    } catch (ConnectException | MalformedURLException | JSONRPC2SessionException e) {
        logger.error("handle subscribe exception:", e);
    }
}
Also used : PendingTransactionNotification(org.starcoin.bean.PendingTransactionNotification) TransactionRPCClient(org.starcoin.api.TransactionRPCClient) PendingTransaction(org.starcoin.bean.PendingTransaction) MalformedURLException(java.net.MalformedURLException) JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) StarcoinSubscriber(org.starcoin.api.StarcoinSubscriber) WebSocketService(org.web3j.protocol.websocket.WebSocketService) URL(java.net.URL) ConnectException(java.net.ConnectException)

Example 14 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class TransactionPayloadHandle method executeInternal.

@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) {
    if (client == null) {
        init();
    }
    TransferOffset transactionPayloadRemoteOffset = ServiceUtils.getRemoteOffset(client, index);
    logger.info("handle txn payload: {}", transactionPayloadRemoteOffset);
    if (transactionPayloadRemoteOffset == null) {
        // init offset
        transactionPayloadRemoteOffset = new TransferOffset();
        transactionPayloadRemoteOffset.setTimestamp("0");
        ServiceUtils.setRemoteOffset(client, index, transactionPayloadRemoteOffset);
        logger.info("offset not init, init ok!");
    }
    try {
        List<Transaction> transactionList = elasticSearchHandler.getTransactionByTimestamp(transactionPayloadRemoteOffset.getTimestamp());
        if (!transactionList.isEmpty()) {
            List<SwapTransaction> swapTransactionList = new ArrayList<>();
            elasticSearchHandler.addUserTransactionToList(transactionList);
            elasticSearchHandler.bulkAddPayload(index, transactionList, objectMapper, swapTransactionList);
            // add es success and add swap txn
            if (!swapTransactionList.isEmpty()) {
                Map<String, BigDecimal> tokenPriceMap = new HashMap<>();
                for (SwapTransaction swapTransaction : swapTransactionList) {
                    List<String> tokenList = new ArrayList<>();
                    tokenList.add(swapTransaction.getTokenA());
                    tokenList.add(swapTransaction.getTokenB());
                    swapTransaction.setAmountA(ServiceUtils.divideScalingFactor(stateRPCClient, swapTransaction.getTokenA(), swapTransaction.getAmountA()));
                    swapTransaction.setAmountB(ServiceUtils.divideScalingFactor(stateRPCClient, swapTransaction.getTokenB(), swapTransaction.getAmountB()));
                    boolean isSwap = SwapType.isSwap(swapTransaction.getSwapType());
                    BigDecimal value = getTotalValue(tokenPriceMap, swapTransaction.getTokenA(), swapTransaction.getAmountA(), swapTransaction.getTokenB(), swapTransaction.getAmountB(), isSwap);
                    if (value != null) {
                        swapTransaction.setTotalValue(value);
                    } else {
                        int retry = 3;
                        while (retry > 0) {
                            // get oracle price
                            logger.info("token price not cache, load from oracle: {}, {}", swapTransaction.getTokenA(), swapTransaction.getTokenB());
                            long priceTime = swapTransaction.getTimestamp() - 300000 * (6 - retry);
                            List<org.starcoin.bean.OracleTokenPair> oracleTokenPairs = swapApiClient.getProximatePriceRounds(network, tokenList, String.valueOf(priceTime));
                            if (oracleTokenPairs != null && !oracleTokenPairs.isEmpty()) {
                                BigDecimal priceA = null;
                                OracleTokenPair oracleTokenA = oracleTokenPairs.get(0);
                                if (oracleTokenA != null) {
                                    priceA = new BigDecimal(oracleTokenA.getPrice());
                                    priceA = priceA.movePointLeft(oracleTokenA.getDecimals());
                                    tokenPriceMap.put(swapTransaction.getTokenA(), priceA);
                                    logger.info("get oracle price1 ok: {}", oracleTokenA);
                                }
                                // get tokenB price
                                BigDecimal priceB = null;
                                OracleTokenPair oracleTokenB = oracleTokenPairs.get(1);
                                if (oracleTokenB != null) {
                                    priceB = new BigDecimal(oracleTokenB.getPrice());
                                    priceB = priceB.movePointLeft(oracleTokenB.getDecimals());
                                    tokenPriceMap.put(swapTransaction.getTokenB(), priceB);
                                    logger.info("get oracle price2 ok: {}", oracleTokenB);
                                }
                                BigDecimal zero = new BigDecimal(0);
                                if (isSwap) {
                                    if (priceA != null && priceA.compareTo(zero) == 1) {
                                        swapTransaction.setTotalValue(priceA.multiply(swapTransaction.getAmountA()));
                                        break;
                                    }
                                    if (priceB != null && priceB.compareTo(zero) == 1) {
                                        swapTransaction.setTotalValue(priceB.multiply(swapTransaction.getAmountB()));
                                        break;
                                    }
                                    logger.warn("get oracle price null: {}, {}, {}", swapTransaction.getTokenA(), swapTransaction.getTokenB(), swapTransaction.getTimestamp());
                                    retry--;
                                } else {
                                    // add or remove
                                    boolean isExistB = priceB != null && priceB.compareTo(zero) == 1;
                                    if (priceA != null && priceA.compareTo(zero) == 1) {
                                        BigDecimal valueA = priceA.multiply(swapTransaction.getAmountA());
                                        if (isExistB) {
                                            swapTransaction.setTotalValue(priceB.multiply(swapTransaction.getAmountB()).add(valueA));
                                        } else {
                                            swapTransaction.setTotalValue(valueA.multiply(new BigDecimal(2)));
                                        }
                                        break;
                                    } else {
                                        if (isExistB) {
                                            swapTransaction.setTotalValue(priceB.multiply(swapTransaction.getAmountB()).multiply(new BigDecimal(2)));
                                            break;
                                        } else {
                                            logger.warn("get oracle price null: {}, {}, {}", swapTransaction.getTokenA(), swapTransaction.getTokenB(), swapTransaction.getTimestamp());
                                            retry--;
                                        }
                                    }
                                }
                            } else {
                                logger.warn("getProximatePriceRounds null: {}, {}, {}", swapTransaction.getTokenA(), swapTransaction.getTokenB(), swapTransaction.getTimestamp());
                                retry--;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                swapTxnService.saveList(swapTransactionList);
                logger.info("save swap txn ok: {}", swapTransactionList.size());
            }
            // update offset
            Transaction last = transactionList.get(transactionList.size() - 1);
            TransferOffset currentOffset = new TransferOffset();
            currentOffset.setTimestamp(String.valueOf(last.getTimestamp()));
            ServiceUtils.setRemoteOffset(client, index, currentOffset);
            logger.info("update payload ok: {}", currentOffset);
        } else {
            logger.warn("get txn_info null");
        }
    } catch (IOException | DeserializationError | JSONRPC2SessionException e) {
        logger.warn("handle transaction payload error:", e);
    }
}
Also used : HashMap(java.util.HashMap) DeserializationError(com.novi.serde.DeserializationError) JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal) Transaction(org.starcoin.bean.Transaction)

Example 15 with JSONRPC2SessionException

use of com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException in project starcoin-search by starcoinorg.

the class TvlService method getTokenPairTvl.

public TokenPairTvl getTokenPairTvl(String tokenX, String tokenY) {
    try {
        ContractCall call = new ContractCall();
        call.setFunctionId("0x8c109349c6bd91411d6bc962e080c4a3::TokenSwap::get_reserves");
        List<String> typeTags = new ArrayList<>();
        typeTags.add(tokenX);
        typeTags.add(tokenY);
        call.setTypeArgs(typeTags);
        call.setArgs(new ArrayList<>());
        List result = contractRPCClient.call(call);
        if (result.size() > 1) {
            long x = (Long) result.get(0);
            long y = (Long) result.get(1);
            return new TokenPairTvl(new TokenTvlAmount(tokenX, BigInteger.valueOf(x)), new TokenTvlAmount(tokenY, BigInteger.valueOf(y)));
        }
    } catch (JSONRPC2SessionException e) {
        logger.warn("call contract function failed", e);
    }
    return null;
}
Also used : JSONRPC2SessionException(com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException) TokenTvlAmount(org.starcoin.bean.TokenTvlAmount) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) TokenPairTvl(org.starcoin.bean.TokenPairTvl) ContractCall(org.starcoin.bean.ContractCall)

Aggregations

JSONRPC2SessionException (com.thetransactioncompany.jsonrpc2.client.JSONRPC2SessionException)18 ArrayList (java.util.ArrayList)10 JSONRPC2Request (com.thetransactioncompany.jsonrpc2.JSONRPC2Request)7 Block (org.starcoin.bean.Block)5 ContractCall (org.starcoin.bean.ContractCall)5 JSONObject (com.alibaba.fastjson.JSONObject)4 JSONRPC2Response (com.thetransactioncompany.jsonrpc2.JSONRPC2Response)4 List (java.util.List)4 JSONRPC2Session (com.thetransactioncompany.jsonrpc2.client.JSONRPC2Session)3 IOException (java.io.IOException)2 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 BlockHeader (org.starcoin.bean.BlockHeader)2 BlockOffset (org.starcoin.bean.BlockOffset)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 DeserializationError (com.novi.serde.DeserializationError)1 BigDecimal (java.math.BigDecimal)1 ConnectException (java.net.ConnectException)1