提前准备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;
}
}
}