YSTron.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import 'dart:math';
  2. import 'package:bs58check/bs58check.dart' as bs58check;
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:flutter_wallet/tools/YSAes.dart';
  6. import 'package:flutter_wallet/tools/YSNetWork.dart';
  7. import 'package:flutter_wallet/tools/YSSqflite.dart';
  8. import 'package:flutter_wallet/tools/YSTools.dart';
  9. import 'package:hex/hex.dart';
  10. import 'dart:convert';
  11. import 'package:http/http.dart' as http;
  12. import 'package:web3dart/web3dart.dart';
  13. class YSTron{
  14. static String changeAddress(String str) {
  15. var bytes = bs58check.base58.decode(str);
  16. String value = HEX.encode(bytes.sublist(0, bytes.length - 4));
  17. // LogUtil.d('changeAddress======$value');
  18. return value;
  19. }
  20. static getBalance(String str) async{
  21. String address = changeAddress(str);
  22. var yourQuickNodeRpcUrl = YSData().rpc;
  23. var headers = {
  24. 'Content-Type': 'application/json',
  25. };
  26. var body = jsonEncode({
  27. "jsonrpc": "2.0",
  28. "id": 1,
  29. "method": "eth_getBalance",
  30. "params": [address, "latest"]
  31. });
  32. var response = await http.post(
  33. Uri.parse(yourQuickNodeRpcUrl),
  34. headers: headers,
  35. body: body,
  36. );
  37. if (response.statusCode == 200) {
  38. var result = jsonDecode(response.body);
  39. String resultStr = '${result['result']}';
  40. var balance = int.parse(resultStr.replaceAll('0x', ''), radix: 16);
  41. String balanceStr = '${balance/pow(10, 6)}';
  42. LogUtil.d('TRON============$balanceStr');
  43. return balanceStr;
  44. }
  45. }
  46. static Future<String> transferData(BuildContext context,{required String from,required String to,required String private,required String amount}) async{
  47. // 创建一个新的HTTP客户端
  48. var client = http.Client();
  49. try {
  50. // 构建请求URL
  51. var url = Uri.parse('https://api.trongrid.io/wallet/createtransaction');
  52. // LogUtil.d('transferData3========$amount');
  53. // 构建请求参数
  54. var body = jsonEncode({
  55. 'to_address': to, // 替换为接收者的地址
  56. 'owner_address': from, // 替换为你的地址
  57. 'amount': int.parse('${(double.parse(amount)*pow(10, 6))~/1}'), // 转账金额(单位:TRX)
  58. "visible": true
  59. });
  60. LogUtil.d('transferData3=======1$body');
  61. YSFileWriteRead().writeContent(body.toString());
  62. // 发送POST请求
  63. var response = await client.post(
  64. url,
  65. headers: {'Content-Type': 'application/json','TRON-PRO-API-KEY' : '6c8142d8-877d-474d-9a8c-60a533493c9f','accept': 'application/json'},
  66. body: body,
  67. );
  68. // 解析响应结果
  69. var result = jsonDecode(response.body);
  70. LogUtil.d('transferData3============$result');
  71. YSFileWriteRead().writeContent(result.toString());
  72. Map request = {};
  73. request['tx'] = result;
  74. String privateS = YSAes.aesEncode3('${private}_${DateTime.now().microsecond}');
  75. request['prikey'] = privateS;
  76. // ignore: use_build_context_synchronously
  77. Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tronsign', parameter: request);
  78. if(dict.isNotEmpty){
  79. // return false;
  80. Map data = dict['data'];
  81. result['signature'] = data['signature'];
  82. // 广播交易
  83. url = Uri.parse('https://api.trongrid.io/wallet/broadcasttransaction');
  84. LogUtil.d('transferData3============$result');
  85. YSFileWriteRead().writeContent(result.toString());
  86. response = await client.post(
  87. url,
  88. headers: {'Content-Type': 'application/json'},
  89. body: jsonEncode(result),
  90. );
  91. // LogUtil.d('TRON============Transaction ID $result');
  92. // return;
  93. // 解析响应结果
  94. result = jsonDecode(response.body);
  95. LogUtil.d('transferData3============4${result['txid']}');
  96. YSFileWriteRead().writeContent(result.toString());
  97. if(result['result']==true){
  98. return result['txid']??'';
  99. }else{
  100. return '';
  101. }
  102. }else{
  103. return '';
  104. }
  105. } finally {
  106. // 关闭HTTP客户端
  107. client.close();
  108. }
  109. }
  110. static Future<String> transferContractData(BuildContext context,{
  111. required String from,
  112. required String to,
  113. required String private,
  114. required String amount,
  115. required String tokenId,
  116. required String tokenAddress
  117. }) async{
  118. var client = http.Client();
  119. try {
  120. LogUtil.d('transferData3========');
  121. Map result = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'createtransfer', parameter: {
  122. 'contractAddress':tokenAddress,
  123. 'ownerAddress':from,
  124. 'toAddress':to,
  125. 'amount':int.parse('${(double.parse(amount)*pow(10, 6))~/1}')
  126. });
  127. if(result.isNotEmpty){
  128. Map data = result['data']??{};
  129. if(data.isNotEmpty){
  130. Map request = {};
  131. request['tx'] = data;
  132. String privateS = YSAes.aesEncode3('${private}_${DateTime.now().microsecond}');
  133. request['prikey'] = privateS;
  134. // ignore: use_build_context_synchronously
  135. Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tronsign', parameter: request);
  136. if(dict.isNotEmpty){
  137. // return '';
  138. Map data2 = dict['data'];
  139. data['signature'] = data2['signature'];
  140. // 广播交易
  141. var url = Uri.parse('https://api.trongrid.io/wallet/broadcasttransaction');
  142. LogUtil.d('transferData3=======$data');
  143. var response = await client.post(
  144. url,
  145. headers: {'Content-Type': 'application/json'},
  146. body: jsonEncode(data),
  147. );
  148. result = jsonDecode(response.body);
  149. LogUtil.d('transferData3============${response.body}');
  150. if(result['result']==true){
  151. return '${result['txid']??''}';
  152. }else{
  153. return '';
  154. }
  155. }else{
  156. return '';
  157. }
  158. }
  159. }
  160. return '';
  161. } finally {
  162. // 关闭HTTP客户端
  163. client.close();
  164. }
  165. }
  166. static Future<String> approveContractData(BuildContext context,{
  167. required String from,
  168. required String to,
  169. required String private,
  170. required String amount,
  171. required String fromTokenAddress,
  172. required String toTokenAddress
  173. }) async{
  174. var client = http.Client();
  175. try {
  176. // YSTronTable ysTronTable = YSTronTable().init();
  177. // ysTronTable.rawInsert(from_addr: from, to_addr: to, from_token_addr: fromTokenAddress,
  178. // to_token_addr: toTokenAddress, amount: '100', hash: 'result3Data');
  179. // return '';
  180. LogUtil.d('transferData3========');
  181. int amountValue = double.parse(amount)~/1;
  182. String privateS = YSAes.aesEncode3('${private}_${DateTime.now().microsecond}');
  183. Map result = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/myres', parameter: {
  184. 'owner_address': from,
  185. });
  186. if(result.isNotEmpty){
  187. Map resultData = result['data'];
  188. int network_rate = resultData['network_rate'];
  189. int rest_energy = resultData['rest_energy'];
  190. // return '';
  191. // ignore: use_build_context_synchronously
  192. Map result2 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/query/approve', parameter: {
  193. "amount":amountValue,
  194. "from_token":fromTokenAddress,
  195. "owner_address":from
  196. });
  197. if(result2.isNotEmpty){
  198. int result2Data = result2['data'];
  199. // ignore: use_build_context_synchronously
  200. Map result3 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/approve/start', parameter: {
  201. "prikey":privateS,
  202. "amount":amountValue,
  203. "from_token":fromTokenAddress,
  204. 'limit':(result2Data*network_rate*1.1)~/1
  205. });
  206. if(result3.isNotEmpty){
  207. String result3Data = result3['data']??'';
  208. YSTronTable ysTronTable = YSTronTable().init();
  209. ysTronTable.rawInsert(from_addr: from, to_addr: to, from_token_addr: fromTokenAddress,to_token_addr: toTokenAddress, amount: '$amountValue', hash: result3Data);
  210. return result3Data;
  211. // return result3Data;
  212. // ignore: use_build_context_synchronously
  213. // Map result4 = await YSNetWork.ysRequestHttpNOSet2(context, type: RequestType.post, api: 'tron/approve/check', parameter: {
  214. // "hash":result3Data,
  215. // });
  216. // if(result4.isNotEmpty){
  217. // Map result4Data = result4['data']??{};
  218. // if(result4Data.isNotEmpty){
  219. // // ignore: use_build_context_synchronously
  220. // Map result5 = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tron/query/swap', parameter: {
  221. // "amount":amountValue //转账金额 要和授权的保持一致
  222. // ,"from_token":fromTokenAddress //转出token
  223. // ,"to_token":toTokenAddress //转入token
  224. // ,"owner_address":from //钱包地址
  225. // });
  226. // if(result5.isNotEmpty){
  227. //
  228. // }
  229. // }
  230. // }
  231. }
  232. }
  233. }
  234. return '';
  235. if(result.isNotEmpty){
  236. Map data = result['data']??{};
  237. if(data.isNotEmpty){
  238. Map request = {};
  239. request['tx'] = data;
  240. String privateS = YSAes.aesEncode3('${private}_${DateTime.now().microsecond}');
  241. request['prikey'] = privateS;
  242. // ignore: use_build_context_synchronously
  243. Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tronsign', parameter: request);
  244. if(dict.isNotEmpty){
  245. // return '';
  246. Map data2 = dict['data'];
  247. data['signature'] = data2['signature'];
  248. // 广播交易
  249. var url = Uri.parse('https://api.trongrid.io/wallet/broadcasttransaction');
  250. LogUtil.d('transferData3=======$data');
  251. var response = await client.post(
  252. url,
  253. headers: {'Content-Type': 'application/json'},
  254. body: jsonEncode(data),
  255. );
  256. result = jsonDecode(response.body);
  257. LogUtil.d('transferData3============${response.body}');
  258. if(result['result']==true){
  259. return '${result['txid']??''}';
  260. }else{
  261. return '';
  262. }
  263. }else{
  264. return '';
  265. }
  266. }
  267. }
  268. return '';
  269. } finally {
  270. // 关闭HTTP客户端
  271. client.close();
  272. }
  273. }
  274. static Future<String> exchangeContractData2(BuildContext context,{
  275. required String from,
  276. required String to,
  277. required String private,
  278. required String amount,
  279. required String tokenAddress
  280. }) async{
  281. var client = http.Client();
  282. try {
  283. // 构建交易请求
  284. Map<String, dynamic> requestBody = {
  285. 'privateKey': private,
  286. 'owner_address': from,
  287. 'to_address': tokenAddress,
  288. 'contractAddress': tokenAddress,
  289. 'amount': double.parse(amount)~/1,
  290. 'visible':true
  291. };
  292. LogUtil.d(requestBody);
  293. // 发送交易请求
  294. final response = await http.post(
  295. Uri.parse('https://api.trongrid.io/wallet/createtransaction'),
  296. headers: <String, String>{
  297. 'Content-Type': 'application/json; charset=UTF-8',
  298. },
  299. body: jsonEncode(requestBody),
  300. );
  301. LogUtil.d(response.body);
  302. return '';
  303. // 解析交易结果
  304. if (response.statusCode == 200) {
  305. Map<String, dynamic> responseBody = jsonDecode(response.body);
  306. Map request = {};
  307. request['tx'] = responseBody;
  308. String privateS = YSAes.aesEncode3('${private}_${DateTime.now().microsecond}');
  309. request['prikey'] = privateS;
  310. // ignore: use_build_context_synchronously
  311. Map dict = await YSNetWork.ysRequestHttpNOSet(context, type: RequestType.post, api: 'tronsign', parameter: request);
  312. if(dict.isNotEmpty){
  313. // return '';
  314. Map data2 = dict['data'];
  315. responseBody['signature'] = data2['signature'];
  316. // 广播交易
  317. var url = Uri.parse('https://api.trongrid.io/wallet/broadcasttransaction');
  318. LogUtil.d('transferData3=======$responseBody');
  319. var response = await client.post(
  320. url,
  321. headers: {'Content-Type': 'application/json'},
  322. body: jsonEncode(responseBody),
  323. );
  324. Map result = jsonDecode(response.body);
  325. LogUtil.d('transferData3============${response.body}');
  326. if(result['result']==true){
  327. return '${result['txid']??''}';
  328. }else{
  329. return '';
  330. }
  331. }
  332. // String transactionId = responseBody['txID'];
  333. // LogUtil.d('Transaction ID: $transactionId');
  334. } else {
  335. LogUtil.d('Transaction failed with status code: ${response.statusCode}');
  336. }
  337. return '';
  338. } finally {
  339. // 关闭HTTP客户端
  340. client.close();
  341. }
  342. }
  343. /// 将合约格式化
  344. static Future<DeployedContract> fromAssets(String path, String contractAddress) async {
  345. final contractJson = jsonDecode(await rootBundle.loadString(path));
  346. DeployedContract value = DeployedContract(ContractAbi.fromJson(jsonEncode(contractJson['abi']),contractJson['contractName'] as String),EthereumAddress.fromHex(contractAddress));
  347. return value;
  348. }
  349. }
  350. String toHex(Uint8List bytes) {
  351. return bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
  352. }