xiaoyong931011
2023-07-31 e6d01c8312b6adb1db73cebea9e8293a44267ee8
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
package cc.mrbird.febs.dapp.contract;
 
import cc.mrbird.febs.common.contants.AppContants;
import cc.mrbird.febs.common.contants.SystemConstants;
import cc.mrbird.febs.common.service.RedisService;
import cc.mrbird.febs.dapp.entity.DataDictionaryCustom;
import cc.mrbird.febs.dapp.enumerate.DataDictionaryEnum;
import cc.mrbird.febs.dapp.mapper.DataDictionaryCustomMapper;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import cc.mrbird.febs.dapp.entity.DappFundFlowEntity;
import cc.mrbird.febs.dapp.entity.DappMemberEntity;
import cc.mrbird.febs.dapp.entity.DappSystemProfit;
import cc.mrbird.febs.dapp.mapper.DappFundFlowDao;
import cc.mrbird.febs.dapp.mapper.DappMemberDao;
import cc.mrbird.febs.dapp.mapper.DappSystemProfitDao;
import cc.mrbird.febs.rabbit.producer.ChainProducer;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.DefaultBlockParameterNumber;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.tx.gas.StaticGasProvider;
import org.web3j.utils.Convert;
 
import java.math.BigInteger;
import java.util.List;
 
 
@Component
public class ContractMain {
 
    @Autowired
    private ChainProducer chainProducer;
 
    @Autowired
    private SystemConstants systemConstants;
 
    private static Web3j web3;
 
    @Autowired
    private RedisService redisService;
 
    private static Web3j getInstance() {
        if (web3 == null) {
            HttpService httpService = new HttpService(blockchainNode);
            web3 = Web3j.build(httpService);
        }
        return web3;
    }
    // gas费用单价
    public static final BigInteger GAS_PRICE = Convert.toWei(getGas(), Convert.Unit.GWEI).toBigInteger();
    // gas费用最大值
    public static final BigInteger GAS_LIMIT = Convert.toWei("100000", Convert.Unit.WEI).toBigInteger();
    private static StaticGasProvider getStaticGasProvider(){
        return new StaticGasProvider(GAS_PRICE,GAS_LIMIT);
    }
 
    private static String getGas() {
        String gas = "5";
//        try{
//            String resp = HttpUtil.get("https://gbsc.blockscan.com/gasapi.ashx?apikey=key&method=gasoracle");
//            JSONObject data = JSONObject.parseObject(resp);
//            gas = data.getString("FastGasPrice");
//        }catch (Exception exception) {
//            exception.printStackTrace();
//        }
        return StrUtil.isBlank(gas) ? "5" : gas;
    }
 
    private static Web3j getInstanceScope() {
 
        HttpService httpService = new HttpService(blockchainNode);
        return Web3j.build(httpService);
    }
 
    // 区块链节点地址 TODO
//    private static String blockchainNode = "https://bsc-dataseed.binance.org";
    private static String blockchainNode = "https://bsc-dataseed1.ninicoin.io";
 
    // 合约地址 TODO
//    private static String contractAddr = "0xb5a1aC0fA05BFb8ad16B231e84b0bAC1d46eAfD0";//测试
    private static String contractAddr = "0x532B0F9554D92b8BF1bdE85DD4E8b86E4228DE27";
 
    // 操作账号 手续费钱包地址的私钥(合约里会把手续费转到你这个私钥地址上) 用于操作合约内方法 TODO
    private static String privateKey = "221be67f85375a5af6dd0f4b77fbe877ad2e57e05db201de1b1383fb76494d18";//测试
 
//    private static String privateKey = AppContants.FEE_ADDRESS_KEY.get("feeAddressKey").toString() ;
 
    private EthFilter getFilter(BigInteger startBlock) {
        if (startBlock != null) {
            EthFilter filter = new EthFilter(new DefaultBlockParameterNumber(startBlock),
                    DefaultBlockParameterName.LATEST, contractAddr);
            return filter;
        } else {
            return new EthFilter(DefaultBlockParameterName.EARLIEST,
                    DefaultBlockParameterName.LATEST, contractAddr);
        }
    }
 
 
    /**
     * 监听投注 参数是起始的区块值
     */
    public void listenBetting(BigInteger startBlock){
        System.out.println("启动投注监听事件");
        // 指定密钥文件并进行账号和密码的验证
        Credentials credentials = Credentials.create(privateKey);
        Abi contract = Abi.load(contractAddr, getInstanceScope(), credentials, new DefaultGasProvider());
        EthFilter filter = getFilter(startBlock);
        contract.bettingEventFlowable(filter).subscribe(e->{
            try {
                // 投注时填的注册码
                String regCode = e.regCode;
                // 投注人的地址
                String from = e.from;
                if(from==null){
                    // 为空则不进入后续逻辑
                    return;
                }
 
                // TODO 业务操作逻辑代码
                System.out.println("regCode:"+regCode+",address:"+from);
                // 更新区块编号 TODO
                redisService.set("BNB_BLOCK_NUMBER",e.log.getBlockNumber().intValue());
                //投注人
//                DappMemberEntity dappMemberEntity = dappMemberDao.selectByAddress(from, "BSC");
//                if(ObjectUtil.isNotEmpty(dappMemberEntity)){
//                    //投注人是否加入
//                    DappSystemProfit dappSystemProfit = dappSystemProfitDao.selectByMemberIdAndState(dappMemberEntity.getId(), DappSystemProfit.STATE_IN);
//                    if(ObjectUtil.isNotEmpty(dappSystemProfit)){
//                        List<DappFundFlowEntity> dappFundFlowEntities = dappFundFlowDao.selectListByState(DappFundFlowEntity.WITHDRAW_STATUS_ING);
//                        if(CollUtil.isNotEmpty(dappFundFlowEntities)){
//                            for(DappFundFlowEntity dappFundFlowEntity : dappFundFlowEntities){
//                                //发送转币消息
//                                chainProducer.sendBnbTransferMsg(dappFundFlowEntity.getId());
//                            }
//                        }
//                    }
//                }
            }catch (Exception exception) {
                exception.printStackTrace();
            }
        });
    }
 
    /**
     * 从合约内转币到制定地址
     */
    public String trans(BigInteger amount, String to1){
        String transactionHash = null;
        Credentials credentials = Credentials.create(privateKey);
        Abi contract = Abi.load(contractAddr, getInstance(), credentials, getStaticGasProvider());
        try {
            //BigInteger bigInteger = Convert.toWei(amount.toString(), Convert.Unit.ETHER).toBigInteger();
            TransactionReceipt send = contract.trans(amount, to1).send();
            if(ObjectUtil.isNotEmpty(send)){
                transactionHash = send.getTransactionHash();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return transactionHash;
    }
 
    public static void main(String[] args) {
        ContractMain contractMain = new ContractMain();
 
        String address = "0xA60AaC0da34C76F3f60207ee09e9F75043319ab4";
//        String address = "0x785D5Aa2951Ac4C6f28Dc593AF0b0536Dd3E82Fe";
        BigInteger bigInteger = new BigInteger(Convert.toWei("0.001", Convert.Unit.ETHER).setScale(0).toString());
        String hash = contractMain.trans(bigInteger,address);
        System.out.println(hash);
    }
}