区块链之java调用智能合约(四) 合约交易

区块链之java调用智能合约(四) 合约交易,第1张

前言

前面我们把准备工作都做好了。现在我们看看具体的实现。

对于java人员来说,这里说成是“方法调动”,或者”api接口”请求会更好理解,或者更贴切。

对于区块链人员,他们称之为“交易”。

正文

第一步。我们需要创建一个以太坊的连接。

第二步。我们需要连接钱包

第三步。引用合约。

第四步。发起交易

第五步。检测交易

private static String netWorkUrl = "https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161";//测试链地址
    private static String credentialsAddress = "钱包地址";//钱包地址
    private static String contractAddress = "合约地址";//合约地址


    public static void useContract(){
        try {
            //连接对应的以太坊
            Web3j web3 = Web3j.build(new HttpService(netWorkUrl));
            Credentials credentials = Credentials.create(credentialsAddress);
            TransactionManager transactionManager = new RawTransactionManager(
                    web3, credentials,3);
            BigInteger gasPrice = web3.ethGasPrice().send().getGasPrice();
            Storage contract = Storage.load(contractAddress,web3,
                    transactionManager,new StaticGasProvider(gasPrice, Contract.GAS_LIMIT));
            //测试store方法
            RemoteCall setWord = contract.store(new BigInteger("1"));
            TransactionReceipt transactionReceipt = setWord.send();
            String transactionHash = transactionReceipt.getTransactionHash();
            System.out.println(transactionHash);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

我们在测试完store后,可以在remix ide中,检查我们是否成功完成交易。

比如:

在remix中,获取到我们写入的值,就表示这个交易是成功的。

其中,需要注意的地方有几点。

1.初步使用测试链*-时候,会出现测试代币不足问题。(获取测试代币) 

(Error: insufficient funds for gas * price + value)

 2.有测试代币,而且全部能正常连接。还是无法交易完成。出现如下图所示错误。

(Error: only replay-protected (EIP-155) transactions allowed over RPC)

表示没有在调用交易的时候指定节点。

只需要在调用合约前加入。

long chainId = 3;
TransactionManager transactionManager = new RawTransactionManager(web3, credentials,chainId);

然后调用合约

Storage contract = Storage.load(contractAddress,web3,
                    transactionManager,new StaticGasProvider(gasPrice, Contract.GAS_LIMIT));

钱包地址可以是。钱包的地址,钱包的私钥,钱包的加密文件。

3.当关闭当前内存浏览器时,部署的合约也会销毁。这时候容易出现调用合约错误。。

需要重新生成sol文件的abi与bin文件。重新生成java类

代码地址:link-sol: 智能合约

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/918371.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存