-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
298 lines (263 loc) · 10.7 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
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
import { Connection, PublicKey } from '@solana/web3.js';
import { Address, AddressUtil } from "@orca-so/common-sdk";
import { swapQuote } from "./markets/orca_whirpools/client/orcaSwapQuotes";
import { InputInfosMeteora, InputWhirpoolsTickArrays, InputInfos as OrcaInputInfos } from "./markets/orca_whirpools/client/types";
import { InputInfos as RaydiumInputInfos } from "./markets/raydium/client/types";
import { quoteSwapOnlyAmm } from "./markets/raydium/client/raydiumSwapQuote";
import { BigNumberish, Percent, Token, TokenAmount } from '@raydium-io/raydium-sdk';
import { quoteSwapMeteora } from './markets/meteora/client/meteoraSwapQuote';
import { SwapQuote } from './markets/meteora/dlmm-sdk/ts-client/src/dlmm/types';
import { PDAUtil, SwapUtils, buildDefaultAccountFetcher } from '@orca-so/whirlpools-sdk';
const { createServer, http } = require("http");
const { Server } = require("socket.io");
const app = require('./app');
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*", // Allow all origins. Adjust as needed for security.
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
console.log("new socket connected");
socket.on('orca_quote', async (json) => {
console.log(json.poolId);
console.log(json.amountIn);
console.log(json.tokenInKey);
console.log(json.tokenOutKey);
try {
let inputParams: OrcaInputInfos = {
pool_id: json.poolId,
tokenInKey: json.tokenInKey,
tokenInDecimals: json.tokenInDecimals,
tokenInSymbol: json.tokenInSymbol,
tokenOutKey: json.tokenOutKey,
tokenOutDecimals: json.tokenOutDecimals,
tokenOutSymbol: json.tokenOutSymbol,
tickSpacing: json.tickSpacing,
amountIn: json.amountIn,
}
let result = await swapQuote(inputParams);
socket.emit('orca_quote_res', {
amountIn: result.amountIn,
estimatedAmountOut: result.estimatedAmountOut,
estimatedMinAmountOut: result.estimatedMinAmountOut,
});
} catch (error) {
console.log("🔴🔴 Error in Orca Simulation");
console.log(error);
socket.emit('orca_quote_res', {
amountIn: error,
estimatedAmountOut: error,
estimatedMinAmountOut: error,
});
}
});
socket.on("disconnect", (reason) => {
console.log(`Socket disconnected due to ${reason}`);
});
socket.on("error", (error) => {
console.log(`Socket error: ${error}`);
});
});
//Add this line
app.set("socket", io);
const normalizePort = (val: any) => {
const port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
httpServer.listen(port);
const errorHandler = (error: any) => {
if (error.syscall !== 'listen') {
throw error;
}
const address = httpServer.address();
const bind = typeof address === 'string' ? 'pipe ' + address : 'port: ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges.');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use.');
process.exit(1);
break;
default:
throw error;
}
};
httpServer.on('error', errorHandler);
httpServer.on('listening', () => {
const address = httpServer.address();
const bind = typeof address === 'string' ? 'pipe ' + address : 'port ' + port;
console.log('✅ Listening on ' + bind);
});
// app.use((request: any, response: any) => {
// response.json({ message: 'Hey! This is your server response baby!' });
// });
app.get('/orca_quote', async function (req: any, res: any) {
let url: string = req.originalUrl;
console.log(url);
console.log("Pool address = ", req.query.poolId);
//Exemple URL: http://localhost:3000/orca_quote?poolId=EzCFMMo43qLLkYQqhLG8Kjj4UL3Dwvk2paf7yqB575KP&tokenInKey=So11111111111111111111111111111111111111112&tokenInDecimals=9&tokenOutKey=JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN&tokenOutDecimals=6&tickSpacing=8&amountIn=1
try {
let inputParams: OrcaInputInfos = {
pool_id: req.query.poolId,
tokenInKey: req.query.tokenInKey,
tokenInDecimals: req.query.tokenInDecimals,
tokenOutSymbol: req.query.tokenOutSymbol,
tokenOutKey: req.query.tokenOutKey,
tokenOutDecimals: req.query.tokenOutDecimals,
tokenInSymbol: req.query.tokenInSymbol,
tickSpacing: req.query.tickSpacing,
amountIn: req.query.amountIn,
}
let result = await swapQuote(inputParams);
res.json({
amountIn: result.amountIn,
estimatedAmountOut: result.estimatedAmountOut,
estimatedMinAmountOut: result.estimatedMinAmountOut,
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
} catch (error) {
console.log("🔴🔴 Error in Orca Simulation");
res.json({
error: error.toString(),
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
}
});
app.get('/raydium_quote', async function (req: any, res: any) {
let url: string = req.originalUrl;
console.log(url);
console.log("Pool address = ", req.query.poolKeys);
//Exemple URL: http://localhost:3000/raydium_quote?poolKeys=58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2&amountIn=1000000¤cyIn=So11111111111111111111111111111111111111112&decimalsIn=9¤cyOut=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v&decimalsOut=6
try {
let inputToken: Token = new Token(
"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8", //Raydium Program Id
req.query.currencyIn,
Number(req.query.decimalsIn),
);
let outputToken: Token = new Token(
"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8", //Raydium Program Id
req.query.currencyOut,
Number(req.query.decimalsOut),
);
// let amountInAtDecimals = Number(req.query.amountIn) * Math.pow(10, Number(req.query.decimalsIn));
let tokenAmount: TokenAmount = new TokenAmount(
inputToken,
req.query.amountIn
);
let slippage: Percent = new Percent(1, 100); //1% Slippage
let inputParams: RaydiumInputInfos = {
outputToken: outputToken,
targetPool: req.query.poolKeys,
inputTokenAmount: tokenAmount,
slippage: slippage,
symbolTokenIn: req.query.symbolTokenIn,
symbolTokenOut: req.query.symbolTokenOut,
}
let result = await quoteSwapOnlyAmm(inputParams);
res.json({
amountIn: req.query.amountIn,
estimatedAmountOut: result.amountOut,
estimatedMinAmountOut: result.minAmountOut
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
} catch (error) {
console.log("🔴🔴 Error in Raydium Simulation");
console.log(error);
res.json({
error: error.toString(),
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
}
});
app.get('/meteora_quote', async function (req: any, res: any) {
//Exemple URL: http://localhost:3000/meteora_quote?poolId=9H7BB44QhZs6H4GP8XvW7Kq1b9PnDC5UAyaPoqYHoV9f&token0to1=true&amountIn=207139234106450&tokenInSymbol=GME&tokenOutSymbol=SOL
try {
let url: string = req.originalUrl;
console.log(url);
console.log("Pool address = ", req.query.poolId);
if (req.query.token0to1 != "true" && req.query.token0to1 != "false") {
throw new Error("Bad boolean on Meteora request");
}
let inputParams: InputInfosMeteora = {
pool_id: req.query.poolId,
token0to1: req.query.token0to1 == "true" ? true : false,
amountIn: req.query.amountIn,
tokenInSymbol: req.query.tokenInSymbol,
tokenOutSymbol: req.query.tokenOutSymbol,
}
let result = await quoteSwapMeteora(inputParams);
res.json({
amountIn: result.consumedInAmount,
estimatedAmountOut: result.amountOut,
estimatedMinAmountOut: result.minAmountOut
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
} catch (error) {
console.log("🔴🔴 Error in Meteora Simulation");
console.log(error);
res.json({
error: error.toString(),
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
}
});
app.get('/whirpools_tick_arrays', async function (req: any, res: any) {
//Exemple URL: http://localhost:3000/whirpools_tick_arrays?tickCurrentIndex=-29686&tickSpacing=8&aToB=true&programId=whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc&whirlpoolAddress=4E6q7eJE6vBNdquqzYYi5gvzd5MNpwiQKhjbRTRQGuQd
try {
let url: string = req.originalUrl;
console.log(url);
console.log("Get tick arrays");
console.log("Pool address = ", req.query.whirlpoolAddress);
// tickCurrentIndex: number,
// tickSpacing: number,
// aToB: boolean,
// programId: PublicKey,
// whirlpoolAddress: PublicKey,
// fetcher: WhirlpoolAccountFetcherInterface,
// opts?: WhirlpoolAccountFetchOptions
let inputParams: InputWhirpoolsTickArrays = {
tickCurrentIndex: req.query.tickCurrentIndex,
tickSpacing: req.query.tickSpacing,
aToB: req.query.aToB,
programId: req.query.programId,
whirlpoolAddress: req.query.whirlpoolAddress,
}
let connection = new Connection(process.env.ANCHOR_PROVIDER_URL);
let fetcher = buildDefaultAccountFetcher(connection);
let result = await SwapUtils.getTickArrays(
+inputParams.tickCurrentIndex,
+inputParams.tickSpacing,
inputParams.aToB,
new PublicKey(inputParams.programId),
new PublicKey(inputParams.whirlpoolAddress),
fetcher
);
let oracle = PDAUtil.getOracle(new PublicKey(inputParams.programId), new PublicKey(inputParams.whirlpoolAddress));
res.json({
tick_array_0: result[0].address,
tick_array_1: result[1].address,
tick_array_2: result[2].address,
oracle: oracle.publicKey,
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
} catch (error) {
console.log("🔴🔴 Error in Get Whirpools tick arrays");
console.log(error);
res.json({
error: error.toString(),
});
console.log("------------------------------------------------------------------------------------------------------------------------------");
}
});