日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

web3j 操作

發(fā)布時間:2024/1/1 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 web3j 操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

#####獲取賬戶的Nonce

public static BigInteger getNonce(Web3j web3j, String addr) {try {EthGetTransactionCount getNonce = web3j.ethGetTransactionCount(addr, DefaultBlockParameterName.PENDING).send();if (getNonce == null){throw new RuntimeException("net error");}return getNonce.getTransactionCount();} catch (IOException e) {throw new RuntimeException("net error");}}

#####獲取ETH余額

public static BigDecimal getBalance(Web3j web3j, String address) {try {EthGetBalance ethGetBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send();return Convert.fromWei(new BigDecimal(ethGetBalance.getBalance()),Convert.Unit.ETHER);} catch (IOException e) {e.printStackTrace();return null;}}

#####獲取代幣余額

public static BigInteger getTokenBalance(Web3j web3j, String fromAddress, String contractAddress) {String methodName = "balanceOf";List<Type> inputParameters = new ArrayList<>();List<TypeReference<?>> outputParameters = new ArrayList<>();Address address = new Address(fromAddress);inputParameters.add(address);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(fromAddress, contractAddress, data);EthCall ethCall;BigInteger balanceValue = BigInteger.ZERO;try {ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());balanceValue = (BigInteger) results.get(0).getValue();} catch (IOException e) {e.printStackTrace();}return balanceValue;}

#####構(gòu)造交易

// 構(gòu)造eth交易 Transaction transaction = Transaction.createEtherTransaction(fromAddr, nonce, gasPrice, null, toAddr, value); // 構(gòu)造合約調(diào)用交易 Transaction transaction = Transaction.createFunctionCallTransaction(fromAddr, nonce, gasPrice, null, contractAddr, funcABI);

#####估算手續(xù)費上限

public static BigInteger getTransactionGasLimit(Web3j web3j, Transaction transaction) {try {EthEstimateGas ethEstimateGas = web3j.ethEstimateGas(transaction).send();if (ethEstimateGas.hasError()){throw new RuntimeException(ethEstimateGas.getError().getMessage());}return ethEstimateGas.getAmountUsed();} catch (IOException e) {throw new RuntimeException("net error");}}

#####轉(zhuǎn)賬ETH

public static String transferETH(Web3j web3j, String fromAddr, String privateKey, String toAddr, BigDecimal amount, String data){// 獲得nonceBigInteger nonce = getNonce(web3j, fromAddr);// value 轉(zhuǎn)換BigInteger value = Convert.toWei(amount, Convert.Unit.ETHER).toBigInteger();// 構(gòu)建交易Transaction transaction = Transaction.createEtherTransaction(fromAddr, nonce, gasPrice, null, toAddr, value);// 計算gasLimitBigInteger gasLimit = getTransactionGasLimit(web3j, transaction);// 查詢調(diào)用者余額,檢測余額是否充足BigDecimal ethBalance = getBalance(web3j, fromAddr);BigDecimal balance = Convert.toWei(ethBalance, Convert.Unit.ETHER);// balance < amount + gasLimit ??if (balance.compareTo(amount.add(new BigDecimal(gasLimit.toString()))) < 0) {throw new RuntimeException("余額不足,請核實");}return signAndSend(web3j, nonce, gasPrice, gasLimit, toAddr, value, data, chainId, privateKey);}

#####轉(zhuǎn)賬代幣

public static String transferToken(Web3j web3j, String fromAddr, String privateKey, String toAddr, String contractAddr, long amount) {BigInteger nonce = getNonce(web3j, fromAddr);// 構(gòu)建方法調(diào)用信息String method = "transfer";// 構(gòu)建輸入?yún)?shù)List<Type> inputArgs = new ArrayList<>();inputArgs.add(new Address(toAddr));inputArgs.add(new Uint256(BigDecimal.valueOf(amount).multiply(BigDecimal.TEN.pow(18)).toBigInteger()));// 合約返回值容器List<TypeReference<?>> outputArgs = new ArrayList<>();String funcABI = FunctionEncoder.encode(new Function(method, inputArgs, outputArgs));Transaction transaction = Transaction.createFunctionCallTransaction(fromAddr, nonce, gasPrice, null, contractAddr, funcABI);RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, null, contractAddr, null, funcABI);BigInteger gasLimit = getTransactionGasLimit(web3j, transaction);// 獲得余額BigDecimal ethBalance = getBalance(web3j, fromAddr);BigInteger tokenBalance = getTokenBalance(web3j, fromAddr, contractAddr);BigInteger balance = Convert.toWei(ethBalance, Convert.Unit.ETHER).toBigInteger();if (balance.compareTo(gasLimit) < 0) {throw new RuntimeException("手續(xù)費不足,請核實");}if (tokenBalance.compareTo(BigDecimal.valueOf(amount).toBigInteger()) < 0) {throw new RuntimeException("代幣不足,請核實");}return signAndSend(web3j, nonce, gasPrice, gasLimit, contractAddr, BigInteger.ZERO, funcABI, chainId, privateKey);}

#####對交易簽名,并發(fā)送交易

public static String signAndSend(Web3j web3j, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to, BigInteger value, String data, byte chainId, String privateKey) {String txHash = "";RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, data);if (privateKey.startsWith("0x")){privateKey = privateKey.substring(2);}ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));Credentials credentials = Credentials.create(ecKeyPair);byte[] signMessage;if (chainId > ChainId.NONE){signMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);} else {signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);}String signData = Numeric.toHexString(signMessage);if (!"".equals(signData)) {try {EthSendTransaction send = web3j.ethSendRawTransaction(signData).send();txHash = send.getTransactionHash();System.out.println(JSON.toJSONString(send));} catch (IOException e) {throw new RuntimeException("交易異常");}}return txHash;}

#####獲取代理額度

public static BigInteger getAllowanceBalance(Web3j web3j, String fromAddr, String toAddr, String contractAddress) {String methodName = "allowance";List<Type> inputParameters = new ArrayList<>();inputParameters.add(new Address(fromAddr));inputParameters.add(new Address(toAddr));List<TypeReference<?>> outputs = new ArrayList<>();TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {};outputs.add(typeReference);Function function = new Function(methodName, inputParameters, outputs);String data = FunctionEncoder.encode(function);Transaction transaction = Transaction.createEthCallTransaction(fromAddr, contractAddress, data);EthCall ethCall;BigInteger balanceValue = BigInteger.ZERO;try {ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();List<Type> result = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());balanceValue = (BigInteger) result.get(0).getValue();} catch (IOException e) {e.printStackTrace();}return balanceValue;}

總結(jié)

以上是生活随笔為你收集整理的web3j 操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。