【web3j】java调用链上合约里的方法
生活随笔
收集整理的這篇文章主要介紹了
【web3j】java调用链上合约里的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
提前準備infura的鏈接,鏈上合約地址,合約里的方法名,錢包私鑰(小狐貍插件里點賬戶地址右邊的三個點,再點賬戶詳情就看到了)。注:下面的示例調用了兩個get方法,傳參Uint
一、用到的包
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.3.1</version> </dependency> <!-- web3j --> <dependency><groupId>org.web3j</groupId><artifactId>core</artifactId><version>4.8.7</version> </dependency> <dependency><groupId>org.web3j</groupId><artifactId>codegen</artifactId><version>5.0.0</version> </dependency> <dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version> </dependency>import org.web3j.abi.FunctionEncoder; import org.web3j.abi.FunctionReturnDecoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.*; 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.EthCall; import org.web3j.protocol.http.HttpService;import java.math.BigInteger; import java.util.Collections; import java.util.List;二、代碼
/*** @author maomo* @version 1.0.0* @date 2022-10-31**/ public class Web3Utils {static Web3j web3j = Web3j.build(new HttpService("https://goerli.infura.io/v3/***************"));/** 鏈上合約地址 */public static final String CONTRACT_ADDRESS = "***************";/** 沒有擁有者時返回的地址 */public static String DEFAULT_OWNER = "0x0000000000000000000000000000000000000000";/** 方法名,通過tokenId獲取ownerAddress(這是erc721自帶的方法) */public static String OWNER_OF = "ownerOf";/** 方法名,通過nftId獲取ownerAddress(這是合約里自定義的方法) */public static String GET_OWNER_BY_NFT_ID = "getOwnerByNFTId";public static void main(String[] args) {System.out.println("ownerOf:"+new Web3Utils().getOwnerByTokenId(1));System.out.println("getOwnerByNFTId:"+new Web3Utils().getOwnerByNftId(1));}/*** 調用合約的只讀方法,無需gas* @param functionName 合約方法名* @param param 參數* @throws Exception 異常*/public String getValue(String functionName,String param) {try {Function function = new Function(functionName,Collections.singletonList(new Uint(new BigInteger(param))),Collections.singletonList(new TypeReference<Address>() {}));String encodedFunction = FunctionEncoder.encode(function);EthCall response = web3j.ethCall(Transaction.createEthCallTransaction(null, contractAddress, encodedFunction),DefaultBlockParameterName.LATEST).sendAsync().get();List<Type> results = FunctionReturnDecoder.decode(response.getValue(), function.getOutputParameters());Type type = results.get(0);String value = (String) type.getValue();if(ObjectUtils.isEmpty(value) || DEFAULT_OWNER.equals(value)){return null;}return (String)type.getValue();}catch (Exception ignore){return null;}}}總結
以上是生活随笔為你收集整理的【web3j】java调用链上合约里的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Angular2-管道Pipe
- 下一篇: 马虎词汇教程26-30(转载)