Jvav 调用 Conflux 智能合约

1. 加入 Conflux 库

        
            io.github.conflux-chain
            conflux.web3j
            1.1.0
        
import conflux.web3j.Account;
import conflux.web3j.Cfx;
import conflux.web3j.AccountManager;
import conflux.web3j.contract.ContractCall;
import conflux.web3j.contract.abi.DecodeUtil;
import conflux.web3j.types.Address;

import org.web3j.abi.FunctionReturnDecoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.*;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Bip39Wallet;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.abi.Utils;

import java.io.File;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

1. 调用 view 、pure 标记函数

        // API地址
        Cfx cfx = Cfx.create("https://test.confluxrpc.org/v2", 3, 1000);
        // 与合约建立连接
        ContractCall contract = new ContractCall(cfx, new Address("cfxtest:acdhpa29xz0095w6rxbhv36yhjeub58vzp64s0swpk"));

        {
            // 单参数返回
            String balance = contract.call("balanceOf", new Address("cfxtest:aasg762e552jwmp3pk73ve9j9tszezz9xu5abab3xb").getABIAddress()).sendAndGet();
            BigInteger outBalance = DecodeUtil.decode(balance, Uint256.class);
            System.out.println("contract minter: " + outBalance);
        }


        {
            // 动态参数返回
            String test = contract.call("tokens", new Uint256(0), new Uint256(11)).sendAndGet();
            List values = FunctionReturnDecoder.decode(test, Utils.convert(Arrays.asList(new TypeReference() {}, new TypeReference>() {})));
            System.out.println("tokens 0 : " + (values.get(0)).getValue());
            List list = (List)values.get(1).getValue();
            for( Uint256 v : list) {
                System.out.println("tokens array : " + v.getValue());
            }
        }

        {
            // 多返回参数
            String test = contract.call("Test").sendAndGet();
            List values = FunctionReturnDecoder.decode(test, Utils.convert(Arrays.asList(new TypeReference() {}, new TypeReference() {} )));
            System.out.println((values.get(0)).getValue());
            System.out.println((values.get(1)).getValue());
        }

2. 调用普通公开逻辑函数

        // 调用者私钥
        String privateKey = "0x私钥";
        // 合约地址
        Address contractAddress = new Address("cfxtest:accb2fg8f6n9c92hszej0x1u88mprtbdhpp69v74a9");
        // 调用者地址
        Address recipient = new Address("cfxtest:aatc1wrjhetj6bnggdkhwd6hhybecrmpj228968j27");
        // API地址
        Cfx cfx = Cfx.create("https://test.confluxrpc.org/v2", 3, 1000);

        // 创建调用账户
        Account account = Account.create(cfx, privateKey);
        // 设置调用设置
        Account.Option opt = new Account.Option();
        // 调用测试链
        opt.withChainId(1);
        
        // 发起合约
        try
        {
            // 发起合约
            String txHash = account.call(opt, contractAddress, "DT_GenerateNFT", recipient.getABIAddress());

            // 返回64位开头0x8的哈希交易地址, 具体内容可以在 https://testnet.confluxscan.io/ 输入返回哈希搜到
            System.out.println("tx hash: " + txHash);
        }
        catch (Exception e)
        {
            // 调用失败
            System.out.println(e.getMessage());
        }

3. 获取交易信息返回值 - 函数返回较慢

    // 订单转换
    private static Call convert(Transaction tx) {

        Call call = new Call();
        call.setFrom(tx.getFrom());
        call.setNonce(tx.getNonce());
        if (tx.getTo().isPresent()) {
            call.setTo(tx.getTo().get());
        }
        call.setValue(tx.getValue());
        call.setGasPrice(tx.getGasPrice());
        call.setGas(tx.getGas());
        call.setData(tx.getData());
        call.setStorageLimit(tx.getStorageLimit());
        return call;
    }

    // 获取交易信息返回值 - 函数返回较慢
    private static String getTXHashReturnValue(Cfx cfx, String txHash) throws Exception {

        Transaction tx = cfx.getTransactionByHash(txHash).sendAndGet().get();
        Receipt receipt = cfx.waitForReceipt(txHash);

        Call call = App.convert(tx);
        BigInteger execEpoch = receipt.getEpochNumber().subtract(BigInteger.ONE);
        StringResponse response = (StringResponse)cfx.call(call, new Epoch[] { Epoch.numberOf(execEpoch) }).sendWithRetry();
        if (response.getError() != null)
        {
            throw new Exception(DecodeUtil.decodeErrorData(response.getError().getData()));
        }
        return response.getValue();
    }

4. 新建地址

        Cfx cfx = Cfx.create("https://test.confluxrpc.org/v2", 3, 1000);
        BigInteger epoch = cfx.getEpochNumber().sendAndGet();
        System.out.println("Current epoch: " + epoch);
        AccountManager accountManager = new AccountManager(1);

        String path = "d:\\2";
        Bip39Wallet wallet = WalletUtils.generateBip39Wallet("1234567678",new File(path));
        System.out.println("助"+wallet.getMnemonic());
        // 使用密码和助记词让账户解锁
        Credentials credentials = WalletUtils.loadBip39Credentials("", wallet.getMnemonic());
        // 获取账户地址
        String address1 = credentials.getAddress();
        System.out.println(address1);
        // 获取公钥
        String publicKey = credentials.getEcKeyPair().getPublicKey().toString(16);
        System.out.println("公"+publicKey);
        // 获取私钥
        String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);
        System.out.println("私"+privateKey);
        // 获取地址
        Optional
c = accountManager.imports(privateKey,"12345678"); System.out.println(c.get().getAddress());

你可能感兴趣的:(Java,智能合约)