[web3j]java使用web3j调用以太坊私链上的智能合约

/ 5,374评论 / 24339阅读 / 9点赞

环境


web3j命令行工具

* 这个工具可以帮我们把合约生成为一个java类,供我们实现java调用智能合约。

* github项目链接


安装4.5.5以上的新版本(4.9)


安装4.5.5以及之前的旧版本

此时的目录结构
web3j_home=/usr/local/sbin/web3j
PATH=$web3j_home/bin:$PATH
export PATH

在Maven中导入web3j

<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.9.0</version>
</dependency>
<dependency>
  <groupId>org.web3j</groupId>
  <artifactId>core</artifactId>
  <version>4.9.0-android</version>
</dependency>

生成测试文件(java智能合约封装器)

准备sol,abi和bin文件

// SPDX-License-Identifier: SimPL-2.0
pragma solidity >=0.4.0 <=0.7.0;

contract HelloWorld {
    uint count = 2022;
    
    function setCount(uint in_count) public
    {
        count = in_count;
    }

    function GetCount()public view returns(uint)
    {
        return count;
    }
}

使用web3j把智能合约生成java类

web3j generate solidity -a hello.abi -b hello.bin -o ./web_hello -p com.coolight.hello

修改web3j自动生成的java类

    //web3j自动生成的函数
    public RemoteFunctionCall<TransactionReceipt> GetCount() {
        final Function function = new Function(
                FUNC_GETCOUNT, 
                Arrays.<Type>asList(), 
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }
    //增加的函数
    public RemoteFunctionCall<BigInteger> GetCountReturn() {
        final Function function = new Function(
                FUNC_GETCOUNT,
                Collections.emptyList(),
                Arrays.asList(new TypeReference<Uint256>(){}));
        return executeRemoteCallSingleValueReturn(function, BigInteger.class);
    }
    //web3j自动生成的函数
    public RemoteFunctionCall<TransactionReceipt> getUserEvent(String user_name) 
    {
        final Function function = new Function(
                FUNC_GETUSEREVENT,
                Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(user_name)),
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }

    //增加的函数
    public RemoteFunctionCall<String> getUserEventReturn(String user_name) {
        final Function function = new Function(
                FUNC_GETUSEREVENT,
                Arrays.asList(new org.web3j.abi.datatypes.Utf8String(user_name)),
                Arrays.asList(new TypeReference<Utf8String>(){}));
        return  executeRemoteCallSingleValueReturn(function, String.class);
    }
    //web3j自动生成的函数
    public RemoteFunctionCall<TransactionReceipt> getUserLen(String user_name) {
        final Function function = new Function(
                FUNC_GETUSERLEN,
                Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(user_name)),
                Collections.<TypeReference<?>>emptyList());
        return  executeRemoteCallTransaction(function);
    }

    //增加的函数
    public RemoteFunctionCall<BigInteger> getUserLenReturn(String user_name) {
        final Function function = new Function(
                FUNC_GETUSERLEN,
                Arrays.asList(new org.web3j.abi.datatypes.Utf8String(user_name)),
                Arrays.asList(new TypeReference<Uint256>(){}));
        return executeRemoteCallSingleValueReturn(function, BigInteger.class);
    }
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.RemoteFunctionCall;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Contract;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.ContractGasProvider;

/**
 * <p>Auto generated code.
 * <p><strong>Do not modify!</strong>
 * <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
 * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the 
 * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
 *
 * <p>Generated with web3j version 4.5.5.
 */
@SuppressWarnings("rawtypes")
public class Hello extends Contract {
    private static final String BINARY = "{\n"
            + "\t\"linkReferences\": {},\n"
            + "\t\"object\": \"60806040526107e660005534801561001657600080fd5b5060c7806100256000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630ab93971146037578063d14e62b8146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506087565b005b60008054905090565b806000819055505056fea26469706673582212205f4a89ec8a6affc1a5970dfedafa55c57435fd83a7635cd22b59193fcb6e42e964736f6c63430007000033\",\n"
            + "\t\"opcodes\": \"PUSH1 0x80 PUSH1 0x40 MSTORE PUSH2 0x7E6 PUSH1 0x0 SSTORE CALLVALUE DUP1 ISZERO PUSH2 0x16 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0xC7 DUP1 PUSH2 0x25 PUSH1 0x0 CODECOPY PUSH1 0x0 RETURN INVALID PUSH1 0x80 PUSH1 0x40 MSTORE CALLVALUE DUP1 ISZERO PUSH1 0xF JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST POP PUSH1 0x4 CALLDATASIZE LT PUSH1 0x32 JUMPI PUSH1 0x0 CALLDATALOAD PUSH1 0xE0 SHR DUP1 PUSH4 0xAB93971 EQ PUSH1 0x37 JUMPI DUP1 PUSH4 0xD14E62B8 EQ PUSH1 0x53 JUMPI JUMPDEST PUSH1 0x0 DUP1 REVERT JUMPDEST PUSH1 0x3D PUSH1 0x7E JUMP JUMPDEST PUSH1 0x40 MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40 MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST PUSH1 0x7C PUSH1 0x4 DUP1 CALLDATASIZE SUB PUSH1 0x20 DUP2 LT ISZERO PUSH1 0x67 JUMPI PUSH1 0x0 DUP1 REVERT JUMPDEST DUP2 ADD SWAP1 DUP1 DUP1 CALLDATALOAD SWAP1 PUSH1 0x20 ADD SWAP1 SWAP3 SWAP2 SWAP1 POP POP POP PUSH1 0x87 JUMP JUMPDEST STOP JUMPDEST PUSH1 0x0 DUP1 SLOAD SWAP1 POP SWAP1 JUMP JUMPDEST DUP1 PUSH1 0x0 DUP2 SWAP1 SSTORE POP POP JUMP INVALID LOG2 PUSH5 0x6970667358 0x22 SLT KECCAK256 0x5F 0x4A DUP10 0xEC DUP11 PUSH11 0xFFC1A5970DFEDAFA55C574 CALLDATALOAD REVERT DUP4 0xA7 PUSH4 0x5CD22B59 NOT EXTCODEHASH 0xCB PUSH15 0x42E964736F6C634300070000330000 \",\n"
            + "\t\"sourceMap\": \"75:231:0:-:0;;;115:4;102:17;;75:231;;;;;;;;;;;;;;;;\"\n"
            + "}\n";

    public static final String FUNC_GETCOUNT = "GetCount";

    public static final String FUNC_SETCOUNT = "setCount";

    @Deprecated
    protected Hello(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    protected Hello(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        super(BINARY, contractAddress, web3j, credentials, contractGasProvider);
    }

    @Deprecated
    protected Hello(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
    }

    protected Hello(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);
    }

    public RemoteFunctionCall<TransactionReceipt> GetCount() {
        final Function function = new Function(
                FUNC_GETCOUNT, 
                Arrays.<Type>asList(), 
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }

    // 新增获取返回值方法
    public RemoteFunctionCall<BigInteger> GetCountReturn() {
        final Function function = new Function(
                FUNC_GETCOUNT, 
                Collections.emptyList(),
                Arrays.asList(new TypeReference<Uint256>(){}));
        return executeRemoteCallSingleValueReturn(function, BigInteger.class);
    }

    public RemoteFunctionCall<TransactionReceipt> setCount(BigInteger in_count) {
        final Function function = new Function(
                FUNC_SETCOUNT, 
                Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Uint256(in_count)), 
                Collections.<TypeReference<?>>emptyList());
        return executeRemoteCallTransaction(function);
    }

    @Deprecated
    public static Hello load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return new Hello(contractAddress, web3j, credentials, gasPrice, gasLimit);
    }

    @Deprecated
    public static Hello load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        return new Hello(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
    }

    public static Hello load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        return new Hello(contractAddress, web3j, credentials, contractGasProvider);
    }

    public static Hello load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        return new Hello(contractAddress, web3j, transactionManager, contractGasProvider);
    }

    public static RemoteCall<Hello> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
        return deployRemoteCall(Hello.class, web3j, credentials, contractGasProvider, BINARY, "");
    }

    @Deprecated
    public static RemoteCall<Hello> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
        return deployRemoteCall(Hello.class, web3j, credentials, gasPrice, gasLimit, BINARY, "");
    }

    public static RemoteCall<Hello> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
        return deployRemoteCall(Hello.class, web3j, transactionManager, contractGasProvider, BINARY, "");
    }

    @Deprecated
    public static RemoteCall<Hello> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
        return deployRemoteCall(Hello.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, "");
    }
}

测试调用智能合约

import java.math.BigInteger;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.admin.methods.response.PersonalUnlockAccount;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.RawTransactionManager;
import org.web3j.tx.TransactionManager;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

public class App
{
   // 1 - 智能合约地址
   private static String contractAddress = "0x62f7ca98490B199857ccDf9e68C218DEf5000d50";

    //燃料消耗
    private static final BigInteger gasPrice = new BigInteger("100000");

    //消耗限制
    private static final BigInteger gasLimit = new BigInteger("300000");

    //2 - 私链ID
    private static final long chainId = 7;


   // main method
   public static void main(String[] args) {

        //3 - 私钥的文件名
        String fileName = "UTC--2022-01-22T14-43-04.829667987Z--7cbad9dbed1f3ef418de1f0c6412cfec197c7751";
        try{
        // 4 - 加载 web3j - 这里需要修改为你要连接的节点链接
       Web3j web3 = Web3j.build(new HttpService("http://localhost:8545/"));

        // 5 - 加载账号 - 第一个String是密码,第二个是私钥的文件路径
       Credentials credentials = WalletUtils.loadCredentials("123456", "/home/0Acoolight/geth/rungeth/data/keystore/" + fileName);
       // 6 - 加载合约
       Hello contract = Hello.load(
           contractAddress, web3,
           new RawTransactionManager(web3, credentials, chainId),
           new StaticGasProvider(gasPrice, gasLimit)
       );
       // say hello
       System.out.println("Welcome coolight - " + credentials.getAddress());
       // 7 - 调用智能合约
           BigInteger currentValue;
           // 获取Count的值 - 调用GetCountReturn() 相当于合约中的GetCount()
           currentValue = contract.GetCountReturn().send();
           System.out.println(currentValue);
           // 修改Count的值 - 调用setCount()
           contract.setCount(new BigInteger("1")).send();
           // 获取Count的值
           currentValue = contract.GetCountReturn().send();
           System.out.println(currentValue);
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

本文所用文件打包

如果显示需要登录,请刷新页面或点击此处下载

常见问题


常见数据类型所在包

  1. MichaelPycle说道:

    get generic clomid tablets: buy generic clomid without rx – can you get cheap clomid

  2. JamesLot说道:

    purchase prednisone prednisone brand name canada prednisone 10 mg tablet cost

  3. MichaelPycle说道:

    ivermectin gel: ivermectin india – ivermectin 400 mg

  4. JamesLot说道:

    can you buy generic clomid for sale can you buy cheap clomid for sale can you get cheap clomid price

  5. DomenicDobby说道:

    amoxicillin buy online canada: amoxicillin 500mg capsules – price of amoxicillin without insurance

  6. BrainSaw说道:

    https://amoxicillina.top/# where to buy amoxicillin

  7. BrainSaw说道:

    https://clomida.pro/# buying cheap clomid

  8. Williamwaymn说道:

    Услуга по сносу старых домов и вывозу мусора в Москве и Московской области. Мы предоставляем услуги по сносу старых зданий и удалению мусора на территории Москвы и Подмосковья. Услуга снос деревянных домов в московской области выполняется опытными специалистами в течение 24 часов после оформления заказа. Перед началом работ наш эксперт бесплатно приезжает на объект для оценки объёма работ и консультации. Чтобы получить дополнительную информацию и рассчитать стоимость услуг, свяжитесь с нами по телефону или оставьте заявку на сайте компании.

  9. BrainSaw说道:

    http://amoxicillina.top/# buy cheap amoxicillin online

  10. BryanSturf说道:

    40 mg prednisone pill: prednisone pill prices – buy prednisone 20mg

  11. MichaelPycle说道:

    buy amoxicillin online no prescription: how to buy amoxicillin online – amoxil generic

  12. MichaelPycle说道:

    buy cheap clomid without prescription: clomid without a prescription – can you get clomid for sale

  13. JamesLot说道:

    zithromax purchase online zithromax capsules 250mg where can i get zithromax

  14. BryanSturf说道:

    order zithromax without prescription: zithromax generic cost – zithromax 1000 mg pills

  15. JamesLot说道:

    prednisone 1mg purchase prednisone medicine prednisone 20mg cheap

  16. BrainSaw说道:

    https://prednisonea.store/# prednisone 10mg tabs

  17. JamesLot说道:

    ivermectin lice ivermectin 500ml ivermectin 6 tablet

  18. DomenicDobby说道:

    clomid without insurance: can i purchase cheap clomid without a prescription – can i get generic clomid online

  19. BrainSaw说道:

    http://amoxicillina.top/# cost of amoxicillin 30 capsules

  20. MichaelPycle说道:

    price of amoxicillin without insurance: buy amoxicillin over the counter uk – can you purchase amoxicillin online

  21. BrainSaw说道:

    http://azithromycina.pro/# zithromax z-pak price without insurance

  22. Wow, marvelous blog structure! How lengthy have you been blogging for?
    you make running a blog glance easy. The overall look of your site is great, let alone the content!
    You can see similar here sklep internetowy

  23. BryanSturf说道:

    ivermectin 1 cream 45gm: ivermectin 8 mg – topical ivermectin cost

  24. MichaelPycle说道:

    prednisone canada: prednisone 5 mg tablet price – where to buy prednisone without prescription

  25. DomenicDobby说道:

    ivermectin over the counter uk: ivermectin 1mg – ivermectin lotion for lice

  26. JamesLot说道:

    where can i buy generic clomid now cost generic clomid for sale where buy generic clomid for sale

  27. MichaelPycle说道:

    ivermectin 12 mg: ivermectin for humans – ivermectin 3mg tablet

  28. ustanovka_area说道:

    Полезные советы
    2. Шаг за шагом: установка кондиционера своими руками
    3. Важные моменты при установке кондиционера в квартире
    4. Специалисты или самостоятельная установка кондиционера?
    5. 10 шагов к идеальной установке кондиционера
    6. Подробная инструкция по установке кондиционера на балконе
    7. Лучшие методы крепления кондиционера на стену
    8. Как выбрать место для установки кондиционера в комнате
    9. Секреты успешной установки кондиционера в частном доме
    10. Рассказываем, как правильно установить сплит-систему
    11. Необходимые инструменты для установки кондиционера
    12. Какие документы нужны для оформления установки кондиционера?
    13. Топ-5 ошибок при самостоятельной установке кондиционера
    14. Установка кондиционера на потолке: особенности и нюансы
    15. Когда лучше всего устанавливать кондиционер в доме?
    16. Почему стоит доверить установку кондиционера профессионалам
    17. Как подготовиться к установке кондиционера в жаркий сезон
    18. Стоит ли экономить на установке кондиционера?
    19. Подбор оптимальной мощности кондиционера перед установкой
    20. Какие бывают типы кондиционеров: сравнение перед установкой

    обслуживание кондиционеров и вентиляции обслуживание кондиционеров и вентиляции .

  29. JamesLot说道:

    buy zithromax canada can you buy zithromax over the counter in canada zithromax 500 mg lowest price pharmacy online

  30. Josephtrink说道:

    http://stromectola.top/# is minocycline an antibiotic

  31. BryanSturf说道:

    ivermectin 4 mg: ivermectin 1 cream generic – stromectol otc

  32. JamesLot说道:

    can i get generic clomid prices where to get generic clomid pill where to buy cheap clomid without dr prescription

  33. MichaelPycle说道:

    buying generic clomid price: buy generic clomid without dr prescription – can you buy clomid without a prescription

  34. ustanovka_saOn说道:

    Установка кондиционера: как не нарваться на ошибки
    сплит система сплит система .

  35. BryanSturf说道:

    prednisone 30 mg coupon: prednisone price australia – prednisone 1 mg for sale

  36. Josephtrink说道:

    http://prednisonea.store/# generic prednisone for sale

  37. Josephtrink说道:

    https://azithromycina.pro/# buy zithromax online with mastercard

  38. ustanovka_jfea说道:

    Полезные советы
    2. Шаг за шагом: установка кондиционера своими руками
    3. Важные моменты при установке кондиционера в квартире
    4. Специалисты или самостоятельная установка кондиционера?
    5. 10 шагов к идеальной установке кондиционера
    6. Подробная инструкция по установке кондиционера на балконе
    7. Лучшие методы крепления кондиционера на стену
    8. Как выбрать место для установки кондиционера в комнате
    9. Секреты успешной установки кондиционера в частном доме
    10. Рассказываем, как правильно установить сплит-систему
    11. Необходимые инструменты для установки кондиционера
    12. Какие документы нужны для оформления установки кондиционера?
    13. Топ-5 ошибок при самостоятельной установке кондиционера
    14. Установка кондиционера на потолке: особенности и нюансы
    15. Когда лучше всего устанавливать кондиционер в доме?
    16. Почему стоит доверить установку кондиционера профессионалам
    17. Как подготовиться к установке кондиционера в жаркий сезон
    18. Стоит ли экономить на установке кондиционера?
    19. Подбор оптимальной мощности кондиционера перед установкой
    20. Какие бывают типы кондиционеров: сравнение перед установкой

    ремонт кондиціонера ремонт кондиціонера .

  39. ustanovka_joOn说道:

    Важные моменты при установке кондиционера: что учесть
    инверторный кондиционер https://ustanovka-kondicionera-cena.ru/ .

  40. MichaelPycle说道:

    prednisone 20mg prescription cost: how to buy prednisone – where can i get prednisone

  41. BryanSturf说道:

    zithromax order online uk: how to get zithromax online – can i buy zithromax over the counter

  42. JamesLot说道:

    zithromax online usa no prescription zithromax 500mg price in india zithromax 500 mg

  43. MichaelPycle说道:

    prednisone 20 mg tablet: prednisone 3 tablets daily – purchase prednisone no prescription

  44. JamesLot说道:

    zithromax online paypal zithromax 500mg price in india buy zithromax online australia

  45. DomenicDobby说道:

    buy minocycline 100mg otc: ivermectin price usa – ivermectin 3mg tablets

  46. RussellVeila说道:

    cytotec buy online usa: buy cytotec – cytotec abortion pill

  47. JeromedUb说道:

    tamoxifen and grapefruit tamoxifen hormone therapy aromatase inhibitors tamoxifen

  48. JeromedUb说道:

    order doxycycline online doxycycline without a prescription doxycycline 100mg online

  49. RussellVeila说道:

    where to get diflucan: diflucan over the counter pill – diflucan 150 australia

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注