-
Notifications
You must be signed in to change notification settings - Fork 74
Open
Description
private static final RpcClient client = new RpcClient(Cluster.MAINNET);
private static Account signer = new Account(Base58.decode(SOLANA_SECRET_KEY));
public static void main(String[] args) {
try {
// Retrieve the block hash
String recentBlockHash = client.getApi().getLatestBlockhash().getValue().getBlockhash();
if (recentBlockHash == null || recentBlockHash.isEmpty()) {
throw new RuntimeException("Failed to fetch recent block hash");
}
// Specify the amount to swap (in wSOL)
BigDecimal desiredAmount = new BigDecimal("0.2"); // Amount of wSOL to buy
int wsolPrecision = 9; // wSOL precision
BigDecimal adjustedAmount = adjustForPrecision(desiredAmount, wsolPrecision);
// Prepare the parameters for the swap
Map<String, String> swapParams = new HashMap<>();
swapParams.put("chainId", chainId);
swapParams.put("fromTokenAddress", FROM_TOKEN_ADDRESS);
swapParams.put("toTokenAddress", TO_TOKEN_ADDRESS);
swapParams.put("amount", adjustedAmount.toPlainString());
swapParams.put("slippage", SLIPPAGE.toString());
swapParams.put("userWalletAddress", "");
// Get swap data from OKX
JSONObject swapResponse = getSwapData(swapParams);
System.out.println("OKX Swap Data: " + swapResponse);
// Extract transaction data (assuming it's base58 encoded)
String transactionData = swapResponse.getJSONArray("data").getJSONObject(0).getJSONObject("tx").getString("data");
byte[] data = Base58.decode(transactionData); // Decode the tx data
// Create the transaction instruction
PublicKey programId = new PublicKey("6m2CDdhRgxpH4WjvdzxAYbGxwdGUz5MziiL5jek2kBma"); // DEX program ID
List<AccountMeta> keys = Arrays.asList(
new AccountMeta(signer.getPublicKey(), true, true) // Signer account
);
TransactionInstruction instruction = new TransactionInstruction(programId, keys, data);
// Create the transaction
Transaction transaction = new Transaction();
transaction.addInstruction(instruction);
transaction.setRecentBlockHash(recentBlockHash);
// Sign the transaction
// transaction.sign(signer);
// Send the transaction
String txid = client.getApi().sendTransaction(transaction, signer);
System.out.println("Transaction ID: " + txid);
} catch (Exception e) {
e.printStackTrace();
}
}
Transaction ID: Ztmi9PgirAM29NcfW3GPzEuAjv1ZLfDD1HtZoNEfmo61Ua6VJ2fS4pHLYJYTrGwHDQK2vZWBmALtx1V7R8uTqeu
Metadata
Metadata
Assignees
Labels
No labels