forked from jup-ag/api-arbs-example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.mjs
185 lines (163 loc) · 4.77 KB
/
index.mjs
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
import dotenv from "dotenv";
import bs58 from "bs58";
import {
Connection,
Keypair,
Transaction,
PublicKey,
SystemProgram,
} from "@solana/web3.js";
import got from "got";
import { Wallet } from "@project-serum/anchor";
import promiseRetry from "promise-retry";
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
Token,
TOKEN_PROGRAM_ID,
} from "@solana/spl-token";
console.log({ dotenv });
dotenv.config();
const connection = new Connection("https://mercurial.rpcpool.com");
const wallet = new Wallet(
Keypair.fromSecretKey(bs58.decode(process.env.PRIVATE_KEY || ""))
);
const USDC_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const SOL_MINT = "So11111111111111111111111111111111111111112";
// wsol account
const createWSolAccount = async () => {
const wsolAddress = await Token.getAssociatedTokenAddress(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
new PublicKey(SOL_MINT),
wallet.publicKey
);
const wsolAccount = await connection.getAccountInfo(wsolAddress);
if (!wsolAccount) {
const transaction = new Transaction({
feePayer: wallet.publicKey,
});
const instructions = [];
instructions.push(
await Token.createAssociatedTokenAccountInstruction(
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
new PublicKey(SOL_MINT),
wsolAddress,
wallet.publicKey,
wallet.publicKey
)
);
// fund 1 sol to the account
instructions.push(
SystemProgram.transfer({
fromPubkey: wallet.publicKey,
toPubkey: wsolAddress,
lamports: 1_000_000_000, // 1 sol
})
);
instructions.push(
// This is not exposed by the types, but indeed it exists
Token.createSyncNativeInstruction(TOKEN_PROGRAM_ID, wsolAddress)
);
transaction.add(...instructions);
transaction.recentBlockhash = await (
await connection.getRecentBlockhash()
).blockhash;
transaction.partialSign(wallet.payer);
const result = await connection.sendTransaction(transaction, [
wallet.payer,
]);
console.log({ result });
}
return wsolAccount;
};
const getCoinQuote = (inputMint, outputMint, amount) =>
got
.get(
`https://quote-api.jup.ag/v1/quote?outputMint=${outputMint}&inputMint=${inputMint}&amount=${amount}&slippage=0.2`
)
.json();
const getTransaction = (route) => {
return got
.post("https://quote-api.jup.ag/v1/swap", {
json: {
route: route,
userPublicKey: wallet.publicKey.toString(),
// to make sure it doesnt close the sol account
wrapUnwrapSOL: false,
},
})
.json();
};
const getConfirmTransaction = async (txid) => {
const res = await promiseRetry(
async (retry, attempt) => {
let txResult = await connection.getTransaction(txid, {
commitment: "confirmed",
});
if (!txResult) {
const error = new Error("Transaction was not confirmed");
error.txid = txid;
retry(error);
return;
}
return txResult;
},
{
retries: 40,
minTimeout: 500,
maxTimeout: 1000,
}
);
if (res.meta.err) {
throw new Error("Transaction failed");
}
return txid;
};
// require wsol to start trading, this function create your wsol account and fund 1 SOL to it
await createWSolAccount();
// initial 20 USDC for quote
const initial = 20_000_000;
while (true) {
// 0.1 SOL
const usdcToSol = await getCoinQuote(USDC_MINT, SOL_MINT, initial);
const solToUsdc = await getCoinQuote(
SOL_MINT,
USDC_MINT,
usdcToSol.data[0].outAmount
);
// when outAmount more than initial
if (solToUsdc.data[0].outAmount > initial) {
await Promise.all(
[usdcToSol.data[0], solToUsdc.data[0]].map(async (route) => {
const { setupTransaction, swapTransaction, cleanupTransaction } =
await getTransaction(route);
await Promise.all(
[setupTransaction, swapTransaction, cleanupTransaction]
.filter(Boolean)
.map(async (serializedTransaction) => {
// get transaction object from serialized transaction
const transaction = Transaction.from(
Buffer.from(serializedTransaction, "base64")
);
// perform the swap
// Transaction might failed or dropped
const txid = await connection.sendTransaction(
transaction,
[wallet.payer],
{
skipPreflight: true,
}
);
try {
await getConfirmTransaction(txid);
console.log(`Success: https://solscan.io/tx/${txid}`);
} catch (e) {
console.log(`Failed: https://solscan.io/tx/${txid}`);
}
})
);
})
);
}
}