Java Code Examples for org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt#isStatusOK()

The following examples show how to use org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt#isStatusOK() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Contract.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Given the duration required to execute a transaction.
 *
 * @param data to send in transaction
 * @param weiValue in Wei to send in transaction
 * @return {@link Optional} containing our transaction receipt
 * @throws IOException if the call to the node fails
 * @throws TransactionException if the transaction was not mined while waiting
 */
protected TransactionReceipt executeTransaction(
        String data, BigInteger weiValue, String funcName)
        throws TransactionException, IOException {

    Callback callback = new Callback();

    asyncExecuteTransaction(data, funcName, callback);
    try {
        callback.semaphore.acquire(1);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }

    TransactionReceipt receipt = callback.receipt;
    if (!receipt.isStatusOK()) {
        String status = receipt.getStatus();
        BigInteger gasUsed = receipt.getGasUsed();

        String message = StatusCode.getStatusMessage(receipt.getStatus(), receipt.getMessage());

        logger.trace(
                " execute transaction not successfully, hash: {}, status: {}, message: {}, gasUsed: {}",
                receipt.getTransactionHash(),
                receipt.getStatus(),
                receipt.getMessage(),
                receipt.getGasUsed());

        throw new TransactionException(message, status, gasUsed, receipt.getTransactionHash());
    }

    return receipt;
}
 
Example 2
Source File: PerformanceDTCallback.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void onResponse(TransactionReceipt receipt) {
    Long cost = System.currentTimeMillis() - startTime;

    try {
        if (receipt.isStatusOK()) {
            String output = receipt.getOutput();
            if (!output.isEmpty()) {
                int code = new BigInteger(output.substring(2, output.length()), 16).intValue();
                logger.debug(" output is {}, code is {} ", output, code);
                if (0 == code) {
                    if (callBackType.compareTo("add") == 0) { // add test
                        dagUserMgr.addUser(user);
                    } else if (callBackType.compareTo("transfer") == 0) { // transfer test
                        fromUser.decrease(amount);
                        toUser.increase(amount);
                    }
                } else {
                    logger.error(" invalid return: code is " + code);
                }
            } else {
                logger.error(" empty return ");
            }
        }
        collector.onMessage(receipt, cost);
    } catch (Exception e) {
        logger.error("onMessage error: ", e);
    }
}
 
Example 3
Source File: PerformanceCollector.java    From WeBASE-Front with Apache License 2.0 4 votes vote down vote up
public void onMessage(TransactionReceipt receipt, Long cost) {
    try {
      if (!receipt.isStatusOK()) {
        System.out.println("receipt error");
        error.addAndGet(1);
//      } else {
//        if (receipt.getLogs().isEmpty()) {
//          System.out.println("receipt log error: "+   receipt.getStatus());
//          error.addAndGet(1);
//        }
      }

      received.incrementAndGet();

      if ((received.get() + 1) % (total / 10) == 0) {
        System.out.println("                                                       |received:"
            + String.valueOf((received.get() + 1) * 100 / total) + "%");
      }

      if (cost < 50) {
        less50.incrementAndGet();
      } else if (cost < 100) {
        less100.incrementAndGet();

      } else if (cost < 200) {
        less200.incrementAndGet();

      } else if (cost < 400) {
        less400.incrementAndGet();
      } else if (cost < 1000) {
        less1000.incrementAndGet();
      } else if (cost < 2000) {
        less2000.incrementAndGet();
      } else {
        timeout2000.incrementAndGet();
      }

      totalCost.addAndGet(cost);

      if (received.intValue() >= total) {
        System.out.println("total");

        // 总耗时
        Long totalTime = System.currentTimeMillis() - startTimestamp;

        System.out.println("===================================================================");

        System.out.println("Total transactions:  " + String.valueOf(total));
        System.out.println("Total time: " + String.valueOf(totalTime) + "ms");
        System.out.println("TPS: " + String.valueOf(total / ((double) totalTime / 1000)));
        System.out.println("Avg time cost: " + String.valueOf(totalCost.get() / total) + "ms");
        System.out.println("Error rate: " + String.valueOf((error.get() / received.get()) * 100) + "%");

        System.out.println("Time area:");
        System.out.println("0    < time <  50ms   : " + String.valueOf(less50) + "  : "
            + String.valueOf((double) less50.get() / total * 100) + "%");
        System.out.println("50   < time <  100ms  : " + String.valueOf(less100) + "  : "
            + String.valueOf((double) less100.get() / total * 100) + "%");
        System.out.println("100  < time <  200ms  : " + String.valueOf(less200) + "  : "
            + String.valueOf((double) less200.get() / total * 100) + "%");
        System.out.println("200  < time <  400ms  : " + String.valueOf(less400) + "  : "
            + String.valueOf((double) less400.get() / total * 100) + "%");
        System.out.println("400  < time <  1000ms : " + String.valueOf(less1000) + "  : "
            + String.valueOf((double) less1000.get() / total * 100) + "%");
        System.out.println("1000 < time <  2000ms : " + String.valueOf(less2000) + "  : "
            + String.valueOf((double) less2000.get() / total * 100) + "%");
        System.out.println("2000 < time           : " + String.valueOf(timeout2000) + "  : "
            + String.valueOf((double) timeout2000.get() / total * 100) + "%");

      //  System.exit(0);
      }
    } catch (Exception e) {
      logger.error("error:", e);
    }
  }
 
Example 4
Source File: TransService.java    From WeBASE-Transaction with Apache License 2.0 4 votes vote down vote up
/**
 * transaction send.
 * 
 * @param transInfoDto transaction info
 */
public void transSend(TransInfoDto transInfoDto) {
    log.debug("transSend transInfoDto:{}", JsonUtils.toJSONString(transInfoDto));
    Long id = transInfoDto.getId();
    log.info("transSend id:{}", id);
    int groupId = transInfoDto.getGroupId();
    int requestCount = transInfoDto.getRequestCount();
    int signType = transInfoDto.getSignType();
    try {
        // check status
        int status = transMapper.selectStatus(id, transInfoDto.getGmtCreate());
        if (status == 1) {
            log.debug("transSend id:{} has successed.", id);
            return;
        }
        // requestCount + 1
        transMapper.updateRequestCount(id, requestCount + 1, transInfoDto.getGmtCreate());
        // check requestCount
        if (requestCount == properties.getRequestCountMax()) {
            log.warn("transSend id:{} has reached limit:{}", id,
                    properties.getRequestCountMax());
            LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0004,
                    ConstantProperties.MSG_ABNORMAL_S0004);
            return;
        }

        String contractAbi = transInfoDto.getContractAbi();
        String contractAddress = transInfoDto.getContractAddress();
        String funcName = transInfoDto.getFuncName();
        List<Object> params = JsonUtils.toJavaObjectList(transInfoDto.getFuncParam(), Object.class);

        // get function abi
        AbiDefinition abiDefinition = ContractAbiUtil.getAbiDefinition(funcName, contractAbi);
        // input format
        List<String> funcInputTypes = ContractAbiUtil.getFuncInputType(abiDefinition);
        List<Type> finalInputs = ContractAbiUtil.inputFormat(funcInputTypes, params);
        // output format
        List<String> funOutputTypes = ContractAbiUtil.getFuncOutputType(abiDefinition);
        List<TypeReference<?>> finalOutputs = ContractAbiUtil.outputFormat(funOutputTypes);
        // encode function
        Function function = new Function(funcName, finalInputs, finalOutputs);
        String encodedFunction = FunctionEncoder.encode(function);
        // data sign
        String signMsg = signMessage(groupId, signType, transInfoDto.getSignUserId(),
                contractAddress, encodedFunction);
        if (StringUtils.isBlank(signMsg)) {
            return;
        }
        // send transaction
        final CompletableFuture<TransactionReceipt> transFuture = new CompletableFuture<>();
        sendMessage(groupId, signMsg, transFuture);
        TransactionReceipt receipt =
                transFuture.get(properties.getTransMaxWait(), TimeUnit.SECONDS);
        transInfoDto.setTransHash(receipt.getTransactionHash());
        transInfoDto.setTransOutput(receipt.getOutput());
        transInfoDto.setReceiptStatus(receipt.isStatusOK());
        if (receipt.isStatusOK()) {
            transInfoDto.setHandleStatus(1);
        }
        transMapper.updateHandleStatus(transInfoDto);
    } catch (Exception e) {
        log.error("fail transSend id:{}", id, e);
        LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0002,
                ConstantProperties.MSG_ABNORMAL_S0002);
    }
}
 
Example 5
Source File: ContractService.java    From WeBASE-Transaction with Apache License 2.0 4 votes vote down vote up
/**
 * deploySend.
 * 
 * @param deployInfoDto deployInfoDto
 */
public void deploySend(DeployInfoDto deployInfoDto) {
    log.debug("deploySend deployInfoDto:{}", JsonUtils.toJSONString(deployInfoDto));
    Long id = deployInfoDto.getId();
    log.info("deploySend id:{}", id);
    int groupId = deployInfoDto.getGroupId();
    int requestCount = deployInfoDto.getRequestCount();
    int signType = deployInfoDto.getSignType();
    try {
        // check status
        int status = contractMapper.selectStatus(id, deployInfoDto.getGmtCreate());
        if (status == 1) {
            log.info("deploySend id:{} has successed.", id);
            return;
        }
        // requestCount + 1
        contractMapper.updateRequestCount(id, requestCount + 1, deployInfoDto.getGmtCreate());
        // check requestCount
        if (requestCount == properties.getRequestCountMax()) {
            log.warn("deploySend id:{} has reached limit:{}", id,
                    properties.getRequestCountMax());
            LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0003,
                    ConstantProperties.MSG_ABNORMAL_S0003);
            return;
        }

        String contractAbi = deployInfoDto.getContractAbi();
        String contractBin = deployInfoDto.getContractBin();
        List<Object> params = JsonUtils.toJavaObjectList(deployInfoDto.getFuncParam(), Object.class);

        // get function abi
        AbiDefinition abiDefinition = ContractAbiUtil.getAbiDefinition(contractAbi);
        List<String> funcInputTypes = ContractAbiUtil.getFuncInputType(abiDefinition);
        // Constructor encode
        String encodedConstructor = "";
        if (funcInputTypes.size() > 0) {
            List<Type> finalInputs = ContractAbiUtil.inputFormat(funcInputTypes, params);
            encodedConstructor = FunctionEncoder.encodeConstructor(finalInputs);
        }
        // data sign
        String data = contractBin + encodedConstructor;
        String signMsg = transService.signMessage(groupId, signType,
                deployInfoDto.getSignUserId(), "", data);
        if (StringUtils.isBlank(signMsg)) {
            return;
        }
        // send transaction
        final CompletableFuture<TransactionReceipt> transFuture = new CompletableFuture<>();
        transService.sendMessage(groupId, signMsg, transFuture);
        TransactionReceipt receipt =
                transFuture.get(properties.getTransMaxWait(), TimeUnit.SECONDS);
        deployInfoDto.setContractAddress(receipt.getContractAddress());
        deployInfoDto.setTransHash(receipt.getTransactionHash());
        deployInfoDto.setReceiptStatus(receipt.isStatusOK());
        if (receipt.isStatusOK()) {
            deployInfoDto.setHandleStatus(1);
        }
        contractMapper.updateHandleStatus(deployInfoDto);
    } catch (Exception e) {
        log.error("fail deploySend id:{}", id, e);
        LogUtils.monitorAbnormalLogger().error(ConstantProperties.CODE_ABNORMAL_S0001,
                ConstantProperties.MSG_ABNORMAL_S0001);
    }
}
 
Example 6
Source File: PerformanceDTCallback.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
@Override
public void onResponse(TransactionReceipt receipt) {
    Long cost = System.currentTimeMillis() - startTime;

    try {
        if (receipt.isStatusOK()) {

            if (callBackType.compareTo("set") == 0) { // add test
                dagUserMgr.addUser(user);
            } else if (callBackType.compareTo("transfer") == 0) { // transfer test
                fromUser.decrease(amount);
                toUser.increase(amount);
            } else if (callBackType.compareTo("transferRevert") == 0) { // tranfer revert test
                fromUser.decrease(amount);
                toUser.increase(amount);
            }
        }

        if (callBackType.compareTo("transferRevert") == 0) {
            String info =
                    "[RevertTest-TxSent]"
                            + "\t[TxHash]="
                            + receipt.getTransactionHash()
                            + "\t[From]="
                            + fromUser.getUser()
                            + "\t[FromBalance]="
                            + fromUser.getAmount()
                            + "\t[To]="
                            + toUser.getUser()
                            + "\t[ToBalance]="
                            + toUser.getAmount()
                            + "\t[Status]="
                            + receipt.getStatus();
            System.out.println(info);
        }

        collector.onMessage(receipt, cost);
    } catch (Exception e) {
        logger.error("onMessage error: ", e);
    }
}