当前位置:   article > 正文

springboot使用web3进行代币交换(uniswap)_springboot如何实现兑换外币业务

springboot如何实现兑换外币业务
  1. import java.math.BigDecimal;
  2. import java.math.BigInteger;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. import org.web3j.abi.FunctionEncoder;
  10. import org.web3j.abi.TypeReference;
  11. import org.web3j.abi.datatypes.Address;
  12. import org.web3j.abi.datatypes.Function;
  13. import org.web3j.abi.datatypes.StaticArray;
  14. import org.web3j.abi.datatypes.Type;
  15. import org.web3j.abi.datatypes.generated.Uint256;
  16. import org.web3j.crypto.Credentials;
  17. import org.web3j.crypto.RawTransaction;
  18. import org.web3j.crypto.TransactionEncoder;
  19. import org.web3j.protocol.Web3j;
  20. import org.web3j.protocol.core.methods.response.EthGasPrice;
  21. import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
  22. import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
  23. import org.web3j.protocol.core.methods.response.EthSendTransaction;
  24. import org.web3j.protocol.http.HttpService;
  25. import org.web3j.utils.Convert;
  26. import org.web3j.utils.Numeric;
  27. import io.renren.common.utils.R;
  28. import net.sf.json.JSONObject;
  29. @Service
  30. public class Uniswap {
  31. private static final Logger log = LoggerFactory.getLogger(Uniswap.class);
  32. @Autowired
  33. private EthGas ethGas;
  34. @Autowired
  35. private EthAccount ethAccount;
  36. /**
  37. *
  38. * @param gasLimit gaslimit
  39. * @param gasPrice gas费用
  40. * @param host 链路
  41. * @param privateKey 自己的私钥
  42. * @param v 要兑换的对应代币的
  43. * @param contractAddress 如用USDT兑换BTC,则此值是BTC的合约地址
  44. * @param amountOutMin 兑换代币的最小的个数
  45. * @param sendTokenContractAddress 如用USDT兑换BTC,则此值是USDT的合约地址
  46. * @param approveAddress approve合约地址,设置此值可以合约内直接确认,无需调钱包插件确认
  47. * @return
  48. */
  49. public R sendContract(BigInteger gasLimit,BigInteger gasPrice,String host, String privateKey, BigDecimal v, String contractAddress, BigInteger amountOutMin,
  50. String sendTokenContractAddress,String approveAddress) {
  51. Web3j web3j = Web3j.build(new HttpService(host));
  52. try {
  53. Credentials credentials = Credentials.create(privateKey);
  54. String fromAddress = credentials.getAddress();
  55. //获取交易次数
  56. EthGetTransactionCount ethGetTransactionCount = ethAccount.getTradeCount(web3j, privateKey);
  57. //错误返回
  58. if (ethGetTransactionCount.hasError()) {
  59. return R.error(ethGetTransactionCount.getError().getMessage());
  60. }
  61. BigInteger nonce = ethGetTransactionCount.getTransactionCount();
  62. //合约函数参数
  63. List<Address> addList = new ArrayList<Address>();
  64. addList.add(new Address(sendTokenContractAddress));
  65. addList.add(new Address(approveAddress));
  66. StaticArray<Address> address = new StaticArray<Address>(Address.class, addList) {
  67. };
  68. // BigInteger amountOutMin = Numeric.toBigInt("0x8d5ff4d17003f1000");
  69. if(gasPrice.compareTo(BigInteger.valueOf(0)) != 1) { //没有输入gas时查询当前链路的gas
  70. EthGasPrice ethGasPrice = ethGas.getGasPrice(web3j);
  71. if (ethGasPrice.hasError()) {
  72. return R.error(ethGasPrice.getError().getMessage());
  73. }
  74. gasPrice = ethGasPrice.getGasPrice();
  75. }
  76. //创建inputdata
  77. String data = createSwapMethod(amountOutMin, address, addList.size(), new Address(fromAddress),
  78. new Uint256(System.currentTimeMillis() / 1000 + 300));
  79. // EthEstimateGas ethEstimateGas = ethGas.getEthEstimateGas(web3j, fromAddress, contractAddress, data);
  80. // if (ethEstimateGas.hasError()) {
  81. // return R.error(ethEstimateGas.getError().getMessage());
  82. // }
  83. // BigInteger gasLimit = BigInteger.valueOf(910000);
  84. BigInteger value = Convert.toWei(String.valueOf(v.toString()), Convert.Unit.ETHER).toBigInteger();
  85. RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress,
  86. value, data);
  87. byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
  88. String hexValue = Numeric.toHexString(signedMessage);
  89. log.info("hexValue:{}", hexValue);
  90. //发送交易
  91. EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
  92. if (ethSendTransaction.hasError()) {
  93. return R.error(ethSendTransaction.getError().getMessage());
  94. }
  95. log.info("transactionHash:{}", JSONObject.fromObject(ethSendTransaction));
  96. String transactionHash = ethSendTransaction.getTransactionHash();
  97. log.info("transactionHash:{}", transactionHash);
  98. EthGetTransactionReceipt ethGetTransactionReceipt = web3j.ethGetTransactionReceipt(transactionHash)
  99. .sendAsync().get();
  100. log.info("EthGetTransactionReceipt:{}", JSONObject.fromObject(ethGetTransactionReceipt));
  101. if (ethGetTransactionReceipt.hasError()) {
  102. return R.error(ethGetTransactionReceipt.getError().getMessage());
  103. }
  104. return R.ok(transactionHash);
  105. } catch (Exception e) {
  106. // TODO: handle exception
  107. web3j.shutdown();
  108. return R.error(e.getMessage());
  109. }finally {
  110. web3j.shutdown();
  111. }
  112. }
  113. @SuppressWarnings("rawtypes")
  114. public static String createSwapMethod(BigInteger amountOutMin, StaticArray<Address> addressArray, int size,
  115. Address to, Uint256 deadline) {
  116. List<Type> parametersList = new ArrayList<Type>();
  117. parametersList.add(new Uint256(amountOutMin));
  118. parametersList.add(new Uint256(128));
  119. parametersList.add(to);
  120. parametersList.add(deadline);
  121. parametersList.add(new Uint256(BigInteger.valueOf(size)));
  122. parametersList.add(addressArray);
  123. List<TypeReference<?>> outList = new ArrayList<>();
  124. Function function = new Function("swapExactETHForTokens", parametersList, outList);
  125. String encodedFunction = FunctionEncoder.encode(function);
  126. System.out.println(encodedFunction);
  127. //函数编码不正确,先替换
  128. return encodedFunction.replace("0x8fd067c2", "0x7ff36ab5");
  129. }
  130. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/900103
推荐阅读
相关标签
  

闽ICP备14008679号