-
Notifications
You must be signed in to change notification settings - Fork 52
/
router.ts
410 lines (378 loc) · 10.3 KB
/
router.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import {
AccountInfo,
AddressLookupTableAccount,
Connection,
PublicKey,
TransactionInstruction,
TransactionMessage,
VersionedTransaction,
} from '@solana/web3.js';
import fetch from 'node-fetch';
import { createAssociatedTokenAccountIdempotentInstruction } from './utils';
export const MANGO_ROUTER_API_URL = 'https://api.mngo.cloud/router/v1';
export interface QuoteParams {
sourceMint: string;
destinationMint: string;
amount: number;
swapMode: SwapMode;
}
export declare type TokenMintAddress = string;
export interface Quote {
notEnoughLiquidity: boolean;
minInAmount?: number;
minOutAmount?: number;
inAmount: number;
outAmount: number;
feeAmount: number;
feeMint: TokenMintAddress;
feePct: number;
priceImpactPct: number;
}
export declare type QuoteMintToReferrer = Map<TokenMintAddress, string>;
export interface SwapParams {
sourceMint: string;
destinationMint: string;
userSourceTokenAccount: string;
userDestinationTokenAccount: string;
userTransferAuthority: string;
/**
* amount is used for instruction and can be null when it is an intermediate swap, only the first swap has an amount
*/
amount: number;
swapMode: SwapMode;
openOrdersAddress?: string;
quoteMintToReferrer?: QuoteMintToReferrer;
}
export declare type PlatformFee = {
feeBps: number;
feeAccount: string;
};
export interface ExactOutSwapParams extends SwapParams {
inAmount: number;
slippageBps: number;
platformFee?: PlatformFee;
overflowFeeAccount?: string;
}
export declare type AccountInfoMap = Map<string, AccountInfo<Buffer> | null>;
export declare type AmmLabel =
| 'Aldrin'
| 'Crema'
| 'Cropper'
| 'Cykura'
| 'DeltaFi'
| 'GooseFX'
| 'Invariant'
| 'Lifinity'
| 'Lifinity V2'
| 'Marinade'
| 'Mercurial'
| 'Meteora'
| 'Raydium'
| 'Raydium CLMM'
| 'Saber'
| 'Serum'
| 'Orca'
| 'Step'
| 'Penguin'
| 'Saros'
| 'Stepn'
| 'Orca (Whirlpools)'
| 'Sencha'
| 'Saber (Decimals)'
| 'Dradex'
| 'Balansol'
| 'Openbook'
| 'Unknown';
export interface TransactionFeeInfo {
signatureFee: number;
openOrdersDeposits: number[];
ataDeposits: number[];
totalFeeAndDeposits: number;
minimumSOLForTransaction: number;
}
export declare enum SwapMode {
ExactIn = 'ExactIn',
ExactOut = 'ExactOut',
}
export interface Fee {
amount: number;
mint: string;
pct: number;
}
export interface MarketInfo {
id: string;
inAmount: number;
inputMint: string;
label: string;
lpFee: Fee;
notEnoughLiquidity: boolean;
outAmount: number;
outputMint: string;
platformFee: Fee;
priceImpactPct: number;
}
export interface RouteInfo {
amount: number;
inAmount: number;
marketInfos: MarketInfo[];
otherAmountThreshold: number;
outAmount: number;
priceImpactPct: number;
slippageBps: number;
swapMode: SwapMode;
instructions?: TransactionInstruction[];
mints?: PublicKey[];
routerName?: 'Mango';
}
export type Routes = {
routes: RouteInfo[];
bestRoute: RouteInfo | null;
};
export type Token = {
address: string;
chainId: number;
decimals: number;
name: string;
symbol: string;
logoURI: string;
extensions: {
coingeckoId?: string;
};
tags: string[];
};
const fetchJupiterRoutes = async (
inputMint,
outputMint,
amount = '0',
slippage = 50,
swapMode = 'ExactIn',
feeBps = '0',
): Promise<Routes> => {
{
const paramsString = new URLSearchParams({
inputMint: inputMint.toString(),
outputMint: outputMint.toString(),
amount: amount.toString(),
slippageBps: Math.ceil(slippage * 100).toString(),
feeBps: feeBps.toString(),
swapMode,
}).toString();
const response = await fetch(
`https://quote-api.jup.ag/v4/quote?${paramsString}`,
);
const res = await response.json();
const data = res.data;
return {
routes: res.data as RouteInfo[],
bestRoute: (data.length ? data[0] : null) as RouteInfo | null,
};
}
};
const fetchMangoRoutes = async (
inputMint,
outputMint,
amount = '0',
slippage = 50,
swapMode = 'ExactIn',
feeBps = '0',
wallet = PublicKey.default,
): Promise<Routes> => {
{
const defaultOtherAmount =
swapMode === 'ExactIn' ? 0 : Number.MAX_SAFE_INTEGER;
const paramsString = new URLSearchParams({
inputMint: inputMint.toString(),
outputMint: outputMint.toString(),
amount: amount.toString(),
slippage: ((slippage * 1) / 100).toString(),
feeBps: feeBps.toString(),
mode: swapMode,
wallet: wallet.toString(),
otherAmountThreshold: defaultOtherAmount.toString(),
}).toString();
const response = await fetch(
`${MANGO_ROUTER_API_URL}/swap?${paramsString}`,
);
const res = await response.json();
const data: RouteInfo[] = res.map((route: any) => ({
...route,
priceImpactPct: route.priceImpact,
slippageBps: slippage,
marketInfos: route.marketInfos.map((mInfo: any) => ({
...mInfo,
lpFee: {
...mInfo.fee,
pct: mInfo.fee.rate,
},
})),
mints: route.mints.map((x: string) => new PublicKey(x)),
instructions: route.instructions.map((ix: any) => ({
...ix,
programId: new PublicKey(ix.programId),
data: Buffer.from(ix.data, 'base64'),
keys: ix.keys.map((key: any) => ({
...key,
pubkey: new PublicKey(key.pubkey),
})),
})),
routerName: 'Mango',
}));
return {
routes: data,
bestRoute: (data.length ? data[0] : null) as RouteInfo | null,
};
}
};
export const fetchRoutes = async (
inputMint,
outputMint,
amount = '0',
slippage = 50,
swapMode = 'ExactIn',
feeBps = '0',
wallet = PublicKey.default,
): Promise<Routes> => {
try {
const responses = await Promise.allSettled([
fetchMangoRoutes(
inputMint,
outputMint,
amount,
slippage,
swapMode,
feeBps,
wallet,
),
fetchJupiterRoutes(
inputMint,
outputMint,
amount,
slippage,
swapMode,
feeBps,
),
]);
const routes: RouteInfo[] = responses
.filter((x) => x.status === 'fulfilled' && x.value.bestRoute !== null)
.map((x) => (x as any).value.routes)
.flat();
const sortedBestQuoteFirst = routes.sort(
(a, b) =>
swapMode == 'ExactIn'
? Number(b.outAmount) - Number(a.outAmount) // biggest out
: Number(a.inAmount) - Number(b.inAmount), // smallest in
);
return {
routes: sortedBestQuoteFirst,
bestRoute: sortedBestQuoteFirst[0],
};
} catch (e) {
return {
routes: [],
bestRoute: null,
};
}
};
export const prepareMangoRouterInstructions = async (
selectedRoute: RouteInfo,
inputMint: PublicKey,
outputMint: PublicKey,
userPublicKey: PublicKey,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
if (!selectedRoute || !selectedRoute.mints || !selectedRoute.instructions) {
return [[], []];
}
const mintsToFilterOut = [inputMint, outputMint];
const filteredOutMints = [
...selectedRoute.mints.filter(
(routeMint) =>
!mintsToFilterOut.find((filterOutMint) =>
filterOutMint.equals(routeMint),
),
),
];
const additionalInstructions: TransactionInstruction[] = [];
for (const mint of filteredOutMints) {
const ix = await createAssociatedTokenAccountIdempotentInstruction(
userPublicKey,
userPublicKey,
mint,
);
additionalInstructions.push(ix);
}
const instructions = [
...additionalInstructions,
...selectedRoute.instructions,
];
return [instructions, []];
};
const deserializeJupiterIxAndAlt = async (
connection: Connection,
swapTransaction: string,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
const parsedSwapTransaction = VersionedTransaction.deserialize(
Buffer.from(swapTransaction, 'base64'),
);
const message = parsedSwapTransaction.message;
// const lookups = message.addressTableLookups
const addressLookupTablesResponses = await Promise.all(
message.addressTableLookups.map((alt) =>
connection.getAddressLookupTable(alt.accountKey),
),
);
const addressLookupTables: AddressLookupTableAccount[] =
addressLookupTablesResponses
.map((alt) => alt.value)
.filter((x): x is AddressLookupTableAccount => x !== null);
const decompiledMessage = TransactionMessage.decompile(message, {
addressLookupTableAccounts: addressLookupTables,
});
return [decompiledMessage.instructions, addressLookupTables];
};
export const fetchJupiterTransaction = async (
connection: Connection,
selectedRoute: RouteInfo,
userPublicKey: PublicKey,
slippage: number,
inputMint: PublicKey,
outputMint: PublicKey,
): Promise<[TransactionInstruction[], AddressLookupTableAccount[]]> => {
const transactions = await (
await fetch('https://quote-api.jup.ag/v4/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
// route from /quote api
route: selectedRoute,
// user public key to be used for the swap
userPublicKey,
// feeAccount is optional. Use if you want to charge a fee. feeBps must have been passed in /quote API.
// This is the ATA account for the output token where the fee will be sent to. If you are swapping from SOL->USDC then this would be the USDC ATA you want to collect the fee.
// feeAccount: 'fee_account_public_key',
slippageBps: Math.ceil(slippage * 100),
}),
})
).json();
const { swapTransaction } = transactions;
const [ixs, alts] = await deserializeJupiterIxAndAlt(
connection,
swapTransaction,
);
const isSetupIx = (pk: PublicKey): boolean =>
pk.toString() === 'ComputeBudget111111111111111111111111111111' ||
pk.toString() === 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
const isDuplicateAta = (ix: TransactionInstruction): boolean => {
return (
ix.programId.toString() ===
'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL' &&
(ix.keys[3].pubkey.toString() === inputMint.toString() ||
ix.keys[3].pubkey.toString() === outputMint.toString())
);
};
const filtered_jup_ixs = ixs
.filter((ix) => !isSetupIx(ix.programId))
.filter((ix) => !isDuplicateAta(ix));
return [filtered_jup_ixs, alts];
};