Search in sources :

Example 1 with StaticGasProvider

use of org.fisco.bcos.web3j.tx.gas.StaticGasProvider in project web3sdk by FISCO-BCOS.

the class TableTestClient method deployTableTest.

/* deploy the contract,get address from blockchain */
@SuppressWarnings("deprecation")
public static void deployTableTest() {
    RemoteCall<TableTest> deploy = TableTest.deploy(web3j, credentials, new StaticGasProvider(gasPrice, gasLimit));
    TableTest tabletest;
    try {
        tabletest = deploy.send();
        contractAddress = tabletest.getContractAddress();
        System.out.println("deploy contract address: " + contractAddress);
        logger.info("deploy contract address: " + contractAddress);
        final Resource contractResource = new ClassPathResource("contract.properties");
        PropertiesConfiguration prop = new PropertiesConfiguration(contractResource.getFile());
        prop.setProperty("crud_address", contractAddress);
        prop.save();
        System.out.println("deploy contract successful!");
    } catch (TransactionException e) {
        if ("0x19".equals(e.getStatus())) {
            System.out.println("non-authorized to deploy contracts!");
        } else {
            System.out.println("deploy transaction is abnormal, please check the environment msg:" + e.getMessage());
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("deploy transaction is abnormal, please check the environment");
    }
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(org.springframework.core.io.Resource) PropertiesConfiguration(org.apache.commons.configuration.PropertiesConfiguration) ClassPathResource(org.springframework.core.io.ClassPathResource) TransactionException(org.fisco.bcos.web3j.protocol.exceptions.TransactionException)

Example 2 with StaticGasProvider

use of org.fisco.bcos.web3j.tx.gas.StaticGasProvider 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 3 with StaticGasProvider

use of org.fisco.bcos.web3j.tx.gas.StaticGasProvider in project web3sdk by FISCO-BCOS.

the class TestBase method setUpBeforeClass.

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);
    System.out.println("EncryptType =>  " + EncryptType.getEncryptType());
    web3j = Web3j.build(channelEthereumService, service.getGroupId());
    credentials = GenCredential.create();
    Ok ok = Ok.deploy(web3j, credentials, new StaticGasProvider(gasPrice, gasLimit)).send();
    blockNumber = ok.getTransactionReceipt().get().getBlockNumber();
    blockHash = ok.getTransactionReceipt().get().getBlockHash();
    txHash = ok.getTransactionReceipt().get().getTransactionHash();
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) Service(org.fisco.bcos.channel.client.Service) ChannelEthereumService(org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService) Ok(org.fisco.bcos.channel.test.guomi.Ok) BeforeClass(org.junit.BeforeClass)

Example 4 with StaticGasProvider

use of org.fisco.bcos.web3j.tx.gas.StaticGasProvider in project web3sdk by FISCO-BCOS.

the class OkTest method testOkContract.

@Test
public void testOkContract() throws Exception {
    Ok ok = Ok.deploy(web3j, credentials, new StaticGasProvider(gasPrice, gasLimit)).send();
    if (ok != null) {
        TransactionReceipt receipt = ok.trans(new BigInteger("4")).send();
        assertTrue(receipt.getBlockNumber().intValue() > 0);
        assertTrue(receipt.getTransactionIndex().intValue() >= 0);
        assertTrue(receipt.getGasUsed().intValue() > 0);
        BigInteger oldBalance = ok.get().sendAsync().get(60000, TimeUnit.MILLISECONDS);
        ok.trans(new BigInteger("4")).sendAsync().get(60000, TimeUnit.MILLISECONDS);
        BigInteger newBalance = ok.get().sendAsync().get(60000, TimeUnit.MILLISECONDS);
        assertTrue(newBalance.intValue() == oldBalance.intValue() + 4);
    }
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) TransactionReceipt(org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt) BigInteger(java.math.BigInteger) Test(org.junit.Test)

Example 5 with StaticGasProvider

use of org.fisco.bcos.web3j.tx.gas.StaticGasProvider in project web3sdk by FISCO-BCOS.

the class PerformanceDTTest method userTransferTest.

public void userTransferTest(BigInteger count, BigInteger qps, BigInteger deci, BigInteger queryAccountQPS) {
    List<String> signedTransactions = new ArrayList<String>();
    List<PerformanceDTCallback> callbacks = new ArrayList<PerformanceDTCallback>();
    try {
        parallelokAddr = dagUserMgr.getContractAddr();
        parallelok = ParallelOk.load(parallelokAddr, web3, credentials, new StaticGasProvider(new BigInteger("30000000"), new BigInteger("30000000")));
        /*
            System.out.println("Reading account state...");
            List<DagTransferUser> allUser = dagUserMgr.getUserList();
            for (int i = 0; i < allUser.size(); ++i) {
                BigInteger result = parallelok.balanceOf(allUser.get(i).getUser()).send();
                allUser.get(i).setAmount(result);
            }
            */
        List<DagTransferUser> allUser = dagUserMgr.getUserList();
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        threadPool.setCorePoolSize(200);
        threadPool.setMaxPoolSize(500);
        threadPool.setQueueCapacity(Math.max(count.intValue(), allUser.size()) + 1000);
        threadPool.initialize();
        Lock lock = new ReentrantLock();
        final ParallelOk _parallelok = parallelok;
        RateLimiter queryAccountLimiter = RateLimiter.create(queryAccountQPS.intValue());
        AtomicInteger geted = new AtomicInteger(0);
        for (int i = 0; i < allUser.size(); ++i) {
            final Integer _i = i;
            queryAccountLimiter.acquire();
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        BigInteger result = _parallelok.balanceOf(allUser.get(_i).getUser()).send();
                        allUser.get(_i).setAmount(result);
                        int all = geted.incrementAndGet();
                        if (all >= allUser.size()) {
                            System.out.println(dateFormat.format(new Date()) + " Query account finished");
                        }
                    } catch (Exception e) {
                        System.out.println(" Query failed, user is " + allUser.get(_i).getUser());
                        System.exit(0);
                    }
                }
            });
        }
        while (geted.get() < allUser.size()) {
            Thread.sleep(50);
        }
        latch = new CountDownLatch(count.intValue());
        AtomicLong signed = new AtomicLong(0);
        // create signed transactions
        System.out.println("Creating signed transactions...");
        for (int i = 0; i < count.intValue(); ++i) {
            final int index = i;
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        DagTransferUser from = dagUserMgr.getFrom(index);
                        DagTransferUser to = dagUserMgr.getTo(index);
                        if ((deci.intValue() > 0) && (deci.intValue() >= (index % 10 + 1))) {
                            to = dagUserMgr.getNext(index);
                        }
                        Random random = new Random();
                        int r = random.nextInt(100);
                        BigInteger amount = BigInteger.valueOf(r);
                        PerformanceDTCallback callback = new PerformanceDTCallback();
                        callback.setCallBackType("transfer");
                        callback.setCollector(collector);
                        callback.setDagUserMgr(getDagUserMgr());
                        callback.setFromUser(from);
                        callback.setToUser(to);
                        callback.setAmount(amount);
                        try {
                            callback.recordStartTime();
                            String signedTransaction = parallelok.transferSeq(from.getUser(), to.getUser(), amount);
                            lock.lock();
                            signedTransactions.add(signedTransaction);
                            callbacks.add(callback);
                            long totalSigned = signed.incrementAndGet();
                            if (totalSigned % (count.longValue() / 10) == 0) {
                                System.out.println("Signed transaction: " + String.valueOf(totalSigned * 100 / count.longValue()) + "%");
                            }
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        } finally {
                            lock.unlock();
                        }
                    }
                    latch.countDown();
                }
            });
        }
        latch.await();
        latch = new CountDownLatch(count.intValue());
        long startTime = System.currentTimeMillis();
        collector.setStartTimestamp(startTime);
        AtomicInteger sent = new AtomicInteger(0);
        int division = count.intValue() / 10;
        RateLimiter limiter = RateLimiter.create(qps.intValue());
        System.out.println("Sending signed transactions...");
        for (int i = 0; i < count.intValue(); ++i) {
            limiter.acquire();
            final int index = i;
            threadPool.execute(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        try {
                            callbacks.get(index).recordStartTime();
                            transactionManager.sendTransaction(signedTransactions.get(index), callbacks.get(index));
                            break;
                        } catch (Exception e) {
                            continue;
                        }
                    }
                    int current = sent.incrementAndGet();
                    if (current >= division && ((current % division) == 0)) {
                        long elapsed = System.currentTimeMillis() - startTime;
                        double sendSpeed = current / ((double) elapsed / 1000);
                        System.out.println("Already sent: " + current + "/" + count + " transactions" + ",QPS=" + sendSpeed);
                    }
                    latch.countDown();
                }
            });
        }
        latch.await();
        while (!collector.isEnd()) {
            Thread.sleep(3000);
            logger.info(" received: {}, total: {}", collector.getReceived().intValue(), collector.getTotal());
        }
        veryTransferData(threadPool, queryAccountQPS);
        System.exit(0);
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}
Also used : StaticGasProvider(org.fisco.bcos.web3j.tx.gas.StaticGasProvider) ArrayList(java.util.ArrayList) Random(java.util.Random) ReentrantLock(java.util.concurrent.locks.ReentrantLock) CountDownLatch(java.util.concurrent.CountDownLatch) RateLimiter(com.google.common.util.concurrent.RateLimiter) Date(java.util.Date) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BigInteger(java.math.BigInteger) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)

Aggregations

StaticGasProvider (org.fisco.bcos.web3j.tx.gas.StaticGasProvider)16 BigInteger (java.math.BigInteger)10 PropertiesConfiguration (org.apache.commons.configuration.PropertiesConfiguration)6 ContractGasProvider (org.fisco.bcos.web3j.tx.gas.ContractGasProvider)6 ClassPathResource (org.springframework.core.io.ClassPathResource)6 Resource (org.springframework.core.io.Resource)6 Service (org.fisco.bcos.channel.client.Service)5 Credentials (org.fisco.bcos.web3j.crypto.Credentials)5 ChannelEthereumService (org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService)5 TransactionReceipt (org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt)5 ClassPathXmlApplicationContext (org.springframework.context.support.ClassPathXmlApplicationContext)5 Web3j (org.fisco.bcos.web3j.protocol.Web3j)4 ApplicationContext (org.springframework.context.ApplicationContext)4 Random (java.util.Random)3 TransactionException (org.fisco.bcos.web3j.protocol.exceptions.TransactionException)3 ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor)3 RateLimiter (com.google.common.util.concurrent.RateLimiter)2 Date (java.util.Date)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2