java如何调用合约完整代码

413 阅读1分钟

正题

前言:

之前踩坑太多了,各种报错都经历了一遍,比如最经常碰到就是网络拥堵或者gas limit设置太低,然后用别人提供的工具类嘛,我只能说我用不来,尤其只有transaction方法的调用,我还以为通用接口呢,索性研究一下怎么编译sol合约代码,自己调用吧,我这里用的是编译abi,当然也可以编译sol代码,只是我觉得sol代码万一调别人合约没给源码呢,总觉得编译sol文件调用坑比较多。

images.png

web3PanckSwap

Call Panckswap V2 interface to query USDT price.

调用panckswap合约的getAmountsOut方法查看代币对价格,里面我写死了usdt地址,传入其他代币获得代币的usdt价格

1. Pom Explanation

You can check the corresponding dependencies on Maven Repository.

<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>

2.Compile ABI to Generate Java Code

maven command:

通过导入abi,编译成java代码,通过load方法直接调用合约的方法。

mvn web3j:generate-sources

         <plugin>
                <groupId>org.web3j</groupId>
                <artifactId>web3j-maven-plugin</artifactId>
                <version>4.8.7</version> <!-- 替换为最新版本 -->
                <configuration>
                    <packageName>com.example.contract.abi</packageName>
                    <abiSourceFiles>
                        <directory>src/main/resources</directory>
                        <includes>
                            <include>abi/*.json</include>
                        </includes>
                    </abiSourceFiles>
                    <outputDirectory>
                        <java>src/main/java</java>
                    </outputDirectory>
                </configuration>
            </plugin>

images.jpg

3.RPC Explanation

一些bnb网络的rpc写死在代码enum中使用随机调用的方式如果要调用eth链则需要换掉

PRC1("https://binance.llamarpc.com"),

PRC2("https://bsc.blockpi.network/v1/rpc/public"),

PRC3("https://bsc-dataseed3.defibit.io"),

PRC4("https://rpc.ankr.com/bsc"),

PRC5("https://bsc-dataseed3.defibit.io");

Note

This is an interface to request PanckSwap for querying token-to-USDT exchange prices. It can be directly deployed to a server.

Demo

效果展示:

微信截图_20231220135404.png

Corresponding effect

微信截图_20231220134622.png

下载.jpg

Application Configuration

app:
  apiKey: ethscan 的apikey or bscscan  apikey
  # 代理
  http:
    proxy:
      enable: true
      host: localhost
      port: 7890

4.Code Consideration

public class ContractUtil {
    public static Panckswap getPanckSwap(RpcConfig rpcConfig, String erc20Address) {
        Web3j web3j = EthereumUtil.getWeb3jByRpcUrl(rpcConfig.isEnableProxy(), rpcConfig.getRpcUrl());
        // 此处改为自己钱包的私钥地址
        Credentials credentials = Credentials.create("<privite key>");
        return Panckswap.load(erc20Address, web3j, credentials, new DefaultGasProvider());
    }
}

github源码地址:

Github