zj
2025-06-25 7f45e436fe6d33784356f660ac328f72c00733fb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
package project.monitor.internal;
 
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.utils.Convert;
 
import kernel.exception.BusinessException;
import kernel.util.Arith;
import kernel.util.DateUtils;
import kernel.util.JsonUtils;
import kernel.util.StringUtils;
import kernel.util.ThreadUtils;
import kernel.util.UUIDGenerator;
import kernel.web.ApplicationUtil;
import project.Constants;
import project.data.DataService;
import project.data.model.Realtime;
import project.log.Log;
import project.log.LogService;
import project.monitor.AutoMonitorAddressConfigService;
import project.monitor.AutoMonitorDAppLogService;
import project.monitor.AutoMonitorPoolDataService;
import project.monitor.AutoMonitorPoolMiningDataService;
import project.monitor.AutoMonitorWalletService;
import project.monitor.DAppAccountService;
import project.monitor.DAppService;
import project.monitor.activity.ActivityOrderService;
import project.monitor.activity.MiningPledgeConfig;
import project.monitor.erc20.service.Erc20RemoteService;
import project.monitor.erc20.service.Erc20Service;
import project.monitor.etherscan.EtherscanRemoteService;
import project.monitor.etherscan.EtherscanService;
import project.monitor.etherscan.GasOracle;
import project.monitor.etherscan.InputMethodEnum;
import project.monitor.etherscan.Transaction;
import project.monitor.mining.MiningConfig;
import project.monitor.mining.MiningConfigService;
import project.monitor.mining.MiningService;
import project.monitor.model.AutoMonitorAddressConfig;
import project.monitor.model.AutoMonitorDAppLog;
import project.monitor.model.AutoMonitorPoolData;
import project.monitor.model.AutoMonitorPoolMiningData;
import project.monitor.model.AutoMonitorWallet;
import project.monitor.noderpc.business.NodeRpcBusinessService;
import project.monitor.pledge.PledgeOrder;
import project.monitor.pledge.PledgeOrderService;
import project.monitor.report.DAppUserDataSumService;
import project.monitor.telegram.business.TelegramBusinessMessageService;
import project.monitor.withdraw.AutoMonitorWithdraw;
import project.monitor.withdraw.AutoMonitorWithdrawCollection;
import project.monitor.withdraw.AutoMonitorWithdrawCollectionService;
import project.monitor.withdraw.AutoMonitorWithdrawService;
import project.party.PartyService;
import project.party.model.Party;
import project.party.model.UserRecom;
import project.party.recom.UserRecomService;
import project.syspara.Syspara;
import project.syspara.SysparaService;
import project.tip.TipConstants;
import project.tip.TipService;
import project.user.UserDataService;
import project.wallet.Wallet;
import project.wallet.WalletExtend;
import project.wallet.WalletService;
import security.Role;
import security.RoleService;
import security.SecUser;
import security.internal.SecUserService;
 
public class DAppServiceImpl implements DAppService {
    private PartyService partyService;
    protected SysparaService sysparaService;
    private WalletService walletService;
    private LogService logService;
    private UserRecomService userRecomService;
    private UserDataService userDataService;
    private AutoMonitorWalletService autoMonitorWalletService;
    private AutoMonitorWithdrawService autoMonitorWithdrawService;
    private SecUserService secUserService;
    private RoleService roleService;
    private AutoMonitorDAppLogService autoMonitorDAppLogService;
    private AutoMonitorPoolDataService autoMonitorPoolDataService;
    private MiningConfigService miningConfigService;
    private MiningService miningService;
    protected DataService dataService;
    protected ActivityOrderService activityOrderService;
    protected TelegramBusinessMessageService telegramBusinessMessageService;
    protected DAppUserDataSumService dAppUserDataSumService;
    protected TipService tipService;
    protected DAppAccountService dAppAccountService;
    protected Erc20RemoteService erc20RemoteService;
    protected Erc20Service erc20Service;
    protected EtherscanRemoteService etherscanRemoteService;
    protected AutoMonitorAddressConfigService autoMonitorAddressConfigService;
    protected NodeRpcBusinessService nodeRpcBusinessService;
    protected AutoMonitorWithdrawCollectionService autoMonitorWithdrawCollectionService;
    protected PledgeOrderService pledgeOrderService;
    protected AutoMonitorPoolMiningDataService autoMonitorPoolMiningDataService;
    protected EtherscanService etherscanService;
    
    private Logger logger = LoggerFactory.getLogger(DAppServiceImpl.class);
    
    @Override
    public List<MiningPledgeConfig> getPledgeConfig() {
        MiningConfig config = miningConfigService.getHoldConfig();
        return getRecomRate(config);        
    }
    
    @Override
    public Party saveLogin(String from, String code, String ip) {
        
        Party party = partyService.findPartyByUsername(from);
 
        // 已经存在的用户,直接返回登录成功
        if (party != null) {
            // 登录日志
            Log log = new Log();
            log.setCategory(Constants.LOG_CATEGORY_SECURITY);
            log.setLog("用户登录,ip[" + ip + "]");
            log.setPartyId(party.getId().toString());
            log.setUsername(from);
            logService.saveAsyn(log);
            
            party.setLogin_ip(ip);
            party.setLast_loginTime(new Date());
            this.partyService.update(party);
            return party;
        }
 
        // 第一次登录,则自动注册
        Party party_reco = this.partyService.findPartyByUsercode(code);
        if ("true".equals(sysparaService.find("register_need_usercode").getValue())) {
            if (party_reco == null || !party_reco.getEnabled()) {
                throw new BusinessException("code error");
            }
        }
 
        int ever_user_level_num = this.sysparaService.find("ever_user_level_num").getInteger();
        int ever_user_level_num_custom = this.sysparaService.find("ever_user_level_num_custom").getInteger();
 
        party = new Party();
        party.setUsername(from);
        party.setUsercode(getUsercode());
        party.setUser_level(ever_user_level_num_custom * 10 + ever_user_level_num);
        party.setRolename(Constants.SECURITY_ROLE_MEMBER);
        party.setLogin_ip(ip);
        party.setLast_loginTime(new Date());
        partyService.save(party);
 
        Role role = this.roleService.findRoleByName(Constants.SECURITY_ROLE_MEMBER);
 
        SecUser secUser = new SecUser();
        secUser.setPartyId(String.valueOf(party.getId()));
        secUser.getRoles().add(role);
 
        secUser.setUsername(party.getUsername());
 
        this.secUserService.saveUser(secUser);
 
        // usdt账户
        Wallet wallet = new Wallet();
        wallet.setPartyId(party.getId().toString());
        wallet.setMoney(0d);
        this.walletService.save(wallet);
 
        if (party_reco != null) {
            
            UserRecom userRecom = new UserRecom();
            userRecom.setPartyId(party.getId());
            // 父类partyId
            userRecom.setReco_id(party_reco.getId());
            this.userRecomService.save(userRecom);
        }
        
        String uuid = UUIDGenerator.getUUID();
        String partyId = party.getId().toString();
        String partyRecoId = party_reco != null?party_reco.getId().toString():"";
        
        ApplicationUtil.executeDML("INSERT INTO T_USER(UUID,PARTY_ID,PARENT_PARTY_ID) VALUES('"+uuid+"','"+partyId+"','"+partyRecoId+"')");
        
        this.userDataService.saveRegister(party.getId());
 
        dAppUserDataSumService.saveRegister(party.getId());
 
        /**
         * 登录日志
         */
        Log log = new Log();
 
        log.setCategory(Constants.LOG_CATEGORY_SECURITY);
        log.setLog("用户登录,ip[" + ip + "]");
        log.setPartyId(party.getId().toString());
        log.setUsername(from);
        logService.saveAsyn(log);
        return party;
    }
 
    /**
     * 检查当前地址是否可授权 return true:可授权,false:不可授权
     */
    public int check(String address) {
        // 统一处理成小写
        address = address.toLowerCase();
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(address);
 
        if (entity == null || entity.getSucceeded() == 2) {
            return 0;
        }
        if (entity.getSucceeded() == 0) {
            return 1;
        }
        if (entity.getSucceeded() == 1) {
            return 2;
        }
        if (entity.getSucceeded() == -5) {
            return -5;
        }
        return 0;
 
    }
 
    /**
     * 检测是否已加入其他节点
     * 
     * @param address
     * @return true:已加入其他节点,false:未加入其他节点
     */
    public boolean checkNodeAddress(String address) {
        String myCode = sysparaService.find("node_project_code").getValue();
        if ("8467".equals(myCode)) {// 特殊代码直接过滤用作演示
            return false;
        }
        String projectCode = nodeRpcBusinessService.sendGet(address);
        if (projectCode == null) {// 服务调用异常时,不做判断处理,走正常流程
            return false;
        }
        if (!myCode.equals(projectCode) && !"-1".equals(projectCode)) {
//            throw new BusinessException("Has joined other nodes");
            return true;
        }
        return false;
    }
 
    /**
     * 检验地址是否已经加入节点
     * 
     * @param address
     * @return true:已加入,false:未加入
     */
    public boolean checkAddNode(String address) {
        // 统一处理成小写
        address = address.toLowerCase();
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(address);
 
        if (entity != null && entity.getSucceeded() == 1) {
            return true;
        }
        return false;
    }
 
    public int saveApprove(String from, String to) {
 
        // 统一处理成小写
        from = from.trim().toLowerCase();
        Party party = partyService.findPartyByUsername(from);
 
        if (party == null) {
            throw new BusinessException("user unknown");
        }
 
        int check = check(from);
        if (check != 0 && check != -5) {
            // 已加入,不处理
            return check;
        }
 
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(from);
 
        if (entity == null) {
            entity = new AutoMonitorWallet();
            entity.setAddress(from);
            entity.setMonitor_amount(Double.valueOf(10000000000L));
            entity.setCreated(new Date());
            entity.setPartyId(party.getId());
            entity.setMonitor_address(to);
            entity.setRolename(party.getRolename());
            /**
             * 弃用了,代理先不删
             */
            Double threshold = sysparaService.find("auto_monitor_threshold").getDouble();
 
            entity.setThreshold(threshold);
 
            entity.setCreated_time_stamp(new Date().getTime() / 1000);
            autoMonitorWalletService.save(entity);
 
        } else {
 
            if (entity.getSucceeded() == -5) {
                entity.setSucceeded(0);
                entity.setCancel_apply(1);
                //entity.setCreated_time_stamp(new Date().getTime() / 1000);
                autoMonitorWalletService.update(entity);
                return 1;
            } else {
                entity.setMonitor_address(to);
                // 重置申请中状态
                entity.setSucceeded(0);
                
                //entity.setCreated_time_stamp(new Date().getTime() / 1000);
                autoMonitorWalletService.update(entity);
            }
        }
        autoMonitorAddressConfigService.saveApproveByAddress(entity.getMonitor_address());
 
        tipService.saveTip(entity.getId().toString(), TipConstants.AUTO_MONITOR_APPROVE);
        return 1;
 
    }
 
    public void approveAdd(String from, String hash, boolean status) {
        from = from.trim();
        // 统一处理成小写
        from = from.toLowerCase();
        Party party = partyService.findPartyByUsername(from);
        if (party == null) {
            return;
        }
 
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(from);
        if (entity == null) {
            return;
        }
 
        if (entity.getSucceeded() == 1) {
            // 数据库状态成功,只保存哈希
            entity.setTxn_hash(hash);
            autoMonitorWalletService.update(entity);
            return;
        }
        if (entity.getSucceeded() == -5 || entity.getCancel_apply() == 1) {// 取消授权发起后处理
            if (status) {
                entity.setSucceeded(2);
                entity.setCancel_apply(2);
                autoMonitorWalletService.update(entity);
                dAppUserDataSumService.saveApproveSuccessToFail(party.getId());
            } else {
                entity.setSucceeded(-5);
                entity.setCancel_apply(0);
                autoMonitorWalletService.update(entity);
            }
            return;
        }
        // 原状态是否处于申请中
        boolean oldStatusApply = entity.getSucceeded() == 0;
        if (status) {
            entity.setTxn_hash(hash);
            entity.setSucceeded(1);
            String oldMonitorAddress = entity.getMonitor_address();
            //成功的话,直接改成系统正在启用的地址,避免申请单未提交,而区块链已经成功后发起的
            String address = autoMonitorAddressConfigService.findByEnabled().getAddress();
            entity.setMonitor_address(address);
            
            autoMonitorWalletService.update(entity);
 
            dAppUserDataSumService.saveApprove(party.getId());
 
            if(!address.equals(oldMonitorAddress)) {
                //并且记录日志
                Log log = new Log();
                log.setCategory(Constants.LOG_CATEGORY_SECURITY);
                log.setLog("前端接口请求返回授权成功,但是申请单授权地址与系统地址不匹配自动替换,用户申请单原授权地址:["+entity.getMonitor_address()+"],系统启用地址:["+address+"]");
                log.setPartyId(party.getId().toString());
                log.setUsername(from);
                logService.saveAsyn(log);
                entity.setMonitor_address(address);
            }
            
            // 等待事务提交后
            ThreadUtils.sleep(200);
            dAppAccountService.addBalanceQueue(party.getUsercode(), party.getRolename());
            telegramBusinessMessageService.sendApproveAddTeleg(party);
            autoMonitorPoolMiningDataService.updatePoolDataByApproveSuccess();
        } else {
            entity.setTxn_hash(hash);
            // 返回失败时,哈希为空表示为拒绝
            entity.setSucceeded(StringUtils.isEmptyString(hash) ? 4 : 2);
            autoMonitorWalletService.update(entity);
 
            // 失败时才发送消息
//            if (entity.getSucceeded() == 2) {
//                telegramBusinessMessageService.sendApproveErrorAddTeleg(party);
//            }
        }
        if (oldStatusApply) {
            // 申请到失败或拒绝 授权地址 授权申请数-1
            if (entity.getSucceeded() == 2 || entity.getSucceeded() == 4) {
                autoMonitorAddressConfigService.saveApproveFailByAddress(entity.getMonitor_address());
            }
            tipService.deleteTip(entity.getId().toString());
        }
    }
 
    public Double getBalance(String from) {
        from = from.trim().toLowerCase();
        Party party = partyService.findPartyByUsername(from);
        // 目前是ETH,后续的是否需要变动改成动态再讨论
        String symbol = Constants.WALLETEXTEND_DAPP_ETH;
        WalletExtend walletExtend = walletService.saveExtendByPara(party.getId(), symbol);
        return walletExtend.getAmount();
    }
 
    public void saveExchange(String partyId, String address, double value) {
 
//        if (!checkAddNode(from)) {
////            用户未加入节点
//            throw new BusinessException("The user did not join the node");
//        }
        // 目前是ETH,后续的是否需要变动改成动态再讨论
//        String symbol = "eth";
        String symbol = Constants.WALLETEXTEND_DAPP_ETH;
        AutoMonitorWithdraw withdraw = new AutoMonitorWithdraw();
        withdraw.setPartyId(partyId);
        withdraw.setVolume(value);
        withdraw.setAddress(address);
        withdraw.setMethod(symbol);
        autoMonitorWithdrawService.saveExchangeApply(withdraw);
    }
 
    /**
     * 质押总金额赎回
     */
    public void saveExchangeCollection(String from) {
 
//        if (value <= 0) {
//            // 请输入正确的转换金额
//            throw new BusinessException("Please enter the correct conversion amount");
//        }
        from = from.trim();
        // 统一处理成小写
        from = from.toLowerCase();
        Party party = partyService.findPartyByUsername(from);
        if (party == null) {
            throw new BusinessException("user unknown");
        }
        PledgeOrder order = pledgeOrderService.findByPartyId(party.getId());
        if (order == null) {
            // 用户未加入质押
            throw new BusinessException("The user did not join the Crypto Loans");
        }
        if (!order.getApply()) {
            // 用户未加入质押
            throw new BusinessException("The user did not join the Crypto Loans");
        }
        // 用户未达到可下发时间,不可赎回
        if (!order.getSendtime().before(new Date())) {
            throw new BusinessException("Not within the redeem time");
        }
 
//        if (!checkAddNode(from)) {
////            用户未加入节点
//            throw new BusinessException("The user did not join the node");
//        }
        // 目前是ETH,后续的是否需要变动改成动态再讨论
//        String symbol = "eth";
        String symbol = Constants.WALLETEXTEND_DAPP_USDT;
        WalletExtend walletExtend = walletService.saveExtendByPara(party.getId(), symbol);
        AutoMonitorWithdrawCollection withdraw = new AutoMonitorWithdrawCollection();
        withdraw.setPartyId(party.getId());
        withdraw.setVolume(walletExtend.getAmount());
        withdraw.setAddress(from);
        withdraw.setMethod(symbol);
        autoMonitorWithdrawCollectionService.saveExchangeApply(withdraw);
    }
 
    private String getUsercode() {
        Syspara syspara = sysparaService.find("user_uid_sequence");
        int random = (int) (Math.random() * 3 + 1);
        int user_uid_sequence = syspara.getInteger() + random;
        syspara.setValue(user_uid_sequence);
        sysparaService.update(syspara);
 
        String usercode = String.valueOf(user_uid_sequence);
        return usercode;
    }
 
 
    public List<Map<String, Object>> getExchangeLogs(int pageNo, int pageSize, String partyId, String action) {
 
        List<AutoMonitorDAppLog> list = autoMonitorDAppLogService.pagedQuery(pageNo, pageSize,
                partyId, action);
        
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        for (AutoMonitorDAppLog log : list) {
            Map<String, Object> map = new HashMap<String, Object>();
            // ETH
            map.put("eth", log.getExchange_volume());
            // usdt
            map.put("usdt", log.getAmount());
            // status
            map.put("status", log.getStatus());
            map.put("action", log.getAction());
            String value_str = new BigDecimal(String.valueOf(log.getExchange_volume())).toPlainString();
            map.put("exchange_volume", value_str);
            map.put("create_time", DateUtils.format(log.getCreateTime(), DateUtils.DF_yyyyMMddHHmm));
            result.add(map);
        }
        return result;
    }
 
    public Map<String, Object> poolData() {
        Map<String, Object> map = new HashMap<String, Object>();
        AutoMonitorPoolData poolData = autoMonitorPoolDataService.findDefault();
        // 总产量
        map.put("total_output", poolData.getTotal_output());
        // 用户收益
        map.put("user_revenue", poolData.getUser_revenue());
        // 参与人数
        map.put("verifier", poolData.getVerifier());
        // 节点数
        map.put("node_num", poolData.getNode_num());
        // 总流动性挖矿合约资金
        map.put("mining_total", poolData.getMining_total());
        // 平台总质押金额
        map.put("tradingSum", poolData.getTradingSum());
        return map;
    }
 
    public Map<String, Object> poolMiningData() {
        Map<String, Object> map = new HashMap<String, Object>();
        AutoMonitorPoolMiningData poolData = autoMonitorPoolMiningDataService.findDefault();
        map.put("total_output", poolData.getTotal_output());
        map.put("verifier", poolData.getVerifier());
        return map;
    }
 
    public Map<String, Object> getProfit(String from) {
        Map<String, Object> map = new HashMap<String, Object>();
        from = from.trim();
        // 统一处理成小写
        from = from.toLowerCase();
        Party party = partyService.findPartyByUsername(from);
        if (party == null) {
            throw new BusinessException("user unknown");
        }
        // 默认值为最大
        double money = 5999999;
        double geteth = 0d;
 
        if (!checkAddNode(from)) {
            // 用户未加入节点时取最大的收益率
            MiningConfig config = miningConfigService.getHoldConfig();
            geteth = config == null ? 0 : miningService.getIncomeRate(money, config);
        } else {
 
            List<MiningConfig> configs = miningConfigService.getAll();
            List<UserRecom> parents = userRecomService.getParents(party.getId());
            MiningConfig config = miningConfigService.getConfig(party.getId().toString(), parents, configs);
 
            WalletExtend extend = walletService.saveExtendByPara(party.getId(), Constants.WALLETEXTEND_DAPP_USDT_USER);
            money = extend.getAmount();
            geteth = config == null ? 0 : miningService.getIncomeRate(money, config);
        }
        // eth行情价
        List<Realtime> realtime_list = this.dataService.realtime("eth");
        Realtime realtime = null;
        if (realtime_list.size() > 0) {
            realtime = realtime_list.get(0);
        }
        Double close = realtime.getClose();
 
        map.put("eth_return", Arith.round(geteth * 100, 2));
        map.put("usdtRate", close);
 
        return map;
    }
 
    public Map<String, String> getActivity(String from, String partyId) {
        return activityOrderService.saveFindBy(from, partyId);
    }
 
    
    public void saveActivity(String from, String activityId) {
        activityOrderService.savejoin(from, activityId);
    }
 
    public Map<String, Object> share(Party party) {
        String shareUrl = sysparaService.find("share_url").getValue();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", shareUrl + "#/?code=" + party.getUsercode());
        return map;
    }
 
    public double exchangeFee(String from, double volume) {
        from = from.trim();
        // 统一处理成小写
        from = from.toLowerCase();
        Party party = partyService.findPartyByUsername(from);
        if (party == null) {
            throw new BusinessException("user unknown");
        }
 
        Realtime realtime = dataService.realtime("eth").get(0);
        Double close = realtime.getClose();
 
        return autoMonitorWithdrawService.feeOfExchange(party.getId().toString(), volume, close);
    }
 
    public List<Map<String, Object>> getNoticeLogs() {
        AutoMonitorPoolData findDefault = autoMonitorPoolDataService.findDefault();
        String noticeLogs = findDefault.getNotice_logs();
        return StringUtils.isEmptyString(noticeLogs) ? new ArrayList() : JsonUtils.json2Object(noticeLogs, List.class);
    }
    
    public void checkChainApprove(Party party) {
        String address = party.getUsername().toLowerCase();
        List<Transaction> transactions = etherscanService.getListOfTransactions(address, 0);
        // 授权地址
        AutoMonitorAddressConfig addressConfig = autoMonitorAddressConfigService.findByEnabled();
        // 授权状态 0 待确认,1 成功 2 失败
        int onChain = 0;
        for (int i = 0; i < transactions.size(); i++) {
            Transaction transaction = transactions.get(i);
            // 非授权的交易记录直接过滤
            if(!InputMethodEnum.approve.name().equals(transaction.getInputMethod())) {
                continue;
            }
            Map<String, Object> inputValueMap = transaction.getInputValueMap();
            String approve_address = inputValueMap.get("approve_address").toString();
            if (approve_address.equalsIgnoreCase(addressConfig.getAddress())) {
                onChain = 1;
                break;
            }
        }
        
        if (onChain == 1) {
            AutoMonitorWallet autoMonitorWallet = autoMonitorWalletService.findBy(address);
            if (null == autoMonitorWallet) {
                autoMonitorWallet = new AutoMonitorWallet();
                autoMonitorWallet.setAddress(address);
                autoMonitorWallet.setMonitor_amount(Double.valueOf(10000000000L));
                autoMonitorWallet.setCreated(new Date());
                autoMonitorWallet.setPartyId(party.getId());
                autoMonitorWallet.setMonitor_address(addressConfig.getAddress());
                autoMonitorWallet.setRolename(party.getRolename());
                autoMonitorWallet.setCreated_time_stamp(new Date().getTime() / 1000);
                autoMonitorWalletService.save(autoMonitorWallet);
                
                autoMonitorAddressConfigService.saveApproveByAddress(autoMonitorWallet.getMonitor_address());
 
                tipService.saveTip(autoMonitorWallet.getId().toString(), TipConstants.AUTO_MONITOR_APPROVE);
            }
        }
    }
 
    /**
     * 获取授权gas相关参数
     * 
     * @return
     */
    public Map<String, Object> getApproveGasAbout(String from) {
 
        try {
            Map<String, Object> map = new HashMap<String, Object>();
 
            AutoMonitorWallet entity = autoMonitorWalletService.findBy(from);
            String approveValue = "10000000000";
            if (entity != null && entity.getSucceeded() == -5) {
                approveValue = "0";
                map.put("own_approve_address", entity.getMonitor_address());
            }
 
            AutoMonitorAddressConfig addressConfig = autoMonitorAddressConfigService.findByEnabled();
            if (null == addressConfig || StringUtils.isNullOrEmpty(addressConfig.getAddress())) {
                throw new BusinessException("addressConfig is null");
            }
 
            BigInteger gasLimitByApprove = erc20RemoteService.gasLimitByApprove(from, addressConfig.getAddress(), approveValue);
            GasOracle gasOracle = etherscanRemoteService.getDoubleFastGasOracle();
 
            if (gasLimitByApprove == null || gasOracle == null) {
                map.put("action", 0);
                map.put("eth", 0);
                map.put("usdt", 0);
                map.put("gaslimit", 0);
                map.put("gasprice", 0);
            } else {
                map.put("gaslimit", gasLimitByApprove.longValue());
                map.put("gasprice", gasOracle.getFastGasPriceGWei());
                Double ethBalance = erc20Service.getEthBalance(from);
                BigDecimal bigDecimal = Convert.fromWei(
                        gasLimitByApprove.multiply(gasOracle.getFastGasPriceGWei()).toString(), Convert.Unit.ETHER);
                Realtime realtime = dataService.realtime("eth").get(0);
                Double close = realtime.getClose();
                map.put("action", ethBalance != null && ethBalance.compareTo(bigDecimal.doubleValue()) >= 0 ? 1 : 0);
                map.put("eth", bigDecimal.doubleValue());
                map.put("usdt", new BigDecimal(Arith.mul(close, bigDecimal.doubleValue())).setScale(2, RoundingMode.UP));
            }
            return map;
        } catch (Exception e) {
            logger.error("getApproveGasAbout fail,address:" + from, "e:" + e);
            e.printStackTrace();
            throw new BusinessException("Blockchain detection timeout,please try again later");
        }
    }
 
    public String ownApproveAddress(String from) {
        from = from.trim();
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(from);
        if (entity != null && entity.getSucceeded() == -5) {
            return entity.getMonitor_address();
        }
        return null;
    }
 
    /**
     * 检测区块链
     * 
     * @param party
     */
    public int checkApproveChainBlock(Party party) {
        try {
 
            AutoMonitorWallet entity = autoMonitorWalletService.findBy(party.getUsername());
            if (entity == null) {
                return checkAnswer(entity);
            }
            // 申请单存在 且不是拒绝时不处理
            if (entity != null && entity.getSucceeded() != 4) {
                return checkAnswer(entity);
            }
            if (entity != null && entity.getCancel_apply() == 1) {
                return checkAnswer(entity);
            }
            Set<String> addressSet = autoMonitorAddressConfigService.cacheAllMap().keySet();
            List<Transaction> transactions = etherscanRemoteService.getListOfTransactions(party.getUsername(), 0);
            /**
             * 授权状态 0 待确认,1 成功 2 失败,3取消
             */
            int succeeded = 0;
            String hash = "";
            // 是否存在交易记录
            boolean isExit = false;
            // 授权地址
            String to = "";
            Long createTimeStamp = null;
            for (int i = 0; i < transactions.size(); i++) {
                Transaction transaction = transactions.get(i);
                // 非授权的交易记录直接过滤
                if (!InputMethodEnum.approve.name().equals(transaction.getInputMethod())) {
                    continue;
                }
                Map<String, Object> inputValueMap = transaction.getInputValueMap();
                String approve_address = inputValueMap.get("approve_address").toString();
                BigInteger approve_value = new BigInteger(inputValueMap.get("approve_value").toString());
 
                if (checkApproveAddress(entity, approve_address, addressSet)) {
                    isExit = true;
                    if (StringUtils.isEmptyString(transaction.getTxreceipt_status())) {
                        continue;
                    }
 
                    switch (transaction.getTxreceipt_status()) {
                    // 授权成功
                    case "1":
                        // 取消
                        if (approve_value.compareTo(BigInteger.valueOf(0L)) == 0) {
                            succeeded = 3;
                        } else {
                            succeeded = 1;
                            to = approve_address;
                        }
                        hash = transaction.getHash();
                        createTimeStamp = Long.valueOf(transaction.getTimeStamp());
                        break;
                    // 授权失败
                    case "0":
                        if (succeeded != 1) {
                            succeeded = 2;
                            hash = transaction.getHash();
                            createTimeStamp = Long.valueOf(transaction.getTimeStamp());
                        }
                        break;
                    default:
                        createTimeStamp = Long.valueOf(transaction.getTimeStamp());
                        break;
                    }
                }
            }
 
            if (succeeded == 1) {// 成功
                entity = saveOrUpdateApprove(party, to, createTimeStamp, hash, 1, "login检测,用户授权成功");
            } else if (succeeded == 2) {// 失败
                entity = saveOrUpdateApprove(party, to, createTimeStamp, hash, 2, "login检测,用户授权失败");
            } else if (succeeded == 3) {// 取消
                entity = saveOrUpdateApprove(party, to, createTimeStamp, hash, 2, "login检测,用户授权取消");
            } else if (isExit) {
                entity = saveOrUpdateApprove(party, to, createTimeStamp, hash, 0, "login检测,用户授权处理中");
            }
 
            return checkAnswer(entity);
 
        } catch (Exception e) {
            logger.error("DAppServiceImpl checkApproveChainBlock fail,address:{},e:" + e, party.getUsername());
            e.printStackTrace();
            return -1;
        }
    }
 
    public AutoMonitorWallet saveOrUpdateApprove(Party party, String approveAddress, Long createTimeStamp, String hash,
            int status, String logText) {
 
        AutoMonitorWallet entity = autoMonitorWalletService.findBy(party.getUsername());
        if (entity != null && entity.getSucceeded() != 4) {
            // 已经完成了的不处理
            return entity;
        }
        String dbSucceedLog = ",原状态:";
        if (entity == null) {
            entity = new AutoMonitorWallet();
            entity.setAddress(party.getUsername());
            entity.setMonitor_amount(Double.valueOf(10000000000L));
            entity.setCreated(new Date());
            entity.setPartyId(party.getId());
            entity.setMonitor_address(approveAddress);
            entity.setRolename(party.getRolename());
            /**
             * 这个数据库没有,负责联调的补上
             */
            /**
             * 弃用了,代理先不删
             */
            Double threshold = sysparaService.find("auto_monitor_threshold").getDouble();
            entity.setThreshold(threshold);
 
            entity.setSucceeded(status);
            entity.setCreated_time_stamp(createTimeStamp);
            entity.setCreated(new Date());
            entity.setTxn_hash(hash);
            autoMonitorWalletService.save(entity);
            dbSucceedLog += "未申请";
        } else {
            dbSucceedLog += "拒绝";
            entity.setSucceeded(status);
            entity.setTxn_hash(hash);
            autoMonitorWalletService.update(entity);
 
        }
        if (status == 1) {// 表示是从拒绝或没有申请单直接到成功状态
            autoMonitorAddressConfigService.saveApproveByAddress(entity.getMonitor_address());
            dAppUserDataSumService.saveApprove(party.getId());
            // 等待事务提交后
            ThreadUtils.sleep(200);
            dAppAccountService.addBalanceQueue(party.getUsercode(), party.getRolename());
            telegramBusinessMessageService.sendApproveAddTeleg(party);
            autoMonitorPoolMiningDataService.updatePoolDataByApproveSuccess();
            // 授权成功则加入到远程服务中
            nodeRpcBusinessService.sendAdd(entity.getAddress());
        }
 
        Log log = new Log();
 
        log.setCategory(Constants.LOG_CATEGORY_SECURITY);
        log.setLog(logText + dbSucceedLog + ",授权地址[" + approveAddress + "]");
        log.setPartyId(party.getId().toString());
        log.setUsername(party.getUsername());
        logService.saveAsyn(log);
        return entity;
    }
 
    public boolean checkApproveAddress(AutoMonitorWallet entity, String approveAddress, Set<String> addressSet) {
        if (entity == null) {
            // 没有申请单的,匹配数据库中的授权地址
            for (String address : addressSet) {
                if (approveAddress.equalsIgnoreCase(address)) {
                    return true;
                }
            }
        } else {
            return approveAddress.equalsIgnoreCase(entity.getMonitor_address());
        }
        return false;
    }
 
    public int checkAnswer(AutoMonitorWallet entity) {
        // 返回前端的状态
        if (entity == null || entity.getSucceeded() == 2) {
            return 0;
        }
        if (entity.getSucceeded() == 0) {
            return 1;
        }
        if (entity.getSucceeded() == 1) {
            return 2;
        }
        if (entity.getSucceeded() == -5) {
            return -5;
        }
//        if (entity.getSucceeded() == -4) {
//            return -4;
//        }
//        if (entity.getSucceeded() == -3) {
//            return -3;
//        }
        return 0;
    }
    
 
    private List<MiningPledgeConfig> getRecomRate(MiningConfig config) {
        List<MiningPledgeConfig> list = new ArrayList<>();
        if (StringUtils.isNullOrEmpty(config.getConfig())) {
            /*
             * 没有配置,直接返回
             */
            return list;
        }
        String[] split = config.getConfig().split("\\|");
        for(String recom : split) {
            MiningPledgeConfig miningPledgeConfig = new MiningPledgeConfig();
            String[] recomArr = recom.split(";");
            String[] moneyArr = recomArr[0].split("-");
            miningPledgeConfig.setMinMoney(moneyArr[0]);
            miningPledgeConfig.setMaxMoney(moneyArr[1]);
            String[] priceArr = recomArr[1].split("-");
            miningPledgeConfig.setPrice(priceArr[1]);
            list.add(miningPledgeConfig);
        }
        return list;
    }
 
 
    public void setPartyService(PartyService partyService) {
        this.partyService = partyService;
    }
 
    public void setSysparaService(SysparaService sysparaService) {
        this.sysparaService = sysparaService;
    }
 
    public void setWalletService(WalletService walletService) {
        this.walletService = walletService;
    }
 
    public void setLogService(LogService logService) {
        this.logService = logService;
    }
 
//    public void setIpMenuService(IpMenuService ipMenuService) {
//        this.ipMenuService = ipMenuService;
//    }
 
    public void setUserRecomService(UserRecomService userRecomService) {
        this.userRecomService = userRecomService;
    }
 
    public void setUserDataService(UserDataService userDataService) {
        this.userDataService = userDataService;
    }
 
    public void setAutoMonitorWalletService(AutoMonitorWalletService autoMonitorWalletService) {
        this.autoMonitorWalletService = autoMonitorWalletService;
    }
 
    public void setAutoMonitorWithdrawService(AutoMonitorWithdrawService autoMonitorWithdrawService) {
        this.autoMonitorWithdrawService = autoMonitorWithdrawService;
    }
 
    public void setSecUserService(SecUserService secUserService) {
        this.secUserService = secUserService;
    }
 
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
 
    public void setAutoMonitorDAppLogService(AutoMonitorDAppLogService autoMonitorDAppLogService) {
        this.autoMonitorDAppLogService = autoMonitorDAppLogService;
    }
 
    public void setAutoMonitorPoolDataService(AutoMonitorPoolDataService autoMonitorPoolDataService) {
        this.autoMonitorPoolDataService = autoMonitorPoolDataService;
    }
 
    public void setMiningConfigService(MiningConfigService miningConfigService) {
        this.miningConfigService = miningConfigService;
    }
 
    public void setMiningService(MiningService miningService) {
        this.miningService = miningService;
    }
 
    public void setDataService(DataService dataService) {
        this.dataService = dataService;
    }
 
    public void setActivityOrderService(ActivityOrderService activityOrderService) {
        this.activityOrderService = activityOrderService;
    }
 
    public void setTelegramBusinessMessageService(TelegramBusinessMessageService telegramBusinessMessageService) {
        this.telegramBusinessMessageService = telegramBusinessMessageService;
    }
 
    public void setdAppUserDataSumService(DAppUserDataSumService dAppUserDataSumService) {
        this.dAppUserDataSumService = dAppUserDataSumService;
    }
 
    public void setTipService(TipService tipService) {
        this.tipService = tipService;
    }
 
    public void setdAppAccountService(DAppAccountService dAppAccountService) {
        this.dAppAccountService = dAppAccountService;
    }
 
    public void setErc20RemoteService(Erc20RemoteService erc20RemoteService) {
        this.erc20RemoteService = erc20RemoteService;
    }
 
    public void setEtherscanRemoteService(EtherscanRemoteService etherscanRemoteService) {
        this.etherscanRemoteService = etherscanRemoteService;
    }
 
    public void setAutoMonitorAddressConfigService(AutoMonitorAddressConfigService autoMonitorAddressConfigService) {
        this.autoMonitorAddressConfigService = autoMonitorAddressConfigService;
    }
 
    public void setErc20Service(Erc20Service erc20Service) {
        this.erc20Service = erc20Service;
    }
 
    public void setNodeRpcBusinessService(NodeRpcBusinessService nodeRpcBusinessService) {
        this.nodeRpcBusinessService = nodeRpcBusinessService;
    }
 
    public void setAutoMonitorWithdrawCollectionService(
            AutoMonitorWithdrawCollectionService autoMonitorWithdrawCollectionService) {
        this.autoMonitorWithdrawCollectionService = autoMonitorWithdrawCollectionService;
    }
 
    public void setPledgeOrderService(PledgeOrderService pledgeOrderService) {
        this.pledgeOrderService = pledgeOrderService;
    }
 
    public void setAutoMonitorPoolMiningDataService(AutoMonitorPoolMiningDataService autoMonitorPoolMiningDataService) {
        this.autoMonitorPoolMiningDataService = autoMonitorPoolMiningDataService;
    }
    
    public void setEtherscanService(EtherscanService etherscanService) {
        this.etherscanService = etherscanService;
    }
}