栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

How to integrate Web3j to java project

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

How to integrate Web3j to java project

How to integrate Web3j to java project
  • 1. Environment prepare
    • 1.1. Install solc
    • 1.2. Install web3j-cli
    • 1.3. Contract
  • 2. Compile
  • 3. Generate contract JAVA Wrapper
  • 4. Integration
    • 4.1. Maven dependencies:
    • 4.2. Create java classes:
  • 5. References

1. Environment prepare 1.1. Install solc
npm install -g solc

Check if success use this command:

solcjs --version

success like this:

1.2. Install web3j-cli

Download web3j-cli 1.4.1 from https://github.com/web3j/web3j-cli/releases
for example I used v1.4.1 :


extract zip files to local file system:


set web3j-cli’s /bin folder to system environment path:


install finish, check version:

1.3. Contract

Here I use the contract “StandardToken.sol” for testing. It can be download at github ( E.G. https://github.com/tintinweb/smart-contract-sanctuary)

2. Compile

Use command solcjs to compile *.sol file to get .abi and .bin files like below:

solcjs StandardToken.sol --bin --abi --optimize -o .

I got files like this:

3. Generate contract JAVA Wrapper

Command usage:

web3j solidity generate -a  -b  -o  -p 

E.G.


4. Integration 4.1. Maven dependencies:

Add dependencies to pom.xml like :

    
        
            junit
            junit
            4.13.2
            test
        
        
            org.web3j
            core
            5.0.0
        
    
4.2. Create java classes:

Copy contract wrapper file to java project and rename it to “StandardTokenContract.java” like below:

Here’s a helper class written by java named “ContractLoader” :

import okhttp3.OkHttpClient;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;

import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.Proxy;

public final class ContractLoader {
    private static String proxyHost;
    private static int proxyPort;
    private static String rpcUrl;

    private ContractLoader() {

    }

    public static void env(String proxyHost,
                           int proxyPort,
                           String rpcUrl) {
        ContractLoader.proxyHost = proxyHost;
        ContractLoader.proxyPort = proxyPort;
        ContractLoader.rpcUrl = rpcUrl;
    }

    
    public static  T getContract(String contractAddress,
                                                     Class contractClazz) throws Exception {
        return getContract("0000000000000000000000000000000000000000000000000000000000000000",
                Convert.toWei("3000000", Convert.Unit.WEI).toBigInteger(),
                contractAddress,
                contractClazz);
    }

    
    public static  T getContract(String senderPrivateKey,
                                                     String contractAddress,
                                                     Class contractClazz) throws Exception {
        return getContract(senderPrivateKey,
                Convert.toWei("3000000", Convert.Unit.WEI).toBigInteger(),
                contractAddress,
                contractClazz);
    }

    
    public static  T getContract(String senderPrivateKey,
                                                     BigInteger gasLimit,
                                                     String contractAddress,
                                                     Class contractClazz) throws Exception {
        if (null == ContractLoader.rpcUrl || "".equals(ContractLoader.rpcUrl)) {
            throw new Exception("Rpc url can not be empty!");
        }

        //set proxy
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (null != ContractLoader.proxyHost && !"".equals(ContractLoader.proxyHost) && ContractLoader.proxyPort > 0) {
            builder.proxy(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(ContractLoader.proxyHost, ContractLoader.proxyPort)));
        }
        OkHttpClient client = builder.build();

        //initial operation for web3j
        Web3j web3 = Web3j.build(new HttpService(ContractLoader.rpcUrl, client));
        Credentials credentials = Credentials.create(senderPrivateKey);
        EthGasPrice gasPrice = web3.ethGasPrice().sendAsync().get();

        //reflection of contract
        T result = null;
        if (gasPrice != null) {
            Method method = contractClazz.getMethod("load", String.class, Web3j.class, Credentials.class, ContractGasProvider.class);
            result = (T) method.invoke(contractClazz,
                    contractAddress,
                    web3,
                    credentials,
                    new StaticGasProvider(gasPrice.getGasPrice(), gasLimit)
            );
        }
        return result;
    }
}

And here’s a java unit test which used the BSC-TEST rpc point via socks5 proxy:

import com.yayd.contracthelper.ContractLoader;
import com.yayd.contracthelper.StandardTokenContract;
import org.junit.Test;
import org.web3j.utils.Convert;


public class AppTest {
    private static final String PRIVATE_KEY = "here is your wallet private key to authority";
    private static final String RPC_URL = "https://data-seed-prebsc-1-s3.binance.org:8545/";
    private static final String CONTRACT_ADDRESS = "here is your contract address on blockchain";
    public static final String PROXY_HOSTNAME = "127.0.0.1";
    public static final int PROXY_PORT = 10808;

    
    @Test
    public void testTransfer() {
        try {
            ContractLoader.env(
                    PROXY_HOSTNAME,
                    PROXY_PORT,
                    RPC_URL
            );
            //Load contract only read block data with default gas-limit 3000000.
            StandardTokenContract contract = ContractLoader.getContract(
                    CONTRACT_ADDRESS,
                    StandardTokenContract.class);
            System.out.println(contract.owner().send());

            //Load contract with read and write block data with default gas-limit 3000000.
            contract = ContractLoader.getContract(
                    PRIVATE_KEY,
                    CONTRACT_ADDRESS,
                    StandardTokenContract.class);
            System.out.println(contract.owner().send());

            //Load contract with read and write block data with customize gas-limit.
            contract = ContractLoader.getContract(
                    PRIVATE_KEY,
                    Convert.toWei("3000000", Convert.Unit.WEI).toBigInteger(),
                    CONTRACT_ADDRESS,
                    StandardTokenContract.class);
            System.out.println(contract.owner().send());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5. References

: https://docs.soliditylang.org/en/v0.8.14/installing-solidity.html

: https://docs.web3j.io/4.8.7/command_line_tools/

: https://docs.web3j.io/4.8.7/smart_contracts/construction_and_deployment/#solidity-smart-contract-wrappers

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/973832.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号