Search in sources :

Example 11 with TransactionReceipt

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

the class OkClient method testOk.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void testOk(String[] args) throws Exception {
    final Resource contractResource = new ClassPathResource("contract.properties");
    PropertiesConfiguration prop = new PropertiesConfiguration(contractResource.getFile());
    Object addressObj = prop.getProperty("ok_address");
    if (addressObj != null) {
        contractAddress = (String) addressObj;
    } else {
        deployOk();
    }
    ContractGasProvider contractGasProvider = new StaticGasProvider(gasPrice, gasLimit);
    ;
    Ok ok = Ok.load(contractAddress, web3j, credentials, contractGasProvider);
    // trans
    if ("trans".equals(args[0])) {
        if (args.length == 2) {
            String num = args[1];
            RemoteCall<TransactionReceipt> insert = ok.trans(new BigInteger(num));
            TransactionReceipt txReceipt = insert.send();
            System.out.println(txReceipt.getTransactionHash());
        } else {
            System.out.println("\nPlease enter as follow example:\n 1 trans 5");
        }
    } else // get
    if ("get".equals(args[0])) {
        BigInteger num = ok.get().send();
        System.out.println("num = " + num);
    } else {
        System.out.println("\nPlease choose follow commands:\n deploy, trans or get");
    }
}
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) BigInteger(java.math.BigInteger) PropertiesConfiguration(org.apache.commons.configuration.PropertiesConfiguration) ContractGasProvider(org.fisco.bcos.web3j.tx.gas.ContractGasProvider) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 12 with TransactionReceipt

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

the class PerfomanceTableModify method main.

public static void main(String[] args) throws Exception {
    try {
        String groupId = args[3];
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        Service service = context.getBean(Service.class);
        service.setGroupId(Integer.parseInt(groupId));
        service.run();
        System.out.println("Start test...");
        System.out.println("===================================================================");
        ChannelEthereumService channelEthereumService = new ChannelEthereumService();
        channelEthereumService.setChannelService(service);
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(500);
        Web3j web3 = Web3j.build(channelEthereumService, 15 * 100, scheduledExecutorService, Integer.parseInt(groupId));
        Credentials credentials = Credentials.create("b83261efa42895c38c6c2364ca878f43e77f3cddbc922bf57d0d48070f79feb6");
        BigInteger gasPrice = new BigInteger("30000000");
        BigInteger gasLimit = new BigInteger("30000000");
        String command = args[0];
        Integer count = 0;
        Integer qps = 0;
        switch(command) {
            case "trans":
                count = Integer.parseInt(args[1]);
                qps = Integer.parseInt(args[2]);
                break;
            default:
                System.out.println("Args: <trans> <Total> <QPS>");
        }
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(count);
        threadPool.initialize();
        System.out.println("Deploying contract...");
        TableTest tabletest = TableTest.deploy(web3, credentials, gasPrice, gasLimit).send();
        PerfomanceCollector collector = new PerfomanceCollector();
        collector.setTotal(count);
        RateLimiter limiter = RateLimiter.create(qps);
        Integer area = count / 10;
        final Integer total = count;
        Random random = new Random(System.currentTimeMillis());
        System.out.println("Start test,total:" + count);
        for (Integer i = 0; i < count; ++i) {
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    limiter.acquire();
                    PerfomanceTableTestCallback callback = new PerfomanceTableTestCallback();
                    callback.setCollector(collector);
                    try {
                        long _id = getNextID();
                        Random r = new Random();
                        long l1 = r.nextLong();
                        tabletest.update("fruit" + l1 % TableTestClient.modevalue, BigInteger.valueOf(_id), "apple" + getId(), callback);
                    } catch (Exception e) {
                        TransactionReceipt receipt = new TransactionReceipt();
                        receipt.setStatus("-1");
                        callback.onResponse(receipt);
                        logger.error("Error sending:", e);
                    }
                    int current = sended.incrementAndGet();
                    if (current >= area && ((current % area) == 0)) {
                        System.out.println("Already sended: " + current + "/" + total + " transactions");
                    }
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Service(org.fisco.bcos.channel.client.Service) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) ApplicationContext(org.springframework.context.ApplicationContext) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Web3j(org.fisco.bcos.web3j.protocol.Web3j) Random(java.util.Random) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Credentials(org.fisco.bcos.web3j.crypto.Credentials)

Example 13 with TransactionReceipt

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

the class CallContractTest method testSyncCallContract.

private static void testSyncCallContract(CallContract callContract, String address) {
    CallResult contractResult;
    contractResult = callContract.call(address, "getStringOld", new Utf8String("hello world"), new Int256(10086), new Bool(true));
    List<TypeReference<?>> referencesList = Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
    });
    List<Type> returnList1 = FunctionReturnDecoder.decode(contractResult.getOutput(), Utils.convert(referencesList));
    System.out.println("call getStringOld: " + (String) returnList1.get(0).getValue());
    TransactionReceipt receipt;
    receipt = callContract.sendTransaction(gasPrice, gasLimit, address, "setAndget", new Utf8String("hello world"), new Int256(10086));
    referencesList = Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
    }, new TypeReference<Int256>() {
    });
    List<Type> returnList2 = FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
    System.out.println("call setAndget: " + (String) returnList2.get(0).getValue() + ", " + (BigInteger) returnList2.get(1).getValue());
    receipt = callContract.sendTransaction(address, "setAndget", new Utf8String("hello world"), new Int256(10086));
    referencesList = Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
    }, new TypeReference<Int256>() {
    });
    List<Type> returnList3 = FunctionReturnDecoder.decode(receipt.getOutput(), Utils.convert(referencesList));
    System.out.println("default call setAndget: " + (String) returnList3.get(0).getValue() + ", " + (BigInteger) returnList3.get(1).getValue());
    contractResult = callContract.call(address, "getArray", new StaticArray2(typeMap(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(2)), Int16.class)), new DynamicArray(typeMap(Arrays.asList(BigInteger.valueOf(2), BigInteger.valueOf(2)), Uint16.class)));
    List<Type> returnList4 = callContract.decode(contractResult.getOutput(), new TypeReference<StaticArray2<Int16>>() {
    }, new TypeReference<DynamicArray<Int16>>() {
    });
    System.out.println("call getArray: " + callContract.convertList((List<Type>) returnList4.get(0).getValue()) + ", " + callContract.convertList((List<Type>) returnList4.get(1).getValue()));
    List<List<BigInteger>> dyadicArray = new ArrayList<List<BigInteger>>();
    dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(2)));
    dyadicArray.add(Arrays.asList(BigInteger.valueOf(-1), BigInteger.valueOf(992)));
    byte[] bytes = new byte[] { 'a', 'b' };
    contractResult = callContract.call(address, "newTest", new StaticArray2(typeMap(dyadicArray, StaticArray2.class, Int256.class)), new DynamicBytes(bytes));
    List<Type> returnList5 = callContract.decode(contractResult.getOutput(), new TypeReference<StaticArray2<StaticArray2<Int256>>>() {
    }, new TypeReference<DynamicBytes>() {
    });
    System.out.println("call newTest: " + callContract.convertListList((List<StaticArray<Int256>>) returnList5.get(0).getValue()) + ", " + new String((byte[]) returnList5.get(1).getValue()) + ", " + dyadicArray);
}
Also used : ArrayList(java.util.ArrayList) Utf8String(org.fisco.bcos.web3j.abi.datatypes.Utf8String) Int16(org.fisco.bcos.web3j.abi.datatypes.generated.Int16) DynamicBytes(org.fisco.bcos.web3j.abi.datatypes.DynamicBytes) Bool(org.fisco.bcos.web3j.abi.datatypes.Bool) Uint16(org.fisco.bcos.web3j.abi.datatypes.generated.Uint16) ArrayList(java.util.ArrayList) List(java.util.List) TypeReference(org.fisco.bcos.web3j.abi.TypeReference) StaticArray(org.fisco.bcos.web3j.abi.datatypes.StaticArray) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) 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) DynamicArray(org.fisco.bcos.web3j.abi.datatypes.DynamicArray) BigInteger(java.math.BigInteger) StaticArray2(org.fisco.bcos.web3j.abi.datatypes.generated.StaticArray2)

Example 14 with TransactionReceipt

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

the class ChannelEthereumService method sendOnly.

@Override
public void sendOnly(Request request) throws IOException {
    byte[] payload = objectMapper.writeValueAsBytes(request);
    BcosRequest fiscoRequest = new BcosRequest();
    fiscoRequest.setKeyID(channelService.getOrgID());
    fiscoRequest.setBankNO("");
    fiscoRequest.setContent(new String(payload));
    fiscoRequest.setMessageID(channelService.newSeq());
    if (timeout != 0) {
        fiscoRequest.setTimeout(timeout);
    }
    if (!request.isNeedTransCallback()) {
        channelService.asyncSendEthereumMessage(fiscoRequest, new BcosResponseCallback() {

            @Override
            public void onResponse(BcosResponse response) {
                try {
                    logger.debug("fisco Request:{} {}", fiscoRequest.getMessageID(), objectMapper.writeValueAsString(request));
                    logger.debug("fisco Response:{} {} {}", fiscoRequest.getMessageID(), response.getErrorCode(), response.getContent());
                    if (response.getErrorCode() != 0) {
                        logger.error("Error: " + response.getErrorCode());
                    }
                } catch (Exception e) {
                    logger.error("Error: ", e);
                }
            }
        });
    } else {
        channelService.asyncSendEthereumMessage(fiscoRequest, new BcosResponseCallback() {

            @Override
            public void onResponse(BcosResponse response) {
                try {
                    logger.debug("fisco Request:{} {}", fiscoRequest.getMessageID(), objectMapper.writeValueAsString(request));
                    logger.debug("fisco Response:{} {} {}", fiscoRequest.getMessageID(), response.getErrorCode(), response.getContent());
                    if (response.getErrorCode() == 0) {
                        // SendTransaction
                        SendTransaction sendTransaction = objectMapper.readValue(response.getContent(), SendTransaction.class);
                        if (sendTransaction.getError() == null) {
                            logger.debug("sendRawTransaction response ok, transaction hash: {} ", sendTransaction.getResult());
                        } else {
                            TransactionReceipt receipt = new TransactionReceipt();
                            receipt.setStatus(String.valueOf(sendTransaction.getError().getCode()));
                            receipt.setMessage(sendTransaction.getError().getMessage());
                            // optional code
                            if (channelService.getThreadPool() == null) {
                                channelService.onReceiveTransactionMessage(fiscoRequest.getMessageID(), receipt);
                            } else {
                                // Execute the callback function in the thread pool
                                channelService.getThreadPool().execute(new Runnable() {

                                    @Override
                                    public void run() {
                                        channelService.onReceiveTransactionMessage(fiscoRequest.getMessageID(), receipt);
                                    }
                                });
                            }
                            logger.debug(" sendRawTransaction response not ok, code: {}, message: {} ", receipt.getStatus(), receipt.getMessage());
                        }
                    }
                } catch (Exception e) {
                    logger.error("Error: ", e);
                }
            }
        }, request.getTransactionSucCallback());
    }
}
Also used : BcosResponseCallback(org.fisco.bcos.channel.client.BcosResponseCallback) BcosResponse(org.fisco.bcos.channel.dto.BcosResponse) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) SendTransaction(org.fisco.bcos.web3j.protocol.core.methods.response.SendTransaction) BcosRequest(org.fisco.bcos.channel.dto.BcosRequest) IOException(java.io.IOException) MessageDecodingException(org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException) ContractCallException(org.fisco.bcos.web3j.tx.exceptions.ContractCallException)

Example 15 with TransactionReceipt

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

the class Contract method create.

private static <T extends Contract> T create(T contract, String binary, String encodedConstructor, BigInteger value) throws IOException, TransactionException {
    TransactionReceipt transactionReceipt = contract.executeTransaction(binary + encodedConstructor, value, FUNC_DEPLOY);
    String contractAddress = transactionReceipt.getContractAddress();
    if (contractAddress == null) {
        throw new RuntimeException("Empty contract address returned");
    }
    contract.setContractAddress(contractAddress);
    contract.setTransactionReceipt(transactionReceipt);
    return contract;
}
Also used : TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt)

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