forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswapUtils.ts
327 lines (297 loc) · 10 KB
/
swapUtils.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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { getAssociatedTokenAddress } from "@solana/spl-token";
import {
BlockhashWithExpiryBlockHeight,
Connection,
Keypair,
PublicKey,
RpcResponseAndContext,
SimulatedTransactionResponse,
TokenAmount,
VersionedTransaction,
} from "@solana/web3.js";
import { settings, elizaLogger } from "@elizaos/core";
const solAddress = settings.SOL_ADDRESS;
const SLIPPAGE = settings.SLIPPAGE;
const connection = new Connection(
settings.SOLANA_RPC_URL || "https://api.mainnet-beta.solana.com"
);
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function delayedCall<T>(
method: (...args: any[]) => Promise<T>,
...args: any[]
): Promise<T> {
await delay(150);
return method(...args);
}
export async function getTokenDecimals(
connection: Connection,
mintAddress: string
): Promise<number> {
const mintPublicKey = new PublicKey(mintAddress);
const tokenAccountInfo =
await connection.getParsedAccountInfo(mintPublicKey);
// Check if the data is parsed and contains the expected structure
if (
tokenAccountInfo.value &&
typeof tokenAccountInfo.value.data === "object" &&
"parsed" in tokenAccountInfo.value.data
) {
const parsedInfo = tokenAccountInfo.value.data.parsed?.info;
if (parsedInfo && typeof parsedInfo.decimals === "number") {
return parsedInfo.decimals;
}
}
throw new Error("Unable to fetch token decimals");
}
export async function getQuote(
connection: Connection,
baseToken: string,
outputToken: string,
amount: number
): Promise<any> {
const decimals = await getTokenDecimals(connection, baseToken);
const adjustedAmount = amount * 10 ** decimals;
const quoteResponse = await fetch(
`https://quote-api.jup.ag/v6/quote?inputMint=${baseToken}&outputMint=${outputToken}&amount=${adjustedAmount}&slippageBps=50`
);
const swapTransaction = await quoteResponse.json();
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
return new Uint8Array(swapTransactionBuf);
}
export const executeSwap = async (
transaction: VersionedTransaction,
type: "buy" | "sell"
) => {
try {
const latestBlockhash: BlockhashWithExpiryBlockHeight =
await delayedCall(connection.getLatestBlockhash.bind(connection));
const signature = await connection.sendTransaction(transaction, {
skipPreflight: false,
});
const confirmation = await connection.confirmTransaction(
{
signature,
lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
blockhash: latestBlockhash.blockhash,
},
"confirmed"
);
if (confirmation.value.err) {
elizaLogger.log("Confirmation error", confirmation.value.err);
throw new Error("Confirmation error");
} else {
if (type === "buy") {
elizaLogger.log(
"Buy successful: https://solscan.io/tx/${signature}"
);
} else {
elizaLogger.log(
"Sell successful: https://solscan.io/tx/${signature}"
);
}
}
return signature;
} catch (error) {
elizaLogger.log(error);
}
};
export const Sell = async (baseMint: PublicKey, wallet: Keypair) => {
try {
const tokenAta = await delayedCall(
getAssociatedTokenAddress,
baseMint,
wallet.publicKey
);
const tokenBalInfo: RpcResponseAndContext<TokenAmount> =
await delayedCall(
connection.getTokenAccountBalance.bind(connection),
tokenAta
);
if (!tokenBalInfo) {
elizaLogger.log("Balance incorrect");
return null;
}
const tokenBalance = tokenBalInfo.value.amount;
if (tokenBalance === "0") {
elizaLogger.warn(
`No token balance to sell with wallet ${wallet.publicKey}`
);
}
const sellTransaction = await getSwapTxWithWithJupiter(
wallet,
baseMint,
tokenBalance,
"sell"
);
// simulate the transaction
if (!sellTransaction) {
elizaLogger.log("Failed to get sell transaction");
return null;
}
const simulateResult: RpcResponseAndContext<SimulatedTransactionResponse> =
await delayedCall(
connection.simulateTransaction.bind(connection),
sellTransaction
);
if (simulateResult.value.err) {
elizaLogger.log("Sell Simulation failed", simulateResult.value.err);
return null;
}
// execute the transaction
return executeSwap(sellTransaction, "sell");
} catch (error) {
elizaLogger.log(error);
}
};
export const Buy = async (baseMint: PublicKey, wallet: Keypair) => {
try {
const tokenAta = await delayedCall(
getAssociatedTokenAddress,
baseMint,
wallet.publicKey
);
const tokenBalInfo: RpcResponseAndContext<TokenAmount> =
await delayedCall(
connection.getTokenAccountBalance.bind(connection),
tokenAta
);
if (!tokenBalInfo) {
elizaLogger.log("Balance incorrect");
return null;
}
const tokenBalance = tokenBalInfo.value.amount;
if (tokenBalance === "0") {
elizaLogger.warn(
`No token balance to sell with wallet ${wallet.publicKey}`
);
}
const buyTransaction = await getSwapTxWithWithJupiter(
wallet,
baseMint,
tokenBalance,
"buy"
);
// simulate the transaction
if (!buyTransaction) {
elizaLogger.log("Failed to get buy transaction");
return null;
}
const simulateResult: RpcResponseAndContext<SimulatedTransactionResponse> =
await delayedCall(
connection.simulateTransaction.bind(connection),
buyTransaction
);
if (simulateResult.value.err) {
elizaLogger.log("Buy Simulation failed", simulateResult.value.err);
return null;
}
// execute the transaction
return executeSwap(buyTransaction, "buy");
} catch (error) {
elizaLogger.log(error);
}
};
export const getSwapTxWithWithJupiter = async (
wallet: Keypair,
baseMint: PublicKey,
amount: string,
type: "buy" | "sell"
) => {
try {
switch (type) {
case "buy":
return fetchBuyTransaction(wallet, baseMint, amount);
case "sell":
return fetchSellTransaction(wallet, baseMint, amount);
default:
return fetchSellTransaction(wallet, baseMint, amount);
}
} catch (error) {
elizaLogger.log(error);
}
};
export const fetchBuyTransaction = async (
wallet: Keypair,
baseMint: PublicKey,
amount: string
) => {
try {
const quoteResponse = await (
await fetch(
`https://quote-api.jup.ag/v6/quote?inputMint=${solAddress}&outputMint=${baseMint.toBase58()}&amount=${amount}&slippageBps=${SLIPPAGE}`
)
).json();
const { swapTransaction } = await (
await fetch("https://quote-api.jup.ag/v6/swap", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
quoteResponse,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true,
dynamicComputeUnitLimit: true,
prioritizationFeeLamports: 100000,
}),
})
).json();
if (!swapTransaction) {
elizaLogger.log("Failed to get buy transaction");
return null;
}
// deserialize the transaction
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
const transaction =
VersionedTransaction.deserialize(swapTransactionBuf);
// sign the transaction
transaction.sign([wallet]);
return transaction;
} catch (error) {
elizaLogger.log("Failed to get buy transaction", error);
return null;
}
};
export const fetchSellTransaction = async (
wallet: Keypair,
baseMint: PublicKey,
amount: string
) => {
try {
const quoteResponse = await (
await fetch(
`https://quote-api.jup.ag/v6/quote?inputMint=${baseMint.toBase58()}&outputMint=${solAddress}&amount=${amount}&slippageBps=${SLIPPAGE}`
)
).json();
// get serialized transactions for the swap
const { swapTransaction } = await (
await fetch("https://quote-api.jup.ag/v6/swap", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
quoteResponse,
userPublicKey: wallet.publicKey.toString(),
wrapAndUnwrapSol: true,
dynamicComputeUnitLimit: true,
prioritizationFeeLamports: 52000,
}),
})
).json();
if (!swapTransaction) {
elizaLogger.log("Failed to get sell transaction");
return null;
}
// deserialize the transaction
const swapTransactionBuf = Buffer.from(swapTransaction, "base64");
const transaction =
VersionedTransaction.deserialize(swapTransactionBuf);
// sign the transaction
transaction.sign([wallet]);
return transaction;
} catch (error) {
elizaLogger.log("Failed to get sell transaction", error);
return null;
}
};