版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sail331x/article/details/112972860
由于在项目中需要,我们又为了节省服务器资源,决定不同步节点数据。也就说说,很多的一些API,我们是不能直接用的了,最直接的有创建地址、签名交易等等
TronUtils.java
/**
* 离线创建地址
*
* @return
*/
public static Map<String, String> createAddress() {
ECKey eCkey = new ECKey(random);
String privateKey = ByteArray.toHexString(eCkey.getPrivKeyBytes());
byte[] addressBytes = eCkey.getAddress();
String hexAddress = ByteArray.toHexString(addressBytes);
Map<String, String> addressInfo = new HashMap<>();
addressInfo.put("address", toViewAddress(hexAddress));
addressInfo.put("hexAddress", hexAddress);
addressInfo.put("privateKey", privateKey);
return addressInfo;
}
离线签名并广播交易
/**
* 广播交易信息 返回交易id
* @param tronUrl
* @param transaction
* @return
*/
public static String signAndBroadcast(String tronUrl,String privateKey,JSONObject transaction)throws Throwable{
if(tronUrl.endsWith("/")){
tronUrl= tronUrl.substring(0,tronUrl.length() - 1);
}
Protocol.Transaction tx = packTransaction(transaction.toJSONString());
byte[] bytes = signTransactionByte(tx.toByteArray(), ByteArray.fromHexString(privateKey));
String signTransation = Hex.toHexString(bytes);
JSONObject jsonObjectGB = new JSONObject();
jsonObjectGB.put("transaction", signTransation);
String url = tronUrl + "/wallet/broadcasthex";
String transationCompelet1 = HttpClientUtils.postJson(url, jsonObjectGB.toString());
JSONObject transationCompelet = JSONObject.parseObject(transationCompelet1);
if (transationCompelet.getBoolean("result")) {
return transationCompelet.getString("txid");
} else {
logger.error(String.format("签名交易失败:%s",transationCompelet1));
return null;
}
}
a、trx额度查询 (TrxTest.java)
/**
* 查询额度
*/
@Test
public void balanceOf() throws Throwable {
String queryAddress = "TA1gLs6FS8eik5NJqjvm73L4qRqWDmLwmh";
String url = tronUrl + "/wallet/getaccount";
JSONObject param = new JSONObject();
param.put("address", TronUtils.toHexAddress(queryAddress));
String result = HttpClientUtils.postJson(url, param.toJSONString());
BigInteger balance = BigInteger.ZERO;
if (!StringUtils.isEmpty(result)) {
JSONObject obj = JSONObject.parseObject(result);
BigInteger b = obj.getBigInteger("balance");
if(b != null){
balance = b;
}
}
System.out.println("trx:"+new BigDecimal(balance).divide(decimal,6, RoundingMode.FLOOR));
}
b、trc20额度查询(Trc20Test.java)
/**
* 查询trc20数量
*/
@Test
public void balanceOfTrc20()throws Throwable{
String queryAddress = "TDzVKgBF9WSFox22qbdm7YYec9NjaXUrrr";
String url = tronUrl + "/wallet/triggerconstantcontract";
JSONObject param = new JSONObject();
param.put("owner_address",TronUtils.toHexAddress(queryAddress));
param.put("contract_address",TronUtils.toHexAddress(contract));
param.put("function_selector","balanceOf(address)");
List<Type> inputParameters = new ArrayList<>();
inputParameters.add(new Address(TronUtils.toHexAddress(queryAddress).substring(2)));
param.put("parameter",FunctionEncoder.encodeConstructor(inputParameters));
String result = HttpClientUtils.postJson(url, param.toJSONString());
BigDecimal amount = BigDecimal.ZERO;
if(StringUtils.isNotEmpty(result)){
JSONObject obj = JSONObject.parseObject(result);
JSONArray results = obj.getJSONArray("constant_result");
if(results != null && results.size() > 0){
BigInteger _amount = new BigInteger(results.getString(0),16);
amount = new BigDecimal(_amount).divide(decimal,6, RoundingMode.FLOOR);
}
}
System.out.println(String.format("账号%s的balance=%s",queryAddress,amount.toString()));
}
/**
* 转账
*/
@Test
public void sendTrx() throws Throwable {
BigDecimal trxAmount = new BigDecimal("0.5");
String privateKey = "7a2195d52c42c34a8de11633de7fdfbbf6883d2e95918ccd845230629fd95768";
String toAddress = "TDzVKgBF9WSFox22qbdm7YYec9NjaXUrrr";
String url = tronUrl + "/wallet/createtransaction";
JSONObject param = new JSONObject();
param.put("owner_address",TronUtils.toHexAddress(TronUtils.getAddressByPrivateKey(privateKey)));
param.put("to_address",TronUtils.toHexAddress(toAddress));
param.put("amount",trxAmount.multiply(decimal).toBigInteger());
String _result = HttpClientUtils.postJson(url, param.toJSONString());
String txid = null;//交易id
if(StringUtils.isNotEmpty(_result)){
JSONObject transaction = JSONObject.parseObject(_result);
transaction.getJSONObject("raw_data").put("data", Hex.toHexString("这里是备注信息".getBytes()));
txid = TronUtils.signAndBroadcast(tronUrl, privateKey, transaction);
System.out.println(txid);
}
}
/**
* 发起trc20转账
* @throws Throwable
*/
@Test
public void sendTrc20() throws Throwable {
String privateKey = "7a2195d52c42c34a8de11633de7fdfbbf6883d2e95918ccd845230629fd95768";
String toAddress = "TDzVKgBF9WSFox22qbdm7YYec9NjaXUrrr";
BigDecimal amount = new BigDecimal("0.01");
String ownerAddress = TronUtils.getAddressByPrivateKey(privateKey);
JSONObject jsonObject = new JSONObject();
jsonObject.put("contract_address", TronUtils.toHexAddress(contract));
jsonObject.put("function_selector", "transfer(address,uint256)");
List<Type> inputParameters = new ArrayList<>();
inputParameters.add(new Address(TronUtils.toHexAddress(toAddress).substring(2)));
inputParameters.add(new Uint256(amount.multiply(decimal).toBigInteger()));
String parameter = FunctionEncoder.encodeConstructor(inputParameters);
jsonObject.put("parameter", parameter);
jsonObject.put("owner_address", TronUtils.toHexAddress(ownerAddress));
jsonObject.put("call_value", 0);
jsonObject.put("fee_limit", 6000000L);
String trans1 = HttpClientUtils.postJson(tronUrl + "/wallet/triggersmartcontract", jsonObject.toString());
JSONObject result = JSONObject.parseObject(trans1);
if (result.containsKey("Error")) {
System.out.println("send error==========");
return;
}
JSONObject tx = result.getJSONObject("transaction");
tx.getJSONObject("raw_data").put("data", Hex.toHexString("我是Tricky".getBytes()));//填写备注
String txid = TronUtils.signAndBroadcast(tronUrl, privateKey, tx);
if (txid != null) {
System.out.println("交易Id:" + txid);
}
}
注意一定要看readme.md文件,否则你发现坑就有点难以解决了。
如果需要合约/DApp/钱包/游戏/商城/官网开发,可以联系wx: zhongxh886
附带项目地址:
https://github.com/StivenZhong/tron-sdk.git