Search in sources :

Example 26 with TransactionReceipt

use of org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt in project web3sdk by FISCO-BCOS.

the class TestTxDecode method main.

public static void main(String[] args) throws Exception {
    TransactionDecoder transactionDecoder = TransactionDecoderFactory.buildTransactionDecoder("TableTest");
    TransactionReceipt txReceipt = sentTx();
    // decode input
    System.out.println("===================decode input===================");
    String input = txReceipt.getInput();
    String inputResult1 = transactionDecoder.decodeInputReturnJson(input);
    InputAndOutputResult inputResult2 = transactionDecoder.decodeInputReturnObject(input);
    System.out.println(inputResult1);
    System.out.println(inputResult2);
    System.out.println();
    // decode output
    System.out.println("===================decode output===================");
    String output = txReceipt.getOutput();
    String outputResult1 = transactionDecoder.decodeOutputReturnJson(input, output);
    InputAndOutputResult outputResult2 = transactionDecoder.decodeOutputReturnObject(input, output);
    System.out.println(outputResult1);
    System.out.println(outputResult2);
    System.out.println();
    // decode event
    System.out.println("===================decode event===================");
    List<Log> logList = txReceipt.getLogs();
    String logJson = ObjectMapperFactory.getObjectMapper().writeValueAsString(logList);
    String eventResult1 = transactionDecoder.decodeEventReturnJson(logJson);
    Map<String, List<List<EventResultEntity>>> eventResult2 = transactionDecoder.decodeEventReturnObject(logList);
    System.out.println(eventResult1);
    System.out.println(eventResult2);
    System.exit(0);
}
Also used : Log(org.fisco.bcos.web3j.protocol.core.methods.response.Log) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) List(java.util.List)

Example 27 with TransactionReceipt

use of org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt in project web3sdk by FISCO-BCOS.

the class Contract method executeTransaction.

/**
 * 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());
        TransactionException transactionException = new TransactionException(message, status, gasUsed, receipt.getTransactionHash());
        transactionException.setReceipt(receipt);
        throw transactionException;
    }
    return receipt;
}
Also used : EventLogPushWithDecodeCallback(org.fisco.bcos.channel.event.filter.EventLogPushWithDecodeCallback) TransactionSucCallback(org.fisco.bcos.channel.client.TransactionSucCallback) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) BigInteger(java.math.BigInteger)

Example 28 with TransactionReceipt

use of org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt in project web3sdk by FISCO-BCOS.

the class CallContractTest method testAsyncCallContract.

private static void testAsyncCallContract(CallContract callContract, String address) {
    TransactionCallback callback = new TransactionCallback();
    TransactionReceipt receipt;
    callContract.asyncSendTransaction(callback, gasPrice, gasLimit, address, "setAndget", new Utf8String("hello world"), new Int256(10086));
    try {
        callback.semaphore.acquire(1);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        System.out.println(e.getLocalizedMessage());
    }
    receipt = callback.receipt;
    List<TypeReference<?>> referencesList = Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
    }, new TypeReference<Int256>() {
    });
    List<Type> returnList1 = FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
    System.out.println("async call setAndget: " + (String) returnList1.get(0).getValue() + ", " + (BigInteger) returnList1.get(1).getValue());
    callContract.asyncSendTransaction(callback, address, "setAndget", new Utf8String("hello world"), new Int256(10086));
    try {
        callback.semaphore.acquire(1);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        System.out.println(e.getLocalizedMessage());
    }
    receipt = callback.receipt;
    referencesList = Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
    }, new TypeReference<Int256>() {
    });
    List<Type> returnList2 = FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
    System.out.println("default async call setAndget: " + (String) returnList2.get(0).getValue() + ", " + (BigInteger) returnList2.get(1).getValue());
}
Also used : TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) Utf8String(org.fisco.bcos.web3j.abi.datatypes.Utf8String) Utf8String(org.fisco.bcos.web3j.abi.datatypes.Utf8String) Int256(org.fisco.bcos.web3j.abi.datatypes.generated.Int256) Type(org.fisco.bcos.web3j.abi.datatypes.Type) BigInteger(java.math.BigInteger) TypeReference(org.fisco.bcos.web3j.abi.TypeReference)

Example 29 with TransactionReceipt

use of org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt in project web3sdk by FISCO-BCOS.

the class PerformanceDTTest method userAddTest.

public void userAddTest(BigInteger count, BigInteger qps) {
    try {
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(count.intValue());
        threadPool.initialize();
        System.out.println("Start UserAdd test, count " + count);
        System.out.println("===================================================================");
        RateLimiter limiter = RateLimiter.create(qps.intValue());
        Integer area = count.intValue() / 10;
        long seconds = System.currentTimeMillis() / 1000l;
        this.collector.setStartTimestamp(System.currentTimeMillis());
        for (Integer i = 0; i < count.intValue(); ++i) {
            final int index = i;
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    limiter.acquire();
                    String user = Long.toHexString(seconds) + Integer.toHexString(index);
                    BigInteger amount = new BigInteger("1000000000");
                    DagTransferUser dtu = new DagTransferUser();
                    dtu.setUser(user);
                    dtu.setAmount(amount);
                    PerformanceDTCallback callback = new PerformanceDTCallback();
                    callback.setCollector(collector);
                    callback.setDagTransferUser(dtu);
                    callback.setDagUserMgr(getDagUserMgr());
                    callback.setCallBackType("add");
                    try {
                        callback.recordStartTime();
                        dagTransfer.userAdd(user, amount, callback);
                    } catch (Exception e) {
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("-1");
                        callback.onResponse(receipt);
                        logger.info(e.getMessage());
                    }
                    int current = sended.incrementAndGet();
                    if (current >= area && ((current % area) == 0)) {
                        System.out.println("Already sended: " + current + "/" + count + " transactions");
                    }
                }
            });
        }
        // end or not
        while (!collector.isEnd()) {
            Thread.sleep(2000);
            logger.info(" received: {}, total: {}", collector.getReceived().intValue(), collector.getTotal());
        }
        dagUserMgr.writeDagTransferUser();
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}
Also used : TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)

Example 30 with TransactionReceipt

use of org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt in project web3sdk by FISCO-BCOS.

the class MixContractClient method testMixContract.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void testMixContract(String[] args) throws Exception {
    final Resource contractResource = new ClassPathResource("contract.properties");
    PropertiesConfiguration prop = new PropertiesConfiguration(contractResource.getFile());
    Object addressObj = prop.getProperty("mix_address");
    if (addressObj != null) {
        contractAddress = (String) addressObj;
    } else {
        deploymixContract();
    }
    ContractGasProvider contractGasProvider = new StaticGasProvider(gasPrice, gasLimit);
    MixContract mixContract = MixContract.load(contractAddress, web3j, credentials, contractGasProvider);
    // create table
    if ("create".equals(args[0])) {
        TransactionReceipt receipt = mixContract.create().send();
        List<CreateResultEventResponse> createResultEvents = mixContract.getCreateResultEvents(receipt);
        if (createResultEvents.size() == 0) {
            System.out.println("create t_demo table failed.");
            return;
        }
        CreateResultEventResponse createResultEventResponse = createResultEvents.get(0);
        int createCount = createResultEventResponse.count.intValue();
        switch(createCount) {
            case 255:
                System.out.println("non-authorized to create t_demo table.");
                break;
            case 0:
                System.out.println("t_demo table already exist.");
                break;
            case 1:
                System.out.println("create t_demo table completed.");
                break;
        }
    } else // insert
    if ("insert".equals(args[0])) {
        if (args.length == 4) {
            String name = args[1];
            int item_id = Integer.parseInt(args[2]);
            String item_name = args[3];
            RemoteCall<TransactionReceipt> insert = mixContract.insert(name, BigInteger.valueOf(item_id), item_name);
            TransactionReceipt txReceipt = insert.send();
            List<InsertResultEventResponse> insertResultEvents = mixContract.getInsertResultEvents(txReceipt);
            if (insertResultEvents.size() > 0) {
                for (int i = 0; i < insertResultEvents.size(); i++) {
                    InsertResultEventResponse insertResultEventResponse = insertResultEvents.get(i);
                    logger.info("insertCount = " + insertResultEventResponse.count.intValue());
                    System.out.println("insertCount = " + insertResultEventResponse.count.intValue());
                }
            } else {
                System.out.println("t_demo table does not exist.");
            }
        } else {
            System.out.println("\nPlease enter as follow example:\n 1 insert fruit 1 apple");
        }
    } else // select
    if ("select".equals(args[0])) {
        if (args.length == 2) {
            try {
                String keyName = args[1];
                Tuple3<List<byte[]>, List<BigInteger>, List<byte[]>> lists = mixContract.read(keyName).send();
                List<byte[]> value1 = lists.getValue1();
                List<BigInteger> value2 = lists.getValue2();
                List<byte[]> value3 = lists.getValue3();
                logger.info("record numbers = " + value1.size());
                System.out.println("record numbers = " + value1.size());
                for (int i = 0; i < value1.size(); i++) {
                    String name = new String(value1.get(i));
                    logger.info("name = " + name);
                    System.out.println("name = " + name);
                    int item_id = value2.get(i).intValue();
                    logger.info("item_id = " + item_id);
                    System.out.println("item_id = " + item_id);
                    String item_name = new String(value3.get(i));
                    logger.info("item_name = " + item_name);
                    System.out.println("item_name = " + item_name);
                }
                System.out.println();
                System.out.println("totalKeys = " + mixContract.totalKeys().send());
            } catch (Exception e) {
                logger.info("record numbers = 0");
                System.out.println("record numbers = 0");
            }
        } else {
            System.out.println("\nPlease enter as follow example:\n 1 select fruit");
        }
    } else // update
    if ("update".equals(args[0])) {
        if (args.length == 4) {
            String name = args[1];
            int item_id = Integer.parseInt(args[2]);
            String item_name = args[3];
            RemoteCall<TransactionReceipt> update = mixContract.update(name, BigInteger.valueOf(item_id), item_name);
            TransactionReceipt transactionReceipt = update.send();
            List<UpdateResultEventResponse> updateResultEvents = mixContract.getUpdateResultEvents(transactionReceipt);
            if (updateResultEvents.size() > 0) {
                for (int i = 0; i < updateResultEvents.size(); i++) {
                    UpdateResultEventResponse updateResultEventResponse = updateResultEvents.get(i);
                    System.out.println("updateCount = " + updateResultEventResponse.count.intValue());
                    logger.info("updateCount = " + updateResultEventResponse.count.intValue());
                }
            } else {
                System.out.println("t_demo table does not exist.");
            }
        } else {
            System.out.println("\nPlease enter as follow example:\n 1 update fruit 1 orange");
        }
    } else // remove
    if ("remove".equals(args[0])) {
        if (args.length == 3) {
            String name = args[1];
            int item_id = Integer.parseInt(args[2]);
            RemoteCall<TransactionReceipt> remove = mixContract.remove(name, BigInteger.valueOf(item_id));
            TransactionReceipt transactionReceipt = remove.send();
            List<RemoveResultEventResponse> removeResultEvents = mixContract.getRemoveResultEvents(transactionReceipt);
            if (removeResultEvents.size() > 0) {
                RemoveResultEventResponse reomveResultEventResponse = removeResultEvents.get(0);
                logger.info("removeCount = " + reomveResultEventResponse.count.intValue());
                System.out.println("removeCount = " + reomveResultEventResponse.count.intValue());
            } else {
                System.out.println("t_demo table does not exist.");
            }
        } else {
            System.out.println("\nPlease enter as follow example:\n 1 remove fruit 1");
        }
    } else {
        System.out.println("\nPlease choose follow commands:\n deploy, create, insert, select, update or remove");
    }
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(org.springframework.core.io.Resource) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) InsertResultEventResponse(org.fisco.bcos.channel.test.contract.MixContract.InsertResultEventResponse) PropertiesConfiguration(org.apache.commons.configuration.PropertiesConfiguration) ContractGasProvider(org.fisco.bcos.web3j.tx.gas.ContractGasProvider) ClassPathResource(org.springframework.core.io.ClassPathResource) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) UpdateResultEventResponse(org.fisco.bcos.channel.test.contract.MixContract.UpdateResultEventResponse) CreateResultEventResponse(org.fisco.bcos.channel.test.contract.MixContract.CreateResultEventResponse) BigInteger(java.math.BigInteger) List(java.util.List) RemoteCall(org.fisco.bcos.web3j.protocol.core.RemoteCall) RemoveResultEventResponse(org.fisco.bcos.channel.test.contract.MixContract.RemoveResultEventResponse)

Aggregations

TransactionReceipt (org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt)41 BigInteger (java.math.BigInteger)18 Service (org.fisco.bcos.channel.client.Service)10 Credentials (org.fisco.bcos.web3j.crypto.Credentials)10 Web3j (org.fisco.bcos.web3j.protocol.Web3j)10 ChannelEthereumService (org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService)10 ApplicationContext (org.springframework.context.ApplicationContext)10 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)10 RateLimiter (com.google.common.util.concurrent.RateLimiter)9 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)9 ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)9 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)8 Random (java.util.Random)6 Utf8String (org.fisco.bcos.web3j.abi.datatypes.Utf8String)5 StaticGasProvider (org.fisco.bcos.web3j.tx.gas.StaticGasProvider)5 List (java.util.List)4 PrecompileMessageException (org.fisco.bcos.web3j.precompile.exception.PrecompileMessageException)3 Test (org.junit.Test)3 IOException (java.io.IOException)2