springboot使用web3进行代币交换(uniswap)

springboot使用web3进行代币交换(uniswap),第1张

springboot使用web3进行代币交换(uniswap)
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.abi.FunctionEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Function;
import org.web3j.abi.datatypes.StaticArray;
import org.web3j.abi.datatypes.Type;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;

import io.renren.common.utils.R;
import net.sf.json.JSONObject;

@Service
public class Uniswap {
	private static final Logger log = LoggerFactory.getLogger(Uniswap.class);

	@Autowired
	private EthGas ethGas;

	@Autowired
	private EthAccount ethAccount;
	
	
	public R sendContract(BigInteger gasLimit,BigInteger gasPrice,String host, String privateKey, BigDecimal v, String contractAddress, BigInteger amountOutMin,
			String sendTokenContractAddress,String approveAddress) {
		
		Web3j web3j = Web3j.build(new HttpService(host));
		try {
			Credentials credentials = Credentials.create(privateKey);
			String fromAddress = credentials.getAddress();
			//获取交易次数
			EthGetTransactionCount ethGetTransactionCount = ethAccount.getTradeCount(web3j, privateKey);
			//错误返回
			if (ethGetTransactionCount.hasError()) {
				return R.error(ethGetTransactionCount.getError().getMessage());
			}
			BigInteger nonce = ethGetTransactionCount.getTransactionCount();
			//合约函数参数
			List addList = new ArrayList();
			addList.add(new Address(sendTokenContractAddress));
			addList.add(new Address(approveAddress));
			StaticArray address = new StaticArray(Address.class, addList) {
			};
			// BigInteger amountOutMin = Numeric.toBigInt("0x8d5ff4d17003f1000");
			if(gasPrice.compareTo(BigInteger.valueOf(0)) != 1) { //没有输入gas时查询当前链路的gas
				EthGasPrice ethGasPrice = ethGas.getGasPrice(web3j);
				if (ethGasPrice.hasError()) {
					return R.error(ethGasPrice.getError().getMessage());
				}
				gasPrice = ethGasPrice.getGasPrice();
			}
			//创建inputdata
			String data = createSwapMethod(amountOutMin, address, addList.size(), new Address(fromAddress),
					new Uint256(System.currentTimeMillis() / 1000 + 300));
//			EthEstimateGas ethEstimateGas = ethGas.getEthEstimateGas(web3j, fromAddress, contractAddress, data);
//			if (ethEstimateGas.hasError()) {
//				return R.error(ethEstimateGas.getError().getMessage());
//			}
//			BigInteger gasLimit = BigInteger.valueOf(910000);
			
			BigInteger value = Convert.toWei(String.valueOf(v.toString()), Convert.Unit.ETHER).toBigInteger();
			RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress,
					value, data);
			byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
			String hexValue = Numeric.toHexString(signedMessage);
			log.info("hexValue:{}", hexValue);
			//发送交易
			EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
			if (ethSendTransaction.hasError()) {
				return R.error(ethSendTransaction.getError().getMessage());
			}
			log.info("transactionHash:{}", JSONObject.fromObject(ethSendTransaction));
			String transactionHash = ethSendTransaction.getTransactionHash();
			log.info("transactionHash:{}", transactionHash);
			EthGetTransactionReceipt ethGetTransactionReceipt = web3j.ethGetTransactionReceipt(transactionHash)
					.sendAsync().get();
			log.info("EthGetTransactionReceipt:{}", JSONObject.fromObject(ethGetTransactionReceipt));
			if (ethGetTransactionReceipt.hasError()) {
				return R.error(ethGetTransactionReceipt.getError().getMessage());
			}
			return R.ok(transactionHash);
		} catch (Exception e) {
			// TODO: handle exception
			web3j.shutdown();
			return R.error(e.getMessage());
		}finally {
			web3j.shutdown();
		}

	}

	@SuppressWarnings("rawtypes")
	public static String createSwapMethod(BigInteger amountOutMin, StaticArray addressArray, int size,
			Address to, Uint256 deadline) {

		List parametersList = new ArrayList();
		parametersList.add(new Uint256(amountOutMin));
		parametersList.add(new Uint256(128));
		parametersList.add(to);
		parametersList.add(deadline);
		parametersList.add(new Uint256(BigInteger.valueOf(size)));
		parametersList.add(addressArray);
		List> outList = new ArrayList<>();
		Function function = new Function("swapExactETHForTokens", parametersList, outList);
		String encodedFunction = FunctionEncoder.encode(function);
		System.out.println(encodedFunction);
		//函数编码不正确,先替换
		return encodedFunction.replace("0x8fd067c2", "0x7ff36ab5");
	}

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5597936.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存