fix
Helius
2022-06-11 9b72d61675684b6c5c75597e3139b12b9d4437c8
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
package cc.mrbird.febs.dapp.service.impl;
 
import cc.mrbird.febs.common.contants.AppContants;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.common.exception.FebsException;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.utils.LoginUserUtil;
import cc.mrbird.febs.common.utils.RedisUtils;
import cc.mrbird.febs.dapp.chain.ChainEnum;
import cc.mrbird.febs.dapp.chain.ChainService;
import cc.mrbird.febs.dapp.chain.ContractChainService;
import cc.mrbird.febs.dapp.dto.RecordInPageDto;
import cc.mrbird.febs.dapp.dto.TransferDto;
import cc.mrbird.febs.dapp.dto.WalletOperateDto;
import cc.mrbird.febs.dapp.entity.*;
import cc.mrbird.febs.dapp.mapper.*;
import cc.mrbird.febs.dapp.service.DappWalletService;
import cc.mrbird.febs.dapp.vo.WalletInfoVo;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @author
 * @date 2022-03-18
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class DappWalletServiceImpl implements DappWalletService {
 
    private final DappMemberDao dappMemberDao;
    private final DappWalletMineDao dappWalletMineDao;
    private final DappWalletCoinDao dappWalletCoinDao;
    private final DappFundFlowDao dappFundFlowDao;
    private final DappAccountMoneyChangeDao dappAccountMoneyChangeDao;
    private final RedisUtils redisUtils;
 
    @Override
    public WalletInfoVo walletInfo() {
        DappMemberEntity member = LoginUserUtil.getAppUser();
 
        Map<String, BigDecimal> map = dappFundFlowDao.selectAmountTotalByType(member.getId());
        WalletInfoVo walletInfo = new WalletInfoVo();
        List<DappMemberEntity> direct = dappMemberDao.selectChildMemberDirectOrNot(member.getInviteId(), 1);
        List<DappMemberEntity> notDirect = dappMemberDao.selectChildMemberDirectOrNot(member.getInviteId(), 2);
        BigDecimal childHoldAmount = dappMemberDao.selectChildHoldAmount(member.getInviteId());
 
        walletInfo.setTotalChild(notDirect.size());
        walletInfo.setDirectCnt(direct.size());
        walletInfo.setTotalChildCoin(childHoldAmount);
        walletInfo.setTeamReward(map.get("teamReward"));
        walletInfo.setMiningAmount(map.get("mine"));
        walletInfo.setInviteId(member.getInviteId());
        return walletInfo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void change(WalletOperateDto walletOperateDto) {
        DappMemberEntity member = LoginUserUtil.getAppUser();
 
        BigDecimal ethUsdtPrice = (BigDecimal) redisUtils.get(AppContants.REDIS_KEY_ETH_NEW_PRICE);
 
        DappWalletMineEntity walletMine = dappWalletMineDao.selectByMemberId(member.getId());
        if (walletOperateDto.getAmount().compareTo(walletMine.getAvailableAmount()) > 0) {
            throw new FebsException("可用金额不足");
        }
 
        DappFundFlowEntity fund = new DappFundFlowEntity(member.getId(), walletOperateDto.getAmount(), AppContants.MONEY_TYPE_CHANGE, null, null);
        dappFundFlowDao.insert(fund);
 
        BigDecimal preEthAmount = walletMine.getAvailableAmount();
 
        // TODO 并发加悲观锁
        // 更新eth金额
        walletMine.setAvailableAmount(walletMine.getAvailableAmount().subtract(walletOperateDto.getAmount()));
        dappWalletMineDao.updateById(walletMine);
 
        DappWalletCoinEntity walletCoin = dappWalletCoinDao.selectByMemberId(member.getId());
        BigDecimal preUsdtAmount = walletCoin.getAvailableAmount();
 
        // 更新usdt金额
        BigDecimal usdt = walletOperateDto.getAmount().multiply(ethUsdtPrice);
        walletCoin.setAvailableAmount(walletCoin.getAvailableAmount().add(usdt));
        walletCoin.setTotalAmount(walletCoin.getTotalAmount().add(usdt));
        dappWalletCoinDao.updateById(walletCoin);
 
        DappAccountMoneyChangeEntity ethChange = new DappAccountMoneyChangeEntity(member.getId(), preEthAmount, walletOperateDto.getAmount(), walletMine.getAvailableAmount(), "ETH兑换USDT-ETH, 兑换价格为:" + ethUsdtPrice, AppContants.MONEY_TYPE_CHANGE);
        DappAccountMoneyChangeEntity usdtChange = new DappAccountMoneyChangeEntity(member.getId(), preUsdtAmount, usdt, walletCoin.getAvailableAmount(), "ETH兑换USDT-USDT, 兑换价格为:" + ethUsdtPrice, AppContants.MONEY_TYPE_CHANGE);
        dappAccountMoneyChangeDao.insert(ethChange);
        dappAccountMoneyChangeDao.insert(usdtChange);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void withdraw(WalletOperateDto walletOperateDto) {
        DappMemberEntity member = LoginUserUtil.getAppUser();
 
        List<DappFundFlowEntity> fundFlows = dappFundFlowDao.selectListForMemberAndDay(member.getId(), 2);
        if (CollUtil.isNotEmpty(fundFlows)) {
            throw new FebsException("一天只能提现一次");
        }
 
        DappWalletCoinEntity walletCoin = dappWalletCoinDao.selectByMemberId(member.getId());
        if (walletOperateDto.getAmount().compareTo(walletCoin.getAvailableAmount()) > 0) {
            throw new FebsException("可用金额不足");
        }
 
        Integer fee = (Integer) redisUtils.get(AppContants.REDIS_KEY_CHANGE_FEE);
 
        //TODO 并发加悲观锁
        BigDecimal preAmount = walletCoin.getAvailableAmount();
        walletCoin.setAvailableAmount(walletCoin.getAvailableAmount().subtract(walletOperateDto.getAmount()));
        walletCoin.setFrozenAmount(walletCoin.getFrozenAmount().add(walletOperateDto.getAmount()));
        dappWalletCoinDao.updateById(walletCoin);
 
        DappFundFlowEntity fund = new DappFundFlowEntity(member.getId(), walletOperateDto.getAmount(), AppContants.MONEY_TYPE_WITHDRAWAL, 1, new BigDecimal(fee));
        dappFundFlowDao.insert(fund);
 
        DappAccountMoneyChangeEntity usdtChange = new DappAccountMoneyChangeEntity(member.getId(), preAmount, walletOperateDto.getAmount(), walletCoin.getAvailableAmount(), "USDT申请提现", AppContants.MONEY_TYPE_WITHDRAWAL);
        dappAccountMoneyChangeDao.insert(usdtChange);
    }
 
    @Override
    public List<DappFundFlowEntity> recordInPage(RecordInPageDto recordInPageDto) {
        Page<DappFundFlowEntity> page = new Page<>(recordInPageDto.getPageNum(), recordInPageDto.getPageSize());
 
        DappMemberEntity member = LoginUserUtil.getAppUser();
        DappFundFlowEntity dappFundFlowEntity = new DappFundFlowEntity();
        if (recordInPageDto.getType() != null && recordInPageDto.getType() != 0) {
            dappFundFlowEntity.setType(recordInPageDto.getType());
        }
        dappFundFlowEntity.setMemberId(member.getId());
        IPage<DappFundFlowEntity> records = dappFundFlowDao.selectInPage(page, dappFundFlowEntity);
        return records.getRecords();
    }
 
    @Override
    public IPage<DappFundFlowEntity> fundFlowInPage(DappFundFlowEntity dappFundFlowEntity, QueryRequest request) {
        Page<DappFundFlowEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
        return dappFundFlowDao.selectInPage(page, dappFundFlowEntity);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void withdrawAgreeOrNot(Long id, int type) {
        DappFundFlowEntity fundFlow = dappFundFlowDao.selectById(id);
        if (fundFlow == null) {
            throw new FebsException("数据不存在");
        }
 
        DappWalletCoinEntity walletCoin = dappWalletCoinDao.selectByMemberId(fundFlow.getMemberId());
        if (type == 1) {
            walletCoin.setFrozenAmount(walletCoin.getFrozenAmount().subtract(fundFlow.getAmount()));
            walletCoin.setTotalAmount(walletCoin.getTotalAmount().subtract(fundFlow.getAmount()));
            fundFlow.setStatus(DappFundFlowEntity.WITHDRAW_STATUS_AGREE);
        } else if (type == 2) {
            BigDecimal preAmount = walletCoin.getAvailableAmount();
 
            walletCoin.setFrozenAmount(walletCoin.getFrozenAmount().subtract(fundFlow.getAmount()));
            walletCoin.setAvailableAmount(walletCoin.getAvailableAmount().add(fundFlow.getAmount()));
 
            DappAccountMoneyChangeEntity accountMoneyChange = new DappAccountMoneyChangeEntity(walletCoin.getMemberId(), preAmount, fundFlow.getAmount(), walletCoin.getAvailableAmount(), "提现申请被驳回", 2);
            fundFlow.setStatus(DappFundFlowEntity.WITHDRAW_STATUS_DISAGREE);
 
            dappAccountMoneyChangeDao.insert(accountMoneyChange);
        } else {
            throw new FebsException("参数错误");
        }
 
        dappWalletCoinDao.updateById(walletCoin);
        dappFundFlowDao.updateById(fundFlow);
    }
 
    @Override
    public IPage<DappWalletCoinEntity> walletCoinInPage(DappWalletCoinEntity walletCoin, QueryRequest request) {
        Page<DappWalletCoinEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
        return dappWalletCoinDao.selectInPage(walletCoin, page);
    }
 
    @Override
    public IPage<DappWalletMineEntity> walletMineInPage(DappWalletMineEntity walletMine, QueryRequest request) {
        Page<DappWalletMineEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
        return dappWalletMineDao.selectInPage(walletMine, page);
    }
 
    @Override
    public IPage<DappAccountMoneyChangeEntity> accountMoneyChangeInPage(DappAccountMoneyChangeEntity change, QueryRequest request) {
        Page<DappAccountMoneyChangeEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
        return dappAccountMoneyChangeDao.selectInPage(change, page);
    }
 
    @Override
    public Long transfer(TransferDto transferDto) {
        DappMemberEntity member = LoginUserUtil.getAppUser();
 
        if (member.getActiveStatus() == 2) {
            throw new FebsException("请联系邀请人转币激活");
        }
 
        // 每日出U剩余量(卖币)
        BigDecimal usdtRemain = (BigDecimal) redisUtils.get(AppContants.REDIS_KEY_USDT_OUT_LIMIT_REMAIN);
        // 用户24小时可出售量
        BigDecimal saleCoinRemain = (BigDecimal) redisUtils.get(AppContants.REDIS_KEY_COIN_REMAIN + member.getAddress());
        BigDecimal buyCoinRemain = (BigDecimal) redisUtils.get(AppContants.REDIS_KEY_TRANSFER_POOL_VOL_REMAIN);
        // 铸池中的币的剩余量
        BigDecimal makeCoinRemain = (BigDecimal) redisUtils.get(AppContants.REDIS_KEY_MAKE_POOL_CNT);
 
        String hasStart = redisUtils.getString(AppContants.SYSTEM_START_FLAG);
        if (transferDto.getId() == null) {
            if (DappFundFlowEntity.TYPE_SALE == transferDto.getType()) {
                if (!"start".equals(hasStart)) {
                    throw new FebsException("系统还未启动");
                }
 
                if (transferDto.getAmount().multiply(transferDto.getPrice()).compareTo(usdtRemain) > 0) {
                    throw new FebsException("超过当日出U剩余量");
                }
 
                if (transferDto.getAmount().compareTo(saleCoinRemain) > 0) {
                    throw new FebsException("超出24小时内可售量");
                }
 
            } else if (DappFundFlowEntity.TYPE_BUY == transferDto.getType()) {
                if ("start".equals(hasStart)) {
                    if (transferDto.getAmount().compareTo(buyCoinRemain) > 0) {
                        throw new FebsException("超过当日可购买量");
                    }
                    // 如果系统还没有启动,则判断铸池中的剩余量
                } else {
                    if (transferDto.getAmount().compareTo(makeCoinRemain) > 0) {
                        throw new FebsException("可购数量不足");
                    }
                }
            }
 
            DappFundFlowEntity fundFlow = new DappFundFlowEntity(member.getId(), transferDto.getAmount(), transferDto.getType(), 1, transferDto.getFee(), transferDto.getTxHash());
            fundFlow.setNewestPrice(transferDto.getPrice());
            dappFundFlowDao.insert(fundFlow);
            return fundFlow.getId();
        }
 
        if ("success".equals(transferDto.getFlag())) {
            DappFundFlowEntity flow = dappFundFlowDao.selectById(transferDto.getId());
 
            flow.setFromHash(transferDto.getTxHash());
            dappFundFlowDao.updateById(flow);
 
            if (DappFundFlowEntity.TYPE_SALE == transferDto.getType()) {
                usdtRemain = usdtRemain.subtract(flow.getAmount().multiply(flow.getNewestPrice()));
                saleCoinRemain = saleCoinRemain.subtract(flow.getAmount());
 
                // 修改当日U剩余量
                redisUtils.set(AppContants.REDIS_KEY_USDT_OUT_LIMIT_REMAIN, usdtRemain);
                // 修改用户24小时可售量
                redisUtils.set(AppContants.REDIS_KEY_COIN_REMAIN + member.getAddress(), saleCoinRemain);
            } else if (DappFundFlowEntity.TYPE_BUY == transferDto.getType()) {
                if ("start".equals(hasStart)) {
                    buyCoinRemain = buyCoinRemain.subtract(flow.getAmount());
 
                    // 修改当日可购买量
                    redisUtils.set(AppContants.REDIS_KEY_TRANSFER_POOL_VOL_REMAIN, buyCoinRemain);
                } else {
                    makeCoinRemain = makeCoinRemain.subtract(flow.getAmount());
 
                    // 修改铸池量
                    redisUtils.set(AppContants.REDIS_KEY_MAKE_POOL_CNT, makeCoinRemain);
                }
            } else {
                throw new FebsException("参数错误");
            }
        } else {
            dappFundFlowDao.deleteById(transferDto.getId());
        }
        return null;
    }
 
    @Override
    public Map<String, BigDecimal> calPrice() {
        DappMemberEntity member = LoginUserUtil.getAppUser();
 
 
        String hasStart = redisUtils.getString(AppContants.SYSTEM_START_FLAG);
        if (!"start".equals(hasStart)) {
            HashMap<String, BigDecimal> map = new HashMap<>();
            map.put("x", new BigDecimal("0.075"));
            map.put("y", new BigDecimal("100000"));
            return map;
        }
 
        ContractChainService tfcInstance = ChainService.getInstance(ChainEnum.BSC_TFC.name());
        // u剩余数量
        BigDecimal sourceU = ChainService.getInstance(ChainEnum.BSC_USDT.name()).balanceOf(ChainEnum.BSC_USDT_SOURCE.getAddress());
        // 源池代币剩余数量
        BigDecimal sourceCoin = tfcInstance.balanceOf(ChainEnum.BSC_USDT_SOURCE.getAddress());
        // 用户代币剩余数量
        BigDecimal coin = tfcInstance.balanceOf(member.getAddress());
        BigDecimal x = sourceU.divide(sourceCoin, tfcInstance.decimals(), RoundingMode.HALF_UP);
        BigDecimal y = sourceU.divide(sourceCoin.add(coin), tfcInstance.decimals(), RoundingMode.HALF_UP);
 
        log.info("购买价格:{}, 出卖价格:{}", x, y);
        HashMap<String, BigDecimal> map = new HashMap<>();
        map.put("x", x);
        map.put("y", y);
        return map;
    }
}