表现效果
测试用例 EthTestData.java
/**
* 测试数据
*
* @Autor Tricky
* @Date 2021-04-01 22:06:36
*/
public class EthTestData {
// {"address":"0xe81128942ed67a3b453576cad44fa9fb7f0b2098","privateKey":"8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214"}
private String privateKey="8ca3edaabc0567d9555ade455bab24a27bea6ee0524e96ffac9a3cfc2b841214";
private String myAddress = "0x6B488606b33a254734F17797Ab42fc03C8c3Ce73";
//rinkeby上面的测试币 erc20-usdt同款
private String contract="0xf805ed280cadeadc2aa135808688e06fef5a9b71";
private Web3j web3j ;
{
try{
//如果这个地址不知道怎么获取 可以参考 https://blog.csdn.net/sail331x/article/details/115395131
web3j = Web3j.build(new HttpService("https://rinkeby.infura.io/v3/dddddddddda74486b59041e5d83f4af1"));
}catch (Throwable t){
t.printStackTrace();
}
}
/**
* 创建地址
*/
@Test
public void createAddress(){
System.out.println("创建地址:"+JSONUtil.toJsonStr(EthUtils.createAddress()));
}
/**
* 查询eth数量
*/
@Test
public void balanceOf(){
System.out.println("查询ETH:"+EthUtils.balanceOf(web3j,myAddress));
}
/**
* 查询ERC20数量
*/
@Test
public void balanceOfErc20(){
System.out.println("查询ERC20:"+EthUtils.balanceOfErc20(web3j,contract,myAddress));
}
/**
* 发送ERC20
*/
@Test
public void sendErc20(){
String txid = EthUtils.sendErc20(web3j, contract, privateKey, myAddress, BigInteger.valueOf(10000000));
System.out.println("发送ERC20:"+txid);
}
/**
* 发送以太坊
*/
@Test
public void sendEth(){
String txid = EthUtils.sendEth(web3j, privateKey, myAddress, new BigDecimal("0.001"));
System.out.println("发送ETH:"+txid);
}
@Test
public void getTransaction(){
//合约
String txid="0x29d96b351be4ab1c29912a1c26c1c8f9205fc35fb9ea2395c53c5c2e1884c421";
//eth
String txid2="0xef3c06f56085187d6a43edec2bb399a7fe98572aad63bcd5bd80e5e5dab153b3";
EthTransaction tx = EthUtils.getTransaction(web3j, txid2);
System.out.println("查询交易:"+JSONUtil.toJsonStr(tx));
}
}
运行结果
工具类
EthUtils.java工具类
/**
* 以太坊工具类
*
* @Autor Tricky
* @Date 2021-04-01 21:02:11
*/
@Slf4j
public class EthUtils {
public static final BigDecimal ETH_DECIMALS = new BigDecimal(1_000_000_000_000_000_000L);
public static final BigInteger ETH_GAS_LIMIT = new BigInteger("100000");
/**
* 获取区块数据
*
* @param web3j
* @param block 块高
* @param fullTransactionObjects 是否需要交易数据
* @return
*/
public static EthBlock getBlock(Web3j web3j, long block, boolean fullTransactionObjects) {
try {
return web3j.ethGetBlockByNumber(new DefaultBlockParameterNumber(block), fullTransactionObjects).send();
} catch (Throwable t) {
logger.error(String.format("Get Block Error %d", block), t