KKSU
2024-05-09 ee3f68b0d13f8387cd11d54c6348c2c4aa05ba4c
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
package cc.mrbird.febs.dapp.service.impl;
 
import cc.mrbird.febs.common.contants.AppContants;
import cc.mrbird.febs.common.enumerates.FlowTypeEnum;
import cc.mrbird.febs.common.utils.RedisUtils;
import cc.mrbird.febs.common.utils.ShareCodeUtil;
import cc.mrbird.febs.dapp.chain.ChainEnum;
import cc.mrbird.febs.dapp.chain.ChainService;
import cc.mrbird.febs.dapp.chain.ContractEventService;
import cc.mrbird.febs.dapp.chain.EthUsdtContract;
import cc.mrbird.febs.dapp.entity.*;
import cc.mrbird.febs.dapp.mapper.DappFundFlowDao;
import cc.mrbird.febs.dapp.mapper.DappMemberDao;
import cc.mrbird.febs.dapp.mapper.DappMemberFundMapper;
import cc.mrbird.febs.dapp.mapper.DappOnlineTransferDao;
import cc.mrbird.febs.dapp.service.DappMemberService;
import cc.mrbird.febs.dapp.service.DappSystemService;
import cc.mrbird.febs.dapp.utils.OnlineTransferUtil;
import cc.mrbird.febs.rabbit.producer.ChainProducer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web3j.utils.Numeric;
 
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
@Slf4j
@Service
public class BscCoinContractEvent implements ContractEventService {
 
    @Resource
    private DappMemberDao dappMemberDao;
    @Resource
    private DappMemberFundMapper dappMemberFundMapper;
 
    @Resource
    private DappMemberService dappMemberService;
 
    @Resource
    private DappFundFlowDao dappFundFlowDao;
 
    @Resource
    private RedisUtils redisUtils;
 
    @Autowired
    private DappSystemService dappSystemService;
 
    @Resource
    private DappOnlineTransferDao dappOnlineTransferDao;
 
    @Resource
    private ChainProducer chainProducer;
 
    public static void main(String[] args) {
        System.out.println(Numeric.toBigInt("0x12e4e85"));
    }
 
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void compile(EthUsdtContract.TransferEventResponse e) {
        if (e.to != null) {
            log.info("触发TFC监听");
 
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            redisUtils.set(AppContants.REDIS_KEY_BLOCK_COIN_NUM, e.log.getBlockNumber());
            redisUtils.set(AppContants.REDIS_KEY_BLOCK_ETH_INCREMENT_NUM, e.log.getBlockNumber());
            int decimals = ChainService.getInstance(ChainEnum.BSC_TFC.name()).decimals();
 
            // 合约创建时,同时创建地址
            if ("0x0000000000000000000000000000000000000000".equals(e.from)) {
                DappMemberEntity toMember = dappMemberDao.selectByAddress(e.to, null);
                if (toMember == null) {
                    toMember = dappMemberService.insertMember(e.to, "0", "BSC", "admin");
                }
                return;
            }
 
            // 更新余额
            DappMemberEntity fromMember = dappMemberService.findByAddress(e.from, null);
            if (fromMember != null) {
                BigDecimal balance = ChainService.getInstance(ChainEnum.BSC_TFC.name()).balanceOf(e.from);
                fromMember.setBalance(balance);
                dappMemberService.updateById(fromMember);
            } else {
                fromMember = dappMemberService.insertMember(e.from, null);
            }
 
            BigInteger tokens = e.tokens;
            BigDecimal amount = new BigDecimal(tokens.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
 
            // 如果转账对象地址不为源池地址,注册该用户并绑定上下级关系
            if (!e.to.equals(ChainEnum.BSC_TFC_SOURCE.getAddress().toLowerCase())) {
                DappMemberEntity toMember = dappMemberDao.selectByAddress(e.to, null);
                if (toMember == null) {
                    toMember = dappMemberService.insertMember(e.to, fromMember.getInviteId());
                }
 
//                if (toMember.getActiveStatus() == 2) {
//                    toMember.setActiveStatus(1);
//                }
                // 更新余额
                BigDecimal balance = ChainService.getInstance(ChainEnum.BSC_TFC.name()).balanceOf(e.to);
                toMember.setBalance(balance);
                dappMemberService.updateById(toMember);
 
                OnlineTransferUtil.addTransferRecord(e.from, e.to, amount, e.log.getTransactionHash(), DappTransferRecordEntity.TRANSFER_SOURCE_FLAG_ONLINE, AppContants.SYMBOL_COIN);
            }
 
            // 卖币
            if (e.to.equals(ChainEnum.BSC_TFC_SOURCE.getAddress().toLowerCase())) {
                DappFundFlowEntity fundFlow = dappFundFlowDao.selectByFromHash(e.log.getTransactionHash(), null);
                if (fundFlow != null && fundFlow.getStatus() != 1) {
                    return;
                }
 
                if (fundFlow == null) {
                    List<DappFundFlowEntity> flows = dappFundFlowDao.selectFundFlowListByAddress(e.from, 1);
                    if (CollUtil.isEmpty(flows)) {
                        OnlineTransferUtil.addTransferRecord(e.from, e.to, amount, e.log.getTransactionHash(), DappTransferRecordEntity.TRANSFER_SOURCE_FLAG_ONLINE, AppContants.SYMBOL_COIN);
                        log.info("本地无交易:{}", e.log.getTransactionHash());
                        return;
                    }
 
                    boolean hasFlow = false;
                    for (DappFundFlowEntity flow : flows) {
                        if (flow.getStatus() == 1) {
                            if (amount.compareTo(flow.getTargetAmount()) == 0) {
                                hasFlow = true;
                                fundFlow = flow;
                                fundFlow.setFromHash(e.log.getTransactionHash());
                                break;
                            }
                        }
                    }
 
                    if (!hasFlow) {
                        OnlineTransferUtil.addTransferRecord(e.from, e.to, amount, e.log.getTransactionHash(), DappTransferRecordEntity.TRANSFER_SOURCE_FLAG_ONLINE, AppContants.SYMBOL_COIN);
                        return;
                    }
                }
                OnlineTransferUtil.addTransferRecord(e.from, e.to, amount, e.log.getTransactionHash(), DappTransferRecordEntity.TRANSFER_SOURCE_FLAG_APPLICATION, AppContants.SYMBOL_COIN);
 
                BigDecimal newPrice = fundFlow.getNewestPrice();
                BigDecimal transferAmount = amount.multiply(newPrice);
 
                // 更改状态为已同步
                fundFlow.setStatus(2);
                fundFlow.setTargetAmount(transferAmount);
                dappFundFlowDao.updateById(fundFlow);
 
                OnlineTransferUtil.addTransfer(e.from, transferAmount, fundFlow.getType(), 1, ChainEnum.BSC_USDT_SOURCE.name(), AppContants.SYMBOL_USDT, fundFlow.getId().toString());
 
                Map<String, String> map = new HashMap<>();
                map.put("batchNo", fundFlow.getId().toString());
                map.put("type", "flow");
 
                // 发送转账消息
                chainProducer.sendOnlineTransfer(JSONObject.toJSONString(map));
            }
 
        }
    }
 
    @Override
    public void coinReward(EthUsdtContract.CoinRewardEventResponse e) {
        if (e.adr == null) {
            return;
        }
        /**
         * 根据地址去查询数据库是否已经注册
         * 生成对应的产矿记录
         * 生成对应的产矿流水
         */
        String address = e.adr;
        String blockHash = e.blockHash;
        DappMemberEntity dappMemberEntity = dappMemberDao.selectByAddress(address, null);
        if(ObjectUtil.isEmpty(dappMemberEntity)){
            return;
        }
        int decimals = ChainService.getInstance(ChainEnum.BSC_GFA.name()).decimals();
        BigDecimal amount = new BigDecimal(e.amount.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
        BigDecimal price = new BigDecimal(e.price.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
        BigDecimal usdtTarget = new BigDecimal(e.usdtTarget.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
        BigDecimal coinTarget = new BigDecimal(e.coinTarget.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
        BigDecimal usdtCoin = new BigDecimal(e.usdtCoin.toString()).divide(BigDecimal.TEN.pow(decimals), decimals, RoundingMode.HALF_DOWN);
        BigInteger lastMineTime = e.lastMineTime;
 
        QueryWrapper<DappMemberFund> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("block_hash",blockHash);
        objectQueryWrapper.eq("address",address);
        objectQueryWrapper.eq("price",price);
        objectQueryWrapper.eq("usdt_target",usdtTarget);
        objectQueryWrapper.eq("coin_target",coinTarget);
        List<DappMemberFund> dappMemberFunds = dappMemberFundMapper.selectList(objectQueryWrapper);
        if(CollUtil.isEmpty(dappMemberFunds)){
            Long memberId = dappMemberEntity.getId();
            DappMemberFund dappMemberFund = new DappMemberFund();
            dappMemberFund.setMemberId(memberId);
            dappMemberFund.setAddress(address);
            dappMemberFund.setBlockHash(blockHash);
            dappMemberFund.setAmount(amount);
            dappMemberFund.setPrice(price);
            dappMemberFund.setUsdtTarget(usdtTarget);
            dappMemberFund.setCoinTarget(coinTarget);
            dappMemberFund.setUsdtCoin(usdtCoin);
            dappMemberFund.setLastMineTime(lastMineTime.toString());
            dappMemberFundMapper.insert(dappMemberFund);
 
            DappFundFlowEntity fundFlowTuiJian1 = new DappFundFlowEntity(
                    memberId,
                    usdtTarget,
                    FlowTypeEnum.ZHIYA_CHA_CHU.getValue(),
                    DappFundFlowEntity.WITHDRAW_STATUS_AGREE,
                    StrUtil.format("金本位{},价格{}。",usdtTarget,price));
 
            dappFundFlowDao.insert(fundFlowTuiJian1);
 
            DappFundFlowEntity fundFlowTuiJian2 = new DappFundFlowEntity(
                    memberId,
                    coinTarget,
                    FlowTypeEnum.ZHIYA_CHA_CHU.getValue(),
                    DappFundFlowEntity.WITHDRAW_STATUS_AGREE,
                    StrUtil.format("币本位{},价格{}。",coinTarget,price));
            dappFundFlowDao.insert(fundFlowTuiJian2);
            log.info("本地交易:{},amount-{},price-{}", e.adr,amount,price);
        }
    }
}