-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathindex.ts
143 lines (121 loc) · 4.29 KB
/
index.ts
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
import {
QuoteGetRequest,
QuoteResponse,
SwapResponse,
createJupiterApiClient,
} from "../src/index";
import { Connection, Keypair, VersionedTransaction } from "@solana/web3.js";
import { Wallet } from "@project-serum/anchor";
import bs58 from "bs58";
import { transactionSenderAndConfirmationWaiter } from "./utils/transactionSender";
import { getSignature } from "./utils/getSignature";
// If you have problem landing transactions, read this too: https://station.jup.ag/docs/apis/landing-transactions
// Make sure that you are using your own RPC endpoint. This RPC doesn't work.
// Helius and Triton have staked SOL and they can usually land transactions better.
const connection = new Connection(
"https://neat-hidden-sanctuary.solana-mainnet.discover.quiknode.pro/2af5315d336f9ae920028bbb90a73b724dc1bbed/"
);
const jupiterQuoteApi = createJupiterApiClient();
async function getQuote() {
const params: QuoteGetRequest = {
inputMint: "So11111111111111111111111111111111111111112",
outputMint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC
amount: 100000000, // 0.1 SOL
};
// get quote
const quote = await jupiterQuoteApi.quoteGet(params);
if (!quote) {
throw new Error("unable to quote");
}
return quote;
}
async function getSwapObj(wallet: Wallet, quote: QuoteResponse) {
// Get serialized transaction
const swapObj = await jupiterQuoteApi.swapPost({
swapRequest: {
quoteResponse: quote,
userPublicKey: wallet.publicKey.toBase58(),
dynamicComputeUnitLimit: true,
dynamicSlippage: {
// This will set an optimized slippage to ensure high success rate
maxBps: 300, // Make sure to set a reasonable cap here to prevent MEV
},
prioritizationFeeLamports: {
priorityLevelWithMaxLamports: {
maxLamports: 10000000,
priorityLevel: "veryHigh", // If you want to land transaction fast, set this to use `veryHigh`. You will pay on average higher priority fee.
},
},
},
});
return swapObj;
}
async function flowQuote() {
const quote = await getQuote();
console.dir(quote, { depth: null });
}
async function flowQuoteAndSwap() {
const wallet = new Wallet(
Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY || ""))
);
console.log("Wallet:", wallet.publicKey.toBase58());
const quote = await getQuote();
console.dir(quote, { depth: null });
const swapObj = await getSwapObj(wallet, quote);
console.dir(swapObj, { depth: null });
// Serialize the transaction
const swapTransactionBuf = Buffer.from(swapObj.swapTransaction, "base64");
var transaction = VersionedTransaction.deserialize(swapTransactionBuf);
// Sign the transaction
transaction.sign([wallet.payer]);
const signature = getSignature(transaction);
// We first simulate whether the transaction would be successful
const { value: simulatedTransactionResponse } =
await connection.simulateTransaction(transaction, {
replaceRecentBlockhash: true,
commitment: "processed",
});
const { err, logs } = simulatedTransactionResponse;
if (err) {
// Simulation error, we can check the logs for more details
// If you are getting an invalid account error, make sure that you have the input mint account to actually swap from.
console.error("Simulation Error:");
console.error({ err, logs });
return;
}
const serializedTransaction = Buffer.from(transaction.serialize());
const blockhash = transaction.message.recentBlockhash;
const transactionResponse = await transactionSenderAndConfirmationWaiter({
connection,
serializedTransaction,
blockhashWithExpiryBlockHeight: {
blockhash,
lastValidBlockHeight: swapObj.lastValidBlockHeight,
},
});
// If we are not getting a response back, the transaction has not confirmed.
if (!transactionResponse) {
console.error("Transaction not confirmed");
return;
}
if (transactionResponse.meta?.err) {
console.error(transactionResponse.meta?.err);
}
console.log(`https://solscan.io/tx/${signature}`);
}
export async function main() {
switch (process.env.FLOW) {
case "quote": {
await flowQuote();
break;
}
case "quoteAndSwap": {
await flowQuoteAndSwap();
break;
}
default: {
console.error("Please set the FLOW environment");
}
}
}
main();