一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第11天,点击查看活动详情。
目录
在中文版的remix 中 合约地址中输入地址,再部署可以实现调用
Unmatched arguments from index 2
web3j : 无法将“web3j”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
java调用智能合约
综述:
网络上使用remix编写智能合约,得到合约地址,在本地或者公链部署;
下载ABI和BIN 在本地使用web3j将其转化为java
在本地开启区块链:ganache,得到私钥和账户地址
调java用智能合约
在英文版的remix部署,拿到部署地址
在中文版的remix 中 合约地址中输入地址,再部署可以实现调用
使用交互工具进行外部测试智能合约
java调用智能合约
注意是web provide,链接自己本地的账户或者
链接主链上的和账户。
package eth;
import org.web3j.crypto.ContractUtils;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.RemoteCall;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.Contract;
import org.web3j.tx.Transfer;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Convert;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
public class App
{
public static void main( String[] args )
{
try {
//连接以太坊客户端节点,可以是ganache,geth等,注意地址端口和RPC协议(ws ,http)
// Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545"));
// //获取客户端版本号,通常用来判断是否连接上
// Web3ClientVersion web3clientversion = web3j.web3ClientVersion().send();
// String clientVersion = web3clientversion.getWeb3ClientVersion();
// System.out.println("web3clientVersion : " + clientVersion);
// //获取节点上所有的账户,在ganache中,每个账户有100ETH,允许你用上面用户交易
// //注意绝大多数以太坊客户端节点不会允许你用它上面的账户交易,你要自己创建钱包(见后面的Cpp类main函数)
// List<String> addressList = web3j.ethAccounts().send().getAccounts();
// System.out.println("addressList : "+addressList);
// //交易前,获取前两个账户余额
// BigInteger balance0 = web3j.ethGetBalance(addressList.get(0), DefaultBlockParameterName.LATEST).send().getBalance();
// BigInteger balance1 = web3j.ethGetBalance(addressList.get(1), DefaultBlockParameterName.LATEST).send().getBalance();
// System.out.println("before Transaction:");
// System.out.println("balance0 : " + addressList.get(0) + " : " + balance0);
// System.out.println("balance1 : " + addressList.get(1) + " : " + balance1);
//
// //生成交易,参数包括谁发送,发给谁,发多少,给矿工的小费等等,由于ganache允许我们操作它上面的账户,所以不用签名。
// BigInteger mynounce = web3j.ethGetTransactionCount(addressList.get(0), DefaultBlockParameterName.LATEST).send().getTransactionCount();
// BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
// BigInteger gasLimit = BigInteger.valueOf(21000);
// BigInteger value = Convert.toWei(BigDecimal.valueOf(0.5), Convert.Unit.ETHER).toBigInteger() ;
// Transaction mytesttransaction= Transaction.createEtherTransaction(addressList.get(0),mynounce, gasPrice, gasLimit, addressList.get(1),value);
// System.out.println("mytesttransaction : ");
// printTransaction(mytesttransaction);
// //发送交易,获取交易哈希
// String txhash = web3j.ethSendTransaction(mytesttransaction).send().getTransactionHash();
// System.out.println("txhash : " + txhash);
// //交易对应的收据,这个对于智能合约交易非常有用,对普通交易没多大用
// TransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(txhash).send().getTransactionReceipt().get();
// System.out.println("transactionReceipt : " + transactionReceipt);
//
// //交易后的余额
// balance0 = web3j.ethGetBalance(addressList.get(0), DefaultBlockParameterName.LATEST).send().getBalance();
// balance1 = web3j.ethGetBalance(addressList.get(1), DefaultBlockParameterName.LATEST).send().getBalance();
// System.out.println("after Transaction:");
// System.out.println("balance0 : " + addressList.get(0) + " : " + balance0);
// System.out.println("balance1 : " + addressList.get(1) + " : " + balance1);
//
// //获取当前最新区块,并获取它上面的所有交易
// EthBlock.Block latestBlock = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
// System.out.println("latestBlock: " + latestBlock.getHash());
// //获取区块上的所有交易
// List<EthBlock.TransactionResult> txlist = latestBlock.getTransactions();
// System.out.println("get TransactionBy Block :" );
// for (EthBlock.TransactionResult transactionResult : txlist) {
// System.out.println(transactionResult.get());
// }
// System.out.println("===============");
// printTransaction(mytesttransaction);
// System.out.println("===============");
Web3j web3 = Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
Credentials credentials = Credentials.create("f6b3f11ac120b04581d0273faeacbed5be08f4a0cdc3ddb82ed522f9a344b350");
Storage awToken = Storage.load("0x57d53E1fE5847F50A1e5Fa42FA15806f87b5213D",web3, credentials, web3.ethGasPrice().send().getGasPrice(), Contract.GAS_LIMIT);
System.out.println(awToken.getContractAddress());
// 调用合约的函数
awToken.store(1).send();
BigInteger bigInteger=awToken.retrieve().send();
System.out.println("zjq:"+String.valueOf(bigInteger));
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
public static BigInteger getPrice(Web3j web3j) throws Exception{
EthGasPrice send = web3j.ethGasPrice().send();
BigInteger gasPrice = send.getGasPrice();
return gasPrice;
}
public static void printTransaction(Transaction x) {
//打印交易信息
System.out.println("From:"+x.getFrom());
System.out.println("GasLimit:"+x.getGas());
System.out.println("Nonce:"+x.getNonce());
System.out.println("GasPrice:"+x.getGasPrice());
System.out.println("To:"+x.getTo());
System.out.println("Value:"+x.getValue());
}
}
class Cpp {
public static void main(String[] args) {
try {
Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545"));
//通常情况下,以太坊节点是不会让其他人用它上面的账户,我们要自己创建钱包,用自己的私钥对交易签名,
//下面的私钥是ganache上第一个账户的私钥,虽然交易发起者和上面的交易一样,但两者本质是不同的。
Credentials mysigner = Credentials.create("f6b3f11ac120b04581d0273faeacbed5be08f4a0cdc3ddb82ed522f9a344b350");
List<String> addressList = web3j.ethAccounts().send().getAccounts();
String txhash = Transfer.sendFunds(web3j, mysigner, addressList.get(1), BigDecimal.valueOf(1.0), Convert.Unit.ETHER).send().getTransactionHash();
System.out.println("txhash:"+txhash);
TransactionReceipt receipt = web3j.ethGetTransactionReceipt(txhash).send().getTransactionReceipt().get();
System.out.println(receipt);
} catch (Exception e) {
e.printStackTrace();
}
}
}
核心代码
Web3j web3 = Web3j.build(new HttpService("HTTP://127.0.0.1:7545"));
Credentials credentials = Credentials.create("f6b3f11ac120b04581d0273faeacbed5be08f4a0cdc3ddb82ed522f9a344b350");
Storage awToken = Storage.load("0x57d53E1fE5847F50A1e5Fa42FA15806f87b5213D",web3, credentials, web3.ethGasPrice().send().getGasPrice(), Contract.GAS_LIMIT);
System.out.println(awToken.getContractAddress());
java 获取区块链信息
// 连接以太坊客户端节点,可以是ganache,geth等,注意地址端口和RPC协议(ws ,http)
Web3j web3j = Web3j.build(new HttpService("http://127.0.0.1:7545"));
//获取客户端版本号,通常用来判断是否连接上
Web3ClientVersion web3clientversion = web3j.web3ClientVersion().send();
String clientVersion = web3clientversion.getWeb3ClientVersion();
System.out.println("web3clientVersion : " + clientVersion);
//获取节点上所有的账户,在ganache中,每个账户有100ETH,允许你用上面用户交易
//注意绝大多数以太坊客户端节点不会允许你用它上面的账户交易,你要自己创建钱包(见后面的Cpp类main函数)
List<String> addressList = web3j.ethAccounts().send().getAccounts();
System.out.println("addressList : "+addressList);
//交易前,获取前两个账户余额
BigInteger balance0 = web3j.ethGetBalance(addressList.get(0), DefaultBlockParameterName.LATEST).send().getBalance();
BigInteger balance1 = web3j.ethGetBalance(addressList.get(1), DefaultBlockParameterName.LATEST).send().getBalance();
System.out.println("before Transaction:");
System.out.println("balance0 : " + addressList.get(0) + " : " + balance0);
System.out.println("balance1 : " + addressList.get(1) + " : " + balance1);
//生成交易,参数包括谁发送,发给谁,发多少,给矿工的小费等等,由于ganache允许我们操作它上面的账户,所以不用签名。
BigInteger mynounce = web3j.ethGetTransactionCount(addressList.get(0), DefaultBlockParameterName.LATEST).send().getTransactionCount();
BigInteger gasPrice = web3j.ethGasPrice().send().getGasPrice();
BigInteger gasLimit = BigInteger.valueOf(21000);
BigInteger value = Convert.toWei(BigDecimal.valueOf(0.5), Convert.Unit.ETHER).toBigInteger() ;
Transaction mytesttransaction= Transaction.createEtherTransaction(addressList.get(0),mynounce, gasPrice, gasLimit, addressList.get(1),value);
System.out.println("mytesttransaction : ");
printTransaction(mytesttransaction);
//发送交易,获取交易哈希
String txhash = web3j.ethSendTransaction(mytesttransaction).send().getTransactionHash();
System.out.println("txhash : " + txhash);
//交易对应的收据,这个对于智能合约交易非常有用,对普通交易没多大用
TransactionReceipt transactionReceipt = web3j.ethGetTransactionReceipt(txhash).send().getTransactionReceipt().get();
System.out.println("transactionReceipt : " + transactionReceipt);
//交易后的余额
balance0 = web3j.ethGetBalance(addressList.get(0), DefaultBlockParameterName.LATEST).send().getBalance();
balance1 = web3j.ethGetBalance(addressList.get(1), DefaultBlockParameterName.LATEST).send().getBalance();
System.out.println("after Transaction:");
System.out.println("balance0 : " + addressList.get(0) + " : " + balance0);
System.out.println("balance1 : " + addressList.get(1) + " : " + balance1);
//获取当前最新区块,并获取它上面的所有交易
EthBlock.Block latestBlock = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, false).send().getBlock();
System.out.println("latestBlock: " + latestBlock.getHash());
//获取区块上的所有交易
List<EthBlock.TransactionResult> txlist = latestBlock.getTransactions();
System.out.println("get TransactionBy Block :" );
for (EthBlock.TransactionResult transactionResult : txlist) {
System.out.println(transactionResult.get());
}
System.out.println("===============");
printTransaction(mytesttransaction);
System.out.println("===============");
Unmatched arguments from index 2
就是生成代码的命令行有问题,仔细看看我的,注意官方文档
Deploy and Interact with Smart Contracts - Web3j
中文remix实现本地文件上传
点击链接进行配置,带点击文件的图表技能打开本地
Web3j官方文档,web3j生成java代码
web3j generate solidity -a=C:\web3j\bin\Storage.abi -b=C:\web3j\bin\Storage.bin -o=C:\web3j -p=zjqok
-b:bin文件的目录
-a:abi文件的目录
-o=C:\web3j:生成的java文件的输出目录
-p=zjqok:生成的java文件的包名
Deploy and Interact with Smart Contracts - Web3j
web3j : 无法将“web3j”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
用cmd 命令窗口,不用powershell
输入行太长 命令语法不正确
这时我反应过来,我的目录深度很大,直接在c盘根目录
利用Java 调用智能合约接口
连接以太坊网络
Web3j web3j = Web3j.build(new HttpService("以太坊节点地址"));
创建凭证
Credentials credentials = WalletUtils.loadCredentials("密码","Keystore文件地址");
获取当前gasPrice
public BigInteger getPrice(Web3j web3j) throws Exception{
EthGasPrice send = web3j.ethGasPrice().send();
BigInteger gasPrice = send.getGasPrice();
return gasPrice;
}
初始化合约
String contractAddress = "合约地址";
BigInteger gasPrice = getPrice(Web3j web3j);
BigInteger gasLimit = BigInteger.valueOf(80_000);
Contract erc20 = Contract.load(contractAddress, web3j, credentials, gasPrice, gasLimit );
注:这里GasLimit 设置为默认10KWei ,GasPrice 获取当前链上实时的GasPrice
调用合约方法:获取账户代币数量
RemoteCall<BigInteger> balanceOf = erc20.balanceOf("以太坊账户地址");
CompletableFuture<BigInteger> sendAsync = balanceOf.sendAsync();
System.out.println(sendAsync.get());
注:合约方法提供了send 同步方法和 sendAsync 异步方法 可根据具体需要选择
调用合约转账方法
BigInteger price = BigInteger.valueOf(10_000_000);
String to = "转到的账户地址";
RemoteCall<TransactionReceipt> transfer = erc20.transfer(to , price);
CompletableFuture<TransactionReceipt> sendAsync = transfer.sendAsync();
TransactionReceipt transactionReceipt = sendAsync.get();//返回交易信息
\