当前位置:   article > 正文

java web3j 智能合约 读方法和写方法_web3j获取调合约里的getnonce方法获取nonce,getnonce方法没有参数

web3j获取调合约里的getnonce方法获取nonce,getnonce方法没有参数

pom.xml

		<dependency>
			<groupId>org.web3j</groupId>
			<artifactId>core</artifactId>
			<version>5.0.0</version>
		</dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.3.1</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

代码

package com.example.demo.controller;

import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.FunctionReturnDecoder;
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.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.*;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author 
 */
public class ContractUtil {

    private Web3j bscWeb3j = Web3j.build(new HttpService("https://data-seed-prebsc-1-s1.binance.org:8545"));
    
    private Credentials credentials = Credentials.create("matemask的私钥");

    /**
     * call
     * @return
     */
    public Object call() {
        String methodName = "claimUpgratedMaterial";
        List<Type> inputParameters = new ArrayList<>();
        inputParameters.add(new Uint256(1));
        List<TypeReference<?>> outputParameters = new ArrayList<>();

        TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {};
        outputParameters.add(typeReference);
        Function function = new Function(methodName, inputParameters, outputParameters);
        String data = FunctionEncoder.encode(function);
        Transaction transaction = Transaction.createEthCallTransaction("0x500616C4a5CCeE062b6c9aD8855F48940FE754c0", "", data);

        EthCall ethCall;
        Object balanceValue = null;
        try {
            ethCall = bscWeb3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
            List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
            if (results != null) {
                balanceValue = results.get(0).getValue();
            }
        } catch (IOException e) {

        }
        return balanceValue;
    }

    /**
     * send
     * @return
     */
    public String send() throws Exception {
        BigInteger nonce = getNonce("0x500616C4a5CCeE062b6c9aD8855F48940FE754c0");
        String methodName = "startProcess";
        List<Type> inputParameters = new ArrayList<>();
        inputParameters.add(new Uint256(1));
        inputParameters.add(new Uint256(1000));
        List<TypeReference<?>> outputParameters = new ArrayList<>();
        TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {};
        outputParameters.add(typeReference);
        
        Function function = new Function(methodName, inputParameters, outputParameters);

        String functionEncode = FunctionEncoder.encode(function);

        BigInteger gasPrice = bscWeb3j.ethGasPrice().send().getGasPrice().multiply(BigInteger.TEN);
        BigInteger gasLimit = new BigInteger("500000");
        
        RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, "0x72A49A8Af3eF49B3058F4e3f320c411eE9979165",functionEncode);
        EthSendTransaction response = bscWeb3j.ethSendRawTransaction(Numeric.toHexString(TransactionEncoder.signMessage(rawTransaction, credentials)))
                .sendAsync()
                .get();
        if (response.hasError()) {
            System.out.println("合约deposit方法执行异常:" + response.getError().getMessage());
        } else {
        	System.out.println("deposit执行完成,nonce=[" + nonce + "],hash=[" + response.getTransactionHash() + "]");
            String hash = response.getTransactionHash();
            
            while (true) {
            	boolean isOk = transactionCheck(hash);
            	
                System.out.println("transactionCheck:" + isOk);
                
            	if (isOk) {
					break;
				}
				
            	try {
					Thread.sleep(800);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
        }
        
        return null;
    }


    /**
     * 使用交易hash查询交易状态
     * @param hash
     * @return
     * @throws IOException
     */
    public boolean transactionCheck(String hash) throws IOException {
        Optional<TransactionReceipt> receipt = bscWeb3j.ethGetTransactionReceipt(hash).send().getTransactionReceipt();
        if (receipt.isPresent()) {
            TransactionReceipt transactionReceipt = receipt.get();
            return transactionReceipt.isStatusOK();
        } else {
            return false;
        }
    }

    /**
     * 获取账户的Nonce
     * @param address
     * @return
     */
    public BigInteger getNonce(String address) {
        try {
            EthGetTransactionCount getNonce = bscWeb3j.ethGetTransactionCount(address,DefaultBlockParameterName.PENDING).send();
            if (getNonce == null){
                throw new RuntimeException("net error");
            }
            return getNonce.getTransactionCount();
        } catch (IOException e) {
            throw new RuntimeException("net error");
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/574657
推荐阅读
相关标签
  

闽ICP备14008679号