@minswap/noodles-sdk 0.0.12 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.cjs +1 -1687
  2. package/dist/index.js +1 -1512
  3. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -1,1512 +1 @@
1
- import { BluefinXTx, Config, buildTx, getQuote } from "@7kprotocol/sdk-ts/cjs";
2
- import { Transaction } from "@mysten/sui/transactions";
3
- import bignumber from "bignumber.js";
4
- import { Aftermath, Helpers } from "aftermath-ts-sdk";
5
- import { buildSwapPTBFromQuote, getCoins, getQuote as astros_aggregator_sdk_getQuote } from "@naviprotocol/astros-aggregator-sdk";
6
- import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk";
7
- import bn from "bn.js";
8
- import { AggregatorQuoter, Coin, Commission, CommissionType, TradeBuilder } from "@flowx-finance/sdk";
9
- import { fromBase64, normalizeStructTag } from "@mysten/sui/utils";
10
- import tiny_invariant from "@minswap/tiny-invariant";
11
- import { MemezPumpSDK } from "@interest-protocol/memez-fun-sdk";
12
- import { Network } from "@interest-protocol/sui-core-sdk";
13
- import { getFullnodeUrl } from "@mysten/sui/client";
14
- import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
15
- class _7k_SevenKAggregator {
16
- _config;
17
- _suiClient;
18
- constructor(config, suiClient){
19
- this._config = config;
20
- this._suiClient = suiClient;
21
- }
22
- async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
23
- try {
24
- if (this._config.sevenKApiKey) Config.setApiKey(this._config.sevenKApiKey);
25
- const tradeFeePercent = tradeFee ? tradeFee.tradeFeePercent : this._config.defaultTradeFee.tradeFeePercent;
26
- return getQuote({
27
- tokenIn: coinInType,
28
- tokenOut: coinOutType,
29
- amountIn: coinInAmount.toString(),
30
- commissionBps: 10000 * tradeFeePercent
31
- });
32
- } catch (_err) {
33
- return null;
34
- }
35
- }
36
- async getTransaction({ walletAddress, completeRoute, slippage, tradeFee }) {
37
- let tradeFeePercent;
38
- let tradeFeeRecipientAddress;
39
- if (tradeFee) {
40
- tradeFeePercent = tradeFee.tradeFeePercent;
41
- tradeFeeRecipientAddress = tradeFee.tradeFeeRecipientAddress;
42
- } else {
43
- tradeFeePercent = this._config.defaultTradeFee.tradeFeePercent;
44
- tradeFeeRecipientAddress = this._config.defaultTradeFee.tradeFeeRecipientAddress;
45
- }
46
- const transaction = await buildTx({
47
- quoteResponse: completeRoute,
48
- slippage,
49
- accountAddress: walletAddress,
50
- commission: {
51
- partner: tradeFeeRecipientAddress,
52
- commissionBps: 10000 * tradeFeePercent
53
- }
54
- });
55
- if (transaction.tx instanceof BluefinXTx) {
56
- const newTransaction = Transaction.from(transaction.tx.txBytes);
57
- return newTransaction.build({
58
- client: this._suiClient
59
- });
60
- }
61
- transaction.tx.setSender(walletAddress);
62
- return transaction.tx.build({
63
- client: this._suiClient
64
- });
65
- }
66
- }
67
- (function(SevenKAggregator) {
68
- function toCommonTradeRoutes(tradeRouteResponse) {
69
- const routes = [];
70
- if (!tradeRouteResponse.routes || 0 === tradeRouteResponse.routes.length) return null;
71
- for (const route of tradeRouteResponse.routes){
72
- const paths = [];
73
- const allTokenDecimal = {};
74
- for (const path of route.hops){
75
- for (const t of path.pool.allTokens)allTokenDecimal[t.address] = t.decimal;
76
- const pathDecimalIn = allTokenDecimal[path.tokenIn] ?? 0;
77
- const pathDecimalOut = allTokenDecimal[path.tokenOut] ?? 0;
78
- const pathAmountIn = BigInt(new bignumber(path.tokenInAmount).multipliedBy(10 ** pathDecimalIn).toFixed(0, 3));
79
- const pathAmountOut = BigInt(new bignumber(path.tokenOutAmount).multipliedBy(10 ** pathDecimalOut).toFixed(0, 3));
80
- paths.push({
81
- poolAddress: path.poolId,
82
- coinIn: path.tokenIn,
83
- coinOut: path.tokenOut,
84
- amountIn: pathAmountIn,
85
- amountOut: pathAmountOut
86
- });
87
- }
88
- if (0 === paths.length) continue;
89
- const routeDecimalIn = allTokenDecimal[route.tokenIn] ?? 0;
90
- const routeDecimalOut = allTokenDecimal[route.tokenOut] ?? 0;
91
- const routeAmountIn = BigInt(new bignumber(route.tokenInAmount).multipliedBy(10 ** routeDecimalIn).toFixed(0, 3));
92
- const routeAmountOut = BigInt(new bignumber(route.tokenOutAmount).multipliedBy(10 ** routeDecimalOut).toFixed(0, 3));
93
- routes.push({
94
- paths: paths,
95
- coinIn: route.tokenIn,
96
- coinOut: route.tokenOut,
97
- amountIn: routeAmountIn,
98
- amountOut: routeAmountOut
99
- });
100
- }
101
- if (0 === routes.length) return null;
102
- return {
103
- coinIn: tradeRouteResponse.tokenIn,
104
- coinOut: tradeRouteResponse.tokenOut,
105
- amountIn: BigInt(tradeRouteResponse.swapAmountWithDecimal),
106
- amountOut: BigInt(tradeRouteResponse.returnAmountWithDecimal),
107
- routes: routes
108
- };
109
- }
110
- SevenKAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
111
- })(_7k_SevenKAggregator || (_7k_SevenKAggregator = {}));
112
- class aftermath_AftermathAggregator {
113
- _config;
114
- _aftermathClient;
115
- _suiClient;
116
- constructor(config, suiClient){
117
- this._config = config;
118
- this._suiClient = suiClient;
119
- }
120
- async aftermathClient() {
121
- if (this._aftermathClient) return this._aftermathClient;
122
- if (this._config.aftermathApiEndpoint) this._aftermathClient = new Aftermath(this._config.aftermathApiEndpoint);
123
- else this._aftermathClient = new Aftermath("MAINNET");
124
- await this._aftermathClient.init();
125
- if (this._config.aftermathApiKey) {
126
- const keypair = Helpers.keypairFromPrivateKey(this._config.aftermathApiKey);
127
- await this._aftermathClient.Auth().init({
128
- async signMessageCallback ({ message }) {
129
- const { signature } = await keypair.signPersonalMessage(message);
130
- return {
131
- signature
132
- };
133
- },
134
- walletAddress: keypair.toSuiAddress()
135
- });
136
- }
137
- return this._aftermathClient;
138
- }
139
- async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
140
- let externalFee;
141
- externalFee = tradeFee ? {
142
- recipient: tradeFee.tradeFeeRecipientAddress,
143
- feePercentage: tradeFee.tradeFeePercent
144
- } : {
145
- recipient: this._config.defaultTradeFee.tradeFeeRecipientAddress,
146
- feePercentage: this._config.defaultTradeFee.tradeFeePercent
147
- };
148
- const client = await this.aftermathClient();
149
- return client.Router().getCompleteTradeRouteGivenAmountIn({
150
- coinInAmount,
151
- coinInType,
152
- coinOutType,
153
- externalFee
154
- });
155
- }
156
- async getTransaction({ completeRoute, walletAddress, slippage }) {
157
- const client = await this.aftermathClient();
158
- const transaction = await client.Router().getTransactionForCompleteTradeRoute({
159
- completeRoute,
160
- walletAddress,
161
- slippage,
162
- isSponsoredTx: false
163
- });
164
- transaction.setSender(walletAddress);
165
- return transaction.build({
166
- client: this._suiClient
167
- });
168
- }
169
- }
170
- (function(AftermathAggregator) {
171
- function toCommonTradeRoutes(tradeRoute) {
172
- if (0 === tradeRoute.routes.length) return null;
173
- const routes = [];
174
- for (const route of tradeRoute.routes){
175
- const paths = [];
176
- for (const path of route.paths)paths.push({
177
- poolAddress: path.poolId,
178
- coinIn: path.coinIn.type,
179
- coinOut: path.coinOut.type,
180
- amountIn: BigInt(path.coinIn.amount),
181
- amountOut: BigInt(path.coinOut.amount)
182
- });
183
- if (0 !== paths.length) routes.push({
184
- paths: paths,
185
- coinIn: route.coinIn.type,
186
- coinOut: route.coinOut.type,
187
- amountIn: route.coinIn.amount,
188
- amountOut: route.coinOut.amount
189
- });
190
- }
191
- if (0 === routes.length) return null;
192
- return {
193
- coinIn: tradeRoute.coinIn.type,
194
- coinOut: tradeRoute.coinOut.type,
195
- amountIn: tradeRoute.coinIn.amount,
196
- amountOut: tradeRoute.coinOut.amount,
197
- routes: routes
198
- };
199
- }
200
- AftermathAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
201
- })(aftermath_AftermathAggregator || (aftermath_AftermathAggregator = {}));
202
- function isSuiCoin(coin) {
203
- return "0x2::sui::SUI" === coin || "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI" === coin;
204
- }
205
- class astros_AstrosAggregator {
206
- _config;
207
- _suiClient;
208
- constructor(config, suiClient){
209
- this._config = config;
210
- this._suiClient = suiClient;
211
- }
212
- async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
213
- try {
214
- let serviceFee;
215
- serviceFee = tradeFee ? {
216
- fee: tradeFee.tradeFeePercent,
217
- receiverAddress: tradeFee.tradeFeeRecipientAddress
218
- } : {
219
- fee: this._config.defaultTradeFee.tradeFeePercent,
220
- receiverAddress: this._config.defaultTradeFee.tradeFeeRecipientAddress
221
- };
222
- return astros_aggregator_sdk_getQuote(coinInType, coinOutType, coinInAmount, this._config.astrosApiKey, {
223
- byAmountIn: true,
224
- serviceFee: serviceFee
225
- });
226
- } catch (_err) {
227
- return null;
228
- }
229
- }
230
- returnMergedCoins(txb, coins, amount) {
231
- if (coins.length < 2) return txb.object(coins[0].coinObjectId);
232
- let mergedBalance = 0;
233
- const mergeList = [];
234
- coins.sort((a, b)=>Number(b.balance) - Number(a.balance)).slice(1).forEach((coin)=>{
235
- if (mergedBalance >= amount) return;
236
- mergedBalance += Number(coin.balance);
237
- mergeList.push(coin.coinObjectId);
238
- });
239
- const baseObj = coins[0].coinObjectId;
240
- txb.mergeCoins(baseObj, mergeList);
241
- return txb.object(baseObj);
242
- }
243
- async getTransaction({ completeRoute: quote, walletAddress, slippage, tradeFee }) {
244
- let serviceFee;
245
- serviceFee = tradeFee ? {
246
- fee: tradeFee.tradeFeePercent,
247
- receiverAddress: tradeFee.tradeFeeRecipientAddress
248
- } : {
249
- fee: this._config.defaultTradeFee.tradeFeePercent,
250
- receiverAddress: this._config.defaultTradeFee.tradeFeeRecipientAddress
251
- };
252
- const minAmountOut = new bignumber(quote.amount_out).multipliedBy(1 - slippage - serviceFee.fee).toNumber();
253
- const txb = new Transaction();
254
- let coinIn;
255
- if (isSuiCoin(quote.from)) coinIn = txb.splitCoins(txb.gas, [
256
- txb.pure.u64(quote.amount_in)
257
- ]);
258
- else {
259
- const coins = await getCoins(this._suiClient, walletAddress, quote.from);
260
- const mergedCoins = this.returnMergedCoins(txb, coins.data, Number.parseFloat(quote.amount_in));
261
- coinIn = txb.splitCoins(mergedCoins, [
262
- txb.pure.u64(quote.amount_in)
263
- ]);
264
- }
265
- const coinB = await buildSwapPTBFromQuote(walletAddress, txb, minAmountOut, coinIn, quote, void 0, false, this._config.astrosApiKey, {
266
- serviceFee: serviceFee
267
- });
268
- txb.transferObjects([
269
- coinB
270
- ], walletAddress);
271
- txb.setSender(walletAddress);
272
- return txb.build({
273
- client: this._suiClient
274
- });
275
- }
276
- }
277
- (function(AstrosAggregator) {
278
- function toCommonTradeRoutes(tradeRoute, coinInType, coinOutType) {
279
- if (0 === tradeRoute.routes.length) return null;
280
- const routes = [];
281
- for (const route of tradeRoute.routes){
282
- const paths = [];
283
- for (const path of route.path)paths.push({
284
- poolAddress: path.id,
285
- coinIn: path.from,
286
- coinOut: path.target,
287
- amountIn: BigInt(path.amount_in),
288
- amountOut: BigInt(path.amount_out)
289
- });
290
- if (0 !== paths.length) routes.push({
291
- amountIn: BigInt(route.amount_in),
292
- amountOut: BigInt(route.amount_out),
293
- coinIn: paths[0].coinIn,
294
- coinOut: paths[paths.length - 1].coinOut,
295
- paths: paths
296
- });
297
- }
298
- if (0 === routes.length) return null;
299
- return {
300
- coinIn: coinInType,
301
- coinOut: coinOutType,
302
- amountIn: BigInt(tradeRoute.amount_in),
303
- amountOut: BigInt(tradeRoute.amount_out),
304
- routes: routes
305
- };
306
- }
307
- AstrosAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
308
- })(astros_AstrosAggregator || (astros_AstrosAggregator = {}));
309
- (function(TradeFeeOptions) {
310
- function equals(a, b) {
311
- return a.tradeFeePercent === b.tradeFeePercent && a.tradeFeeRecipientAddress === b.tradeFeeRecipientAddress;
312
- }
313
- TradeFeeOptions.equals = equals;
314
- })(types_TradeFeeOptions || (types_TradeFeeOptions = {}));
315
- var types_TradeFeeOptions;
316
- class cetus_CetusAggregator {
317
- _config;
318
- _suiClient;
319
- _cetusClient;
320
- constructor(config, suiClient){
321
- this._config = config;
322
- this._suiClient = suiClient;
323
- }
324
- cetusClient(walletAddress, tradeFee) {
325
- if (tradeFee && !types_TradeFeeOptions.equals(tradeFee, this._config.defaultTradeFee)) return new AggregatorClient({
326
- client: this._suiClient,
327
- overlayFeeReceiver: tradeFee.tradeFeeRecipientAddress,
328
- overlayFeeRate: tradeFee.tradeFeePercent,
329
- env: Env.Mainnet,
330
- signer: walletAddress,
331
- ...this._config.cetusApiKey && this._config.cetusApiEndpoint ? {
332
- apiKey: this._config.cetusApiKey,
333
- endpoint: this._config.cetusApiEndpoint
334
- } : {},
335
- partner: this._config.cetusPartnerId
336
- });
337
- if (this._cetusClient) return this._cetusClient;
338
- this._cetusClient = new AggregatorClient({
339
- client: this._suiClient,
340
- overlayFeeReceiver: this._config.defaultTradeFee.tradeFeeRecipientAddress,
341
- overlayFeeRate: this._config.defaultTradeFee.tradeFeePercent,
342
- env: Env.Mainnet,
343
- signer: walletAddress,
344
- ...this._config.cetusApiKey && this._config.cetusApiEndpoint ? {
345
- apiKey: this._config.cetusApiKey,
346
- endpoint: this._config.cetusApiEndpoint
347
- } : {},
348
- partner: this._config.cetusPartnerId
349
- });
350
- return this._cetusClient;
351
- }
352
- async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
353
- const client = this.cetusClient(void 0, tradeFee);
354
- return client.findRouters({
355
- from: coinInType,
356
- target: coinOutType,
357
- amount: new bn(coinInAmount.toString()),
358
- byAmountIn: true
359
- });
360
- }
361
- async getTransaction({ completeRoute: routers, walletAddress, slippage, tradeFee }) {
362
- const txb = new Transaction();
363
- const client = this.cetusClient(walletAddress, tradeFee);
364
- await client.fastRouterSwap({
365
- router: routers,
366
- txb,
367
- slippage
368
- });
369
- await client.devInspectTransactionBlock(txb);
370
- txb.setSender(walletAddress);
371
- return txb.build({
372
- client: this._suiClient
373
- });
374
- }
375
- }
376
- (function(CetusAggregator) {
377
- function toCommonTradeRoutes(tradeRoute, coinInType, coinOutType) {
378
- if (0 === tradeRoute.paths.length) return null;
379
- const routes = [];
380
- const allPaths = [];
381
- let currentRoute = [];
382
- for(let i = 0; i < tradeRoute.paths.length; i++){
383
- const currentPath = tradeRoute.paths[i];
384
- const tradePath = {
385
- poolAddress: currentPath.id,
386
- amountIn: BigInt(currentPath.amountIn),
387
- amountOut: BigInt(currentPath.amountOut),
388
- coinIn: currentPath.from,
389
- coinOut: currentPath.target
390
- };
391
- currentRoute.push(tradePath);
392
- if (i === tradeRoute.paths.length - 1) allPaths.push([
393
- ...currentRoute
394
- ]);
395
- else {
396
- const nextPath = tradeRoute.paths[i + 1];
397
- if (currentPath.target !== nextPath.from) {
398
- allPaths.push([
399
- ...currentRoute
400
- ]);
401
- currentRoute = [];
402
- }
403
- }
404
- }
405
- for (const pathGroup of allPaths)if (0 !== pathGroup.length) routes.push({
406
- amountIn: pathGroup[0].amountIn,
407
- amountOut: pathGroup[pathGroup.length - 1].amountOut,
408
- coinIn: pathGroup[0].coinIn,
409
- coinOut: pathGroup[pathGroup.length - 1].coinOut,
410
- paths: pathGroup
411
- });
412
- if (0 === routes.length) return null;
413
- return {
414
- coinIn: coinInType,
415
- coinOut: coinOutType,
416
- amountIn: BigInt(tradeRoute.amountIn.toString(10)),
417
- amountOut: BigInt(tradeRoute.amountOut.toString(10)),
418
- routes: routes
419
- };
420
- }
421
- CetusAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
422
- })(cetus_CetusAggregator || (cetus_CetusAggregator = {}));
423
- var common_SupportedAggregator = /*#__PURE__*/ function(SupportedAggregator) {
424
- SupportedAggregator["ASTROS"] = "ASTROS";
425
- SupportedAggregator["AFTERMATH"] = "AFTERMATH";
426
- SupportedAggregator["SEVENK"] = "7K";
427
- SupportedAggregator["CETUS"] = "CETUS";
428
- SupportedAggregator["FLOWX"] = "FLOWX";
429
- return SupportedAggregator;
430
- }({});
431
- function getInputPercent(percent) {
432
- return 1e6 * percent;
433
- }
434
- class flowx_FlowXAggregator {
435
- _config;
436
- _suiClient;
437
- constructor(config, suiClient){
438
- this._config = config;
439
- this._suiClient = suiClient;
440
- }
441
- getCommission(coinInType, tradeFee) {
442
- let tradeFeePercent;
443
- let tradeFeeRecipientAddress;
444
- if (tradeFee) {
445
- tradeFeePercent = tradeFee.tradeFeePercent;
446
- tradeFeeRecipientAddress = tradeFee.tradeFeeRecipientAddress;
447
- } else {
448
- tradeFeePercent = this._config.defaultTradeFee.tradeFeePercent;
449
- tradeFeeRecipientAddress = this._config.defaultTradeFee.tradeFeeRecipientAddress;
450
- }
451
- return new Commission(tradeFeeRecipientAddress, new Coin(coinInType), CommissionType.PERCENTAGE, getInputPercent(tradeFeePercent), true);
452
- }
453
- async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
454
- const quoter = new AggregatorQuoter("mainnet", this._config.flowxApiKey);
455
- try {
456
- return quoter.getRoutes({
457
- tokenIn: coinInType,
458
- tokenOut: coinOutType,
459
- amountIn: coinInAmount.toString(),
460
- commission: this.getCommission(coinInType, tradeFee)
461
- });
462
- } catch (_err) {
463
- return null;
464
- }
465
- }
466
- async getTransaction({ walletAddress, completeRoute, slippage, tradeFee }) {
467
- const tradeBuilder = new TradeBuilder("mainnet", completeRoute.routes);
468
- const result = tradeBuilder.sender(walletAddress).slippage(getInputPercent(slippage)).commission(this.getCommission(completeRoute.coinIn.coinType, tradeFee)).build();
469
- return result.buildTransaction({
470
- client: this._suiClient
471
- }).then((tx)=>{
472
- tx.setSender(walletAddress);
473
- return tx.build({
474
- client: this._suiClient
475
- });
476
- });
477
- }
478
- }
479
- (function(FlowXAggregator) {
480
- function toCommonTradeRoutes(tradeRoute) {
481
- if (0 === tradeRoute.routes.length) return null;
482
- const routes = [];
483
- for (const route of tradeRoute.routes){
484
- const paths = [];
485
- for (const path of route.paths)paths.push({
486
- amountIn: BigInt(path.amountIn.toString()),
487
- amountOut: BigInt(path.amountOut.toString()),
488
- coinIn: path.input.coinType,
489
- coinOut: path.output.coinType,
490
- poolAddress: path.pool.id
491
- });
492
- if (0 !== paths.length) routes.push({
493
- amountIn: BigInt(route.amountIn.toString()),
494
- amountOut: BigInt(route.amountOut.toString()),
495
- coinIn: route.input.coinType,
496
- coinOut: route.output.coinType,
497
- paths: paths
498
- });
499
- }
500
- if (0 === routes.length) return null;
501
- return {
502
- coinIn: tradeRoute.coinIn.coinType,
503
- coinOut: tradeRoute.coinOut.coinType,
504
- amountIn: BigInt(tradeRoute.amountIn.toString()),
505
- amountOut: BigInt(tradeRoute.amountOut.toString()),
506
- routes: routes
507
- };
508
- }
509
- FlowXAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
510
- })(flowx_FlowXAggregator || (flowx_FlowXAggregator = {}));
511
- (function(BlastFunConstants) {
512
- BlastFunConstants.PACKAGE_ID_V4 = "0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd";
513
- BlastFunConstants.MEMEZ_AV_OBJECT_ID = "0x2319e3e76dfad73d8f4684bdbf42be4f32d8ce4521dd61becc8261dc918d82c0";
514
- })(constants_BlastFunConstants || (constants_BlastFunConstants = {}));
515
- var constants_BlastFunConstants;
516
- const BLUEFIN_PACKAGE_ID = "0x62412b7268c35f3808336aee57a52836501f40b8ba5d936f8ad275e672befd04";
517
- const SUI_TYPE = "0x2::sui::SUI";
518
- const SUI_FULL_TYPE = "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";
519
- const USDC_TOKEN_TYPE = "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN";
520
- const NATIVE_USDC_TOKEN_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
521
- const SUI_METADATA_OBJECT_ID = "0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3";
522
- const CLOCK_OBJECT_ID = "0x0000000000000000000000000000000000000000000000000000000000000006";
523
- const orderByKey = (array, key, sortBy)=>{
524
- if (!array?.length) return;
525
- let swapped;
526
- do {
527
- swapped = false;
528
- for(let i = 0; i < array.length - 1; i++){
529
- const a = BigInt(array[i][key]);
530
- const b = BigInt(array[i + 1][key]);
531
- if ("desc" === sortBy ? a < b : a > b) {
532
- const temp = array[i];
533
- array[i] = array[i + 1];
534
- array[i + 1] = temp;
535
- swapped = true;
536
- }
537
- }
538
- }while (swapped);
539
- return array;
540
- };
541
- const getCoinObjectIdsByAmount = async (suiClient, address, amount, coinType)=>{
542
- let coinBalances = [];
543
- let hasNextPage = true;
544
- let nextCursor;
545
- while(hasNextPage)try {
546
- const coins = await suiClient.getCoins({
547
- owner: address,
548
- coinType,
549
- cursor: nextCursor
550
- });
551
- coinBalances = [
552
- ...coinBalances,
553
- ...coins.data
554
- ];
555
- hasNextPage = coins.hasNextPage;
556
- nextCursor = coins.nextCursor;
557
- } catch (error) {
558
- console.error("Error fetching data:", error);
559
- hasNextPage = false;
560
- }
561
- const coinObj = orderByKey(coinBalances.map((item)=>({
562
- ...item,
563
- balance: item.balance
564
- })), "balance", "desc") ?? [];
565
- let balance = "0";
566
- const objectIds = [];
567
- const objectCoins = [];
568
- for (const coin of coinObj){
569
- balance = (BigInt(coin.balance) + BigInt(balance)).toString(10);
570
- objectIds.push(coin.coinObjectId);
571
- objectCoins.push(coin);
572
- if (BigInt(balance) >= BigInt(amount)) break;
573
- }
574
- return {
575
- objectIds,
576
- balance,
577
- objectCoins
578
- };
579
- };
580
- async function addGasFee(params, suiClient) {
581
- const { inheritTx, sender, feeAmount, suiInputAmount } = params;
582
- const tx = inheritTx || new Transaction();
583
- tx.setGasBudget(feeAmount);
584
- const { objectCoins } = await getCoinObjectIdsByAmount(suiClient, sender, (BigInt(suiInputAmount || "0") + feeAmount).toString(), SUI_FULL_TYPE);
585
- tx.setGasPayment(objectCoins.map((c)=>({
586
- objectId: c.coinObjectId,
587
- version: c.version,
588
- digest: c.digest
589
- })));
590
- return tx;
591
- }
592
- (function(BluefinTx) {
593
- function transferOrDestroyZeroCoin(tx, coinType, coin, address) {
594
- tx.moveCall({
595
- target: `${BLUEFIN_PACKAGE_ID}::utils::transfer_or_destroy`,
596
- typeArguments: [
597
- coinType
598
- ],
599
- arguments: [
600
- coin,
601
- tx.pure.address(address)
602
- ]
603
- });
604
- }
605
- BluefinTx.transferOrDestroyZeroCoin = transferOrDestroyZeroCoin;
606
- })(bluefin_BluefinTx || (bluefin_BluefinTx = {}));
607
- var bluefin_BluefinTx;
608
- async function getSplitCoinForTx(params, suiClient) {
609
- const { account, amount, splits, coinType, inheritTx, inspecTransaction, isSponsored = false } = params;
610
- const tx = inheritTx ?? new Transaction();
611
- const { objectIds } = await getCoinObjectIdsByAmount(suiClient, account, amount, coinType);
612
- const coinObjectId = objectIds[0];
613
- if (normalizeStructTag(coinType) === normalizeStructTag(SUI_FULL_TYPE) && !isSponsored) {
614
- let coin;
615
- if (inspecTransaction) {
616
- if (objectIds.length > 1) tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
617
- coin = tx.splitCoins(tx.object(coinObjectId), splits);
618
- } else coin = tx.splitCoins(tx.gas, splits);
619
- return {
620
- tx,
621
- coinData: coin
622
- };
623
- }
624
- if (objectIds.length > 1) tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
625
- const coinData = tx.splitCoins(tx.object(coinObjectId), splits);
626
- return {
627
- tx,
628
- coinData
629
- };
630
- }
631
- const BASE_BPS = 10000;
632
- function getSplitCoinsAfterFee(amount, fee) {
633
- const amountNum = BigInt(amount);
634
- const feeNum = BigInt(Number(fee) * BASE_BPS);
635
- if (feeNum === BigInt(0)) return [
636
- amountNum.toString()
637
- ];
638
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
639
- const remainingAmount = amountNum - feeAmount;
640
- return [
641
- remainingAmount.toString(),
642
- feeAmount.toString()
643
- ];
644
- }
645
- function getAmountAfterFee(amount, fee) {
646
- if (!fee || Number(fee) <= 0) return BigInt(amount);
647
- const amountNum = BigInt(amount);
648
- const feeNum = BigInt(Number(fee) * BASE_BPS);
649
- if (feeNum === BigInt(0)) return amountNum;
650
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
651
- return amountNum - feeAmount;
652
- }
653
- async function getNeededGasFee(suiClient, tx, sender, bufferPercent) {
654
- const { effects: { gasUsed, status } } = await suiClient.devInspectTransactionBlock({
655
- sender,
656
- transactionBlock: tx
657
- });
658
- if ("success" !== status.status) throw new Error(`Transaction failed during dev inspect: ${status.error ?? ""}`);
659
- const fee = BigInt(gasUsed.computationCost) + BigInt(gasUsed.storageCost) - BigInt(gasUsed.storageRebate);
660
- const feeNum = BigInt(Number(bufferPercent) * BASE_BPS);
661
- return fee * (BigInt(BASE_BPS) + feeNum) / BigInt(BASE_BPS);
662
- }
663
- async function getMoveObjectContent(suiClient, objectId) {
664
- const moveObject = await getMoveObject(suiClient, objectId);
665
- return moveObject.fields;
666
- }
667
- async function getMoveObject(suiClient, objectId) {
668
- const objRes = await suiClient.getObject({
669
- id: objectId,
670
- options: {
671
- showContent: true
672
- }
673
- });
674
- const content = objRes.data?.content;
675
- tiny_invariant(content, "Pool object not found or has no content");
676
- tiny_invariant("moveObject" === content.dataType, "Object is not a Move object");
677
- return content;
678
- }
679
- function adaptSuiClient(client) {
680
- return client;
681
- }
682
- function adaptTransaction(transaction) {
683
- return transaction;
684
- }
685
- function createCompatibleSuiClient(client) {
686
- return new Proxy(client, {
687
- get (target, prop) {
688
- const value = target[prop];
689
- if ("function" == typeof value) return value.bind(target);
690
- return value;
691
- }
692
- });
693
- }
694
- (function(MathUtils) {
695
- (function(U64) {
696
- function mulDivUp(a, b, c) {
697
- let roundUp = BigInt(0);
698
- if (a * b % c > BigInt(0)) roundUp = BigInt(1);
699
- return a * b / c + roundUp;
700
- }
701
- U64.mulDivUp = mulDivUp;
702
- })(MathUtils.U64 || (MathUtils.U64 = {}));
703
- })(package_MathUtils || (package_MathUtils = {}));
704
- (function(Bps) {
705
- function calcUp(bps, amount) {
706
- const bpsValue = BigInt(bps.pos0);
707
- const denominator = BigInt(10000);
708
- let roundUp;
709
- roundUp = bpsValue * amount % denominator !== BigInt(0) ? BigInt(1) : BigInt(0);
710
- return bpsValue * amount / denominator + roundUp;
711
- }
712
- Bps.calcUp = calcUp;
713
- function sub(lhs, rhs) {
714
- tiny_invariant(BigInt(lhs.pos0) >= BigInt(rhs.pos0), "Bps underflow");
715
- return {
716
- pos0: (BigInt(lhs.pos0) - BigInt(rhs.pos0)).toString()
717
- };
718
- }
719
- Bps.sub = sub;
720
- function value(bps) {
721
- return BigInt(bps.pos0);
722
- }
723
- Bps.value = value;
724
- function new_(bps) {
725
- return {
726
- pos0: assertOverflow(bps).toString()
727
- };
728
- }
729
- Bps.new_ = new_;
730
- function assertOverflow(bps) {
731
- tiny_invariant(BigInt(bps) <= BigInt(10000), "Bps overflow");
732
- return BigInt(bps);
733
- }
734
- Bps.assertOverflow = assertOverflow;
735
- })(package_Bps || (package_Bps = {}));
736
- (function(BlastFunPackage) {
737
- (function(MemezFun) {
738
- async function isSniperProtectedMemezFun(suiClient, poolId) {
739
- const memezFun = await getMoveObjectContent(suiClient, poolId);
740
- return memezFun.public_key.length > 0;
741
- }
742
- MemezFun.isSniperProtectedMemezFun = isSniperProtectedMemezFun;
743
- })(BlastFunPackage.MemezFun || (BlastFunPackage.MemezFun = {}));
744
- (function(MemezFees) {
745
- function takeWithDiscount(fee, amount, discountBps) {
746
- if ("Value" === fee.variant) {
747
- const amountRequired = BigInt(fee.fields.pos0);
748
- if (amountRequired === BigInt(0)) return BigInt(0);
749
- if (amount >= amountRequired) return amountRequired;
750
- throw new Error(`Insufficient amount to cover fee. Required: ${amountRequired}, provided: ${amount}`);
751
- }
752
- if ("Percentage" === fee.variant) {
753
- const feeBps = fee.fields.pos0.fields;
754
- if (BigInt(feeBps.pos0) === BigInt(0)) return BigInt(0);
755
- const discountedFee = package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
756
- if (amount >= discountedFee) return discountedFee;
757
- throw new Error(`Insufficient amount to cover fee. Required: ${discountedFee}, provided: ${amount}`);
758
- }
759
- throw new Error("Unknown fee variant");
760
- }
761
- MemezFees.takeWithDiscount = takeWithDiscount;
762
- function calculateWithDiscount(fee, discountBps, amount) {
763
- if ("Value" === fee.variant) return BigInt(fee.fields.pos0);
764
- if ("Percentage" === fee.variant) {
765
- const feeBps = fee.fields.pos0.fields;
766
- return package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
767
- }
768
- throw new Error("Unknown fee variant");
769
- }
770
- MemezFees.calculateWithDiscount = calculateWithDiscount;
771
- })(BlastFunPackage.MemezFees || (BlastFunPackage.MemezFees = {}));
772
- (function(MemezBurner) {
773
- function calculate(burner, poolMemeBalance) {
774
- const burnerFee = package_Bps.value(burner.fee.fields);
775
- if (burnerFee === BigInt(0) || poolMemeBalance === BigInt(0)) return package_Bps.new_(0);
776
- if (poolMemeBalance >= BigInt(burner.target_liquidity)) return package_Bps.new_(0);
777
- const baseBps = BigInt(10000);
778
- return package_Bps.new_(package_MathUtils.U64.mulDivUp(package_Bps.value(burner.fee.fields), package_MathUtils.U64.mulDivUp(poolMemeBalance, baseBps, BigInt(burner.target_liquidity)), baseBps));
779
- }
780
- MemezBurner.calculate = calculate;
781
- })(BlastFunPackage.MemezBurner || (BlastFunPackage.MemezBurner = {}));
782
- (function(MemezPump) {
783
- async function getPumpState(suiClient, memezFun) {
784
- return await getMoveObjectContent(suiClient, memezFun.inner_state);
785
- }
786
- MemezPump.getPumpState = getPumpState;
787
- function pump(pumpState, quoteAmount) {
788
- const constantProduct = pumpState.constant_product.fields;
789
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteAmount, constantProduct.quote_referrer_fee.fields);
790
- const quoteAfterFee = quoteAmount - quoteSwapFee;
791
- const memeBalance = BigInt(constantProduct.meme_balance);
792
- const quoteBalance = BigInt(constantProduct.quote_balance);
793
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
794
- const memeOutExpected = memeBalance * quoteAfterFee / (virtualLiquidity + quoteBalance + quoteAfterFee);
795
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeOutExpected, constantProduct.meme_referrer_fee.fields);
796
- return memeOutExpected - memeSwapFee;
797
- }
798
- MemezPump.pump = pump;
799
- function dump(pumpState, memeAmount) {
800
- const constantProduct = pumpState.constant_product.fields;
801
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeAmount, constantProduct.meme_referrer_fee.fields);
802
- const inputAmount = memeAmount - memeSwapFee;
803
- const memeBalance = BigInt(constantProduct.meme_balance);
804
- const quoteBalance = BigInt(constantProduct.quote_balance);
805
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
806
- const burnBps = BlastFunPackage.MemezBurner.calculate(constantProduct.burner.fields, quoteBalance);
807
- const burnAmount = package_Bps.calcUp(burnBps, inputAmount);
808
- const inputAmountAfterFee = inputAmount - (package_Bps.value(burnBps) !== BigInt(0) ? burnAmount : BigInt(0));
809
- let quoteOutBeforeFee = (virtualLiquidity + quoteBalance) * inputAmountAfterFee / (memeBalance + inputAmountAfterFee);
810
- if (quoteOutBeforeFee > quoteBalance) quoteOutBeforeFee = quoteBalance;
811
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteOutBeforeFee, constantProduct.quote_referrer_fee.fields);
812
- return quoteOutBeforeFee - quoteSwapFee;
813
- }
814
- MemezPump.dump = dump;
815
- })(BlastFunPackage.MemezPump || (BlastFunPackage.MemezPump = {}));
816
- })(package_BlastFunPackage || (package_BlastFunPackage = {}));
817
- var package_MathUtils, package_Bps, package_BlastFunPackage;
818
- (function(BlastFunCustomCalculation) {
819
- async function getCurveAmountAfterBuy(params, suiClient) {
820
- let { suiAmount, poolId, frontendFee } = params;
821
- const memezFun = await getMoveObjectContent(suiClient, poolId);
822
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(suiClient, memezFun);
823
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
824
- return package_BlastFunPackage.MemezPump.pump(pumpState, suiAmount);
825
- }
826
- BlastFunCustomCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
827
- async function getSuiAmountAfterSell(params, suiClient) {
828
- const { curveAmount, poolId, frontendFee } = params;
829
- const memezFun = await getMoveObjectContent(suiClient, poolId);
830
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(suiClient, memezFun);
831
- const suiAmount = package_BlastFunPackage.MemezPump.dump(pumpState, curveAmount);
832
- return getAmountAfterFee(suiAmount, frontendFee);
833
- }
834
- BlastFunCustomCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
835
- })(custom_calculation_BlastFunCustomCalculation || (custom_calculation_BlastFunCustomCalculation = {}));
836
- var custom_calculation_BlastFunCustomCalculation;
837
- async function splitSuiCoinAfterFeeFromBuyTx(params, suiClient) {
838
- const { inputAmount, accountAddress, frontendFee, frontendFeeRecipient, extendTx, isSponsored } = params;
839
- tiny_invariant(params.inCoinType === SUI_FULL_TYPE || params.inCoinType === SUI_TYPE, "Input must be SUI");
840
- const { tx: _tx, coinIn } = extendTx || {};
841
- const splitSui = getSplitCoinsAfterFee(inputAmount, frontendFee || "0");
842
- const tx = _tx || new Transaction();
843
- let coinData;
844
- if (coinIn) {
845
- coinData = tx.splitCoins(coinIn, splitSui);
846
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, coinIn, accountAddress);
847
- } else {
848
- const { coinData: _data } = await getSplitCoinForTx({
849
- account: accountAddress,
850
- amount: inputAmount,
851
- splits: splitSui,
852
- coinType: SUI_FULL_TYPE,
853
- inheritTx: tx,
854
- isSponsored: isSponsored || false
855
- }, suiClient);
856
- coinData = _data;
857
- }
858
- let inputSuiCoin;
859
- if (frontendFee && frontendFeeRecipient) {
860
- const [_inputSuiCoin, frontendFeeCoin] = coinData;
861
- inputSuiCoin = _inputSuiCoin;
862
- tx.transferObjects([
863
- frontendFeeCoin
864
- ], tx.pure.address(frontendFeeRecipient || accountAddress));
865
- } else [inputSuiCoin] = coinData;
866
- return {
867
- tx,
868
- coinOut: inputSuiCoin
869
- };
870
- }
871
- async function splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin) {
872
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
873
- if (Number(params.frontendFee || 0) <= 0) return {
874
- tx,
875
- coinOut: suiCoin
876
- };
877
- const suiCoinValue = tx.moveCall({
878
- target: "0x2::coin::value",
879
- typeArguments: [
880
- params.outCoinType
881
- ],
882
- arguments: [
883
- suiCoin
884
- ]
885
- });
886
- const suiCoinFeeValue = tx.moveCall({
887
- target: `${BLUEFIN_PACKAGE_ID}::math::mul_div_u64`,
888
- typeArguments: [],
889
- arguments: [
890
- suiCoinValue,
891
- tx.pure.u64(BigInt(Number(params.frontendFee || "0") * BASE_BPS)),
892
- tx.pure.u64(BigInt(BASE_BPS))
893
- ]
894
- });
895
- const suiCoinFee = tx.moveCall({
896
- target: "0x2::coin::split",
897
- typeArguments: [
898
- params.outCoinType
899
- ],
900
- arguments: [
901
- suiCoin,
902
- suiCoinFeeValue
903
- ]
904
- });
905
- tx.transferObjects([
906
- suiCoinFee
907
- ], tx.pure.address(params.frontendFeeRecipient || params.accountAddress));
908
- return {
909
- tx,
910
- coinOut: suiCoin
911
- };
912
- }
913
- var types_SupportedBondingCurve = /*#__PURE__*/ function(SupportedBondingCurve) {
914
- SupportedBondingCurve["BLAST_FUN"] = "BLAST_FUN";
915
- SupportedBondingCurve["MOONBAGS"] = "MOONBAGS";
916
- return SupportedBondingCurve;
917
- }({});
918
- (function(BlastFunCustomTransaction) {
919
- async function getAllowedVersions(_tx) {
920
- const tx = _tx || new Transaction();
921
- return tx.moveCall({
922
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_allowed_versions::get_allowed_versions`,
923
- arguments: [
924
- tx.object(constants_BlastFunConstants.MEMEZ_AV_OBJECT_ID)
925
- ],
926
- typeArguments: []
927
- });
928
- }
929
- BlastFunCustomTransaction.getAllowedVersions = getAllowedVersions;
930
- async function buildBuyTx(params, suiClient) {
931
- tiny_invariant(!await package_BlastFunPackage.MemezFun.isSniperProtectedMemezFun(suiClient, params.poolId), "This coin is a sniper protected coin, please use the Blast Fun website to trade it.");
932
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
933
- tiny_invariant(suiCoinIn, "Coin out is required");
934
- const curveCoin = tx.moveCall({
935
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::pump`,
936
- typeArguments: [
937
- params.outCoinType,
938
- SUI_FULL_TYPE
939
- ],
940
- arguments: [
941
- tx.object(params.poolId),
942
- suiCoinIn,
943
- tx.pure.vector("address", []),
944
- tx.pure.vector("vector<u8>", []),
945
- tx.pure.u64(params.minAmountOut),
946
- await getAllowedVersions(tx)
947
- ]
948
- });
949
- return {
950
- tx,
951
- coinOut: curveCoin
952
- };
953
- }
954
- BlastFunCustomTransaction.buildBuyTx = buildBuyTx;
955
- async function buildSellTx(params, suiClient) {
956
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
957
- const memezFun = await getMoveObjectContent(suiClient, params.poolId);
958
- const { tx, coinData } = await getSplitCoinForTx({
959
- amount: params.inputAmount,
960
- coinType: params.inCoinType,
961
- inheritTx: params.extendTx?.tx,
962
- account: params.accountAddress,
963
- splits: [
964
- params.inputAmount
965
- ]
966
- }, suiClient);
967
- const [inputCoin] = coinData;
968
- const [suiCoin] = tx.moveCall({
969
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::dump`,
970
- typeArguments: [
971
- params.inCoinType,
972
- params.outCoinType
973
- ],
974
- arguments: [
975
- tx.object(params.poolId),
976
- tx.object(memezFun.ipx_meme_coin_treasury),
977
- inputCoin,
978
- tx.pure.vector("address", []),
979
- tx.pure.u64(params.minAmountOut),
980
- await getAllowedVersions(tx)
981
- ]
982
- });
983
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
984
- }
985
- BlastFunCustomTransaction.buildSellTx = buildSellTx;
986
- })(custom_transaction_BlastFunCustomTransaction || (custom_transaction_BlastFunCustomTransaction = {}));
987
- var custom_transaction_BlastFunCustomTransaction;
988
- const payload = {
989
- network: Network.MAINNET,
990
- fullNodeUrl: getFullnodeUrl("mainnet")
991
- };
992
- const memezPump = new MemezPumpSDK(payload);
993
- function getMemezPumpSDK() {
994
- return memezPump;
995
- }
996
- (function(BlastFunSDKCalculation) {
997
- async function getCurveAmountAfterBuy(params) {
998
- let { suiAmount, poolId, frontendFee } = params;
999
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1000
- const { memeAmountOut } = await getMemezPumpSDK().quotePump({
1001
- pool: poolId,
1002
- amount: suiAmount
1003
- });
1004
- return memeAmountOut;
1005
- }
1006
- BlastFunSDKCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1007
- async function getSuiAmountAfterSell(params) {
1008
- const { curveAmount, poolId, frontendFee } = params;
1009
- const { quoteAmountOut } = await getMemezPumpSDK().quoteDump({
1010
- pool: poolId,
1011
- amount: curveAmount
1012
- });
1013
- return getAmountAfterFee(quoteAmountOut, frontendFee);
1014
- }
1015
- BlastFunSDKCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1016
- })(sdk_calculation_BlastFunSDKCalculation || (sdk_calculation_BlastFunSDKCalculation = {}));
1017
- var sdk_calculation_BlastFunSDKCalculation;
1018
- (function(BlastFunSDKTransaction) {
1019
- async function buildBuyTx(params, suiClient) {
1020
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
1021
- tiny_invariant(suiCoinIn, "Coin out is required");
1022
- const { memeCoin, tx: tx2 } = await getMemezPumpSDK().pump({
1023
- pool: params.poolId,
1024
- quoteCoin: suiCoinIn,
1025
- minAmountOut: params.minAmountOut,
1026
- tx
1027
- });
1028
- return {
1029
- tx: tx2,
1030
- coinOut: memeCoin
1031
- };
1032
- }
1033
- BlastFunSDKTransaction.buildBuyTx = buildBuyTx;
1034
- async function buildSellTx(params, suiClient) {
1035
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1036
- const { tx, coinData } = await getSplitCoinForTx({
1037
- amount: params.inputAmount,
1038
- coinType: params.inCoinType,
1039
- inheritTx: params.extendTx?.tx,
1040
- account: params.accountAddress,
1041
- splits: [
1042
- params.inputAmount
1043
- ]
1044
- }, suiClient);
1045
- const [inputCoin] = coinData;
1046
- const { quoteCoin, tx: tx2 } = await getMemezPumpSDK().dump({
1047
- pool: params.poolId,
1048
- memeCoin: inputCoin,
1049
- tx,
1050
- minAmountOut: params.minAmountOut
1051
- });
1052
- return await splitSuiCoinAfterFeeFromSellTx(tx2, params, quoteCoin);
1053
- }
1054
- BlastFunSDKTransaction.buildSellTx = buildSellTx;
1055
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1056
- tiny_invariant(coinInType === SUI_TYPE, "coinInType must be SUI for buy transaction");
1057
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1058
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1059
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1060
- const inputAmount = coinInAmount;
1061
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({
1062
- poolId: poolId,
1063
- suiAmount: inputAmount,
1064
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1065
- });
1066
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1067
- let { tx, coinOut } = await buildBuyTx({
1068
- accountAddress: walletAddress,
1069
- inCoinType: coinInType,
1070
- outCoinType: coinOutType,
1071
- inputAmount: inputAmount.toString(),
1072
- minAmountOut: minAmountOut.toString(),
1073
- poolId: poolId,
1074
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1075
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1076
- extendTx: void 0,
1077
- isSponsored: false
1078
- }, suiClient);
1079
- tiny_invariant(coinOut, "Coin out is required");
1080
- tx.transferObjects([
1081
- coinOut
1082
- ], tx.pure.address(walletAddress));
1083
- tx.setSender(walletAddress);
1084
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1085
- tx = await addGasFee({
1086
- inheritTx: tx,
1087
- sender: walletAddress,
1088
- feeAmount,
1089
- suiInputAmount: inputAmount
1090
- }, suiClient);
1091
- return tx.build({
1092
- client: suiClient
1093
- });
1094
- }
1095
- BlastFunSDKTransaction.getBuyTransaction = getBuyTransaction;
1096
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1097
- tiny_invariant(coinOutType === SUI_TYPE, "coinOutType must be SUI for sell transaction");
1098
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1099
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1100
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1101
- const inputAmount = coinInAmount;
1102
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({
1103
- poolId: poolId,
1104
- curveAmount: inputAmount,
1105
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1106
- });
1107
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1108
- let { tx, coinOut } = await buildSellTx({
1109
- accountAddress: walletAddress,
1110
- inCoinType: coinInType,
1111
- outCoinType: coinOutType,
1112
- inputAmount: inputAmount.toString(),
1113
- minAmountOut: minAmountOut.toString(),
1114
- poolId: poolId,
1115
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1116
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1117
- extendTx: void 0,
1118
- isSponsored: false
1119
- }, suiClient);
1120
- tiny_invariant(coinOut, "Coin out is required");
1121
- tx.transferObjects([
1122
- coinOut
1123
- ], tx.pure.address(walletAddress));
1124
- tx.setSender(walletAddress);
1125
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1126
- tx = await addGasFee({
1127
- inheritTx: tx,
1128
- sender: walletAddress,
1129
- feeAmount
1130
- }, suiClient);
1131
- return tx.build({
1132
- client: suiClient
1133
- });
1134
- }
1135
- BlastFunSDKTransaction.getSellTransaction = getSellTransaction;
1136
- })(sdk_transaction_BlastFunSDKTransaction || (sdk_transaction_BlastFunSDKTransaction = {}));
1137
- var sdk_transaction_BlastFunSDKTransaction;
1138
- (function(MoonbagsConstants) {
1139
- MoonbagsConstants.PACKAGE_ID = "0xb8df325010942634a4afb3db3901ee215546af43a4ec4af781e7213b0bba7290";
1140
- MoonbagsConstants.CONFIG_OBJECT_ID = "0x74aecf86067c6913960ba4925333aefd2b1f929cafca7e21fd55a8f244b70499";
1141
- MoonbagsConstants.LOCK_CONFIG_OBJECT_ID = "0xfb09822d9808980abd04c51321adb850701f5f55535c6206658ef4d910c3e9be";
1142
- MoonbagsConstants.BURN_MANAGER_OBJECT_ID = "0x1d94aa32518d0cb00f9de6ed60d450c9a2090761f326752ffad06b2e9404f845";
1143
- MoonbagsConstants.POOLS_OBJECT_ID = "0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0";
1144
- MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID = "0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f";
1145
- MoonbagsConstants.FEE_DENOMINATOR = BigInt(10000);
1146
- })(constants_MoonbagsConstants || (constants_MoonbagsConstants = {}));
1147
- var constants_MoonbagsConstants;
1148
- (function(MoonbagsPackage) {
1149
- (function(Curves) {
1150
- function calculateAddLiquidityCost(tokenIn, tokenReserve, tokenAmount) {
1151
- const availableReserve = tokenReserve - tokenAmount;
1152
- const numerator = tokenIn * tokenReserve;
1153
- const fraction = numerator / availableReserve;
1154
- return fraction - tokenIn;
1155
- }
1156
- Curves.calculateAddLiquidityCost = calculateAddLiquidityCost;
1157
- function calculateRemoveLiquidityReturn(tokenIn, tokenReserve, tokenRemoved) {
1158
- const denominator = tokenIn + tokenRemoved;
1159
- const fraction = tokenIn * tokenReserve / denominator;
1160
- return tokenReserve - fraction;
1161
- }
1162
- Curves.calculateRemoveLiquidityReturn = calculateRemoveLiquidityReturn;
1163
- function calculateTokenAmountReceived(tokenIn, tokenReserve, tokenOutReserve) {
1164
- const denominator = tokenIn + tokenOutReserve;
1165
- const fraction = tokenIn * tokenReserve / denominator;
1166
- return tokenReserve - fraction;
1167
- }
1168
- Curves.calculateTokenAmountReceived = calculateTokenAmountReceived;
1169
- })(MoonbagsPackage.Curves || (MoonbagsPackage.Curves = {}));
1170
- (function(Moonbags) {
1171
- async function getDynamicVirtualTokenReserves(suiClient, poolId) {
1172
- const result = await suiClient.getDynamicFieldObject({
1173
- parentId: poolId,
1174
- name: {
1175
- type: "vector<u8>",
1176
- value: "virtual_token_reserves"
1177
- }
1178
- });
1179
- if (!result.data) return;
1180
- return BigInt(result.data.content.fields.value);
1181
- }
1182
- Moonbags.getDynamicVirtualTokenReserves = getDynamicVirtualTokenReserves;
1183
- function buyExactInReturnsWithLock(params) {
1184
- const { inputAmount, amountIn, pool, config, dynamicVirtualTokenReserves } = params;
1185
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1186
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1187
- const remainTokenReserves = BigInt(pool.remain_token_reserves.fields.balance);
1188
- const expectedOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualSuiReserves, virtualTokenReserves, amountIn);
1189
- const availableOut = virtualTokenReserves - (dynamicVirtualTokenReserves || remainTokenReserves);
1190
- let finalOut = expectedOut;
1191
- let usedSui = amountIn;
1192
- if (expectedOut > availableOut) {
1193
- finalOut = availableOut;
1194
- usedSui = MoonbagsPackage.Curves.calculateAddLiquidityCost(virtualSuiReserves, virtualTokenReserves, availableOut) + BigInt(1);
1195
- }
1196
- const feeAmount = usedSui * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1197
- tiny_invariant(inputAmount >= usedSui + feeAmount, "Input amount is less than used SUI + fee");
1198
- return {
1199
- receivedCurve: finalOut,
1200
- receivedSui: inputAmount - usedSui - feeAmount
1201
- };
1202
- }
1203
- Moonbags.buyExactInReturnsWithLock = buyExactInReturnsWithLock;
1204
- function sellReturns(params) {
1205
- const { amountIn, pool, config } = params;
1206
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1207
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1208
- const realSuiReserves = BigInt(pool.real_sui_reserves.fields.balance);
1209
- let rawSuiOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualTokenReserves, virtualSuiReserves, amountIn);
1210
- if (rawSuiOut > realSuiReserves) rawSuiOut = realSuiReserves;
1211
- const feeAmount = rawSuiOut * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1212
- const finalSuiOut = rawSuiOut - feeAmount;
1213
- return {
1214
- receivedCurve: BigInt(0),
1215
- receivedSui: finalSuiOut
1216
- };
1217
- }
1218
- Moonbags.sellReturns = sellReturns;
1219
- })(MoonbagsPackage.Moonbags || (MoonbagsPackage.Moonbags = {}));
1220
- })(package_MoonbagsPackage || (package_MoonbagsPackage = {}));
1221
- var package_MoonbagsPackage;
1222
- (function(MoonbagsCalculation) {
1223
- async function getCurveAmountAfterBuy(params, suiClient) {
1224
- let { suiAmount, poolId, frontendFee } = params;
1225
- const [poolMoveStruct, configMoveStruct, dynamicVirtualTokenReserves] = await Promise.all([
1226
- getMoveObjectContent(suiClient, poolId),
1227
- getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1228
- package_MoonbagsPackage.Moonbags.getDynamicVirtualTokenReserves(suiClient, poolId)
1229
- ]);
1230
- const pool = poolMoveStruct;
1231
- const config = configMoveStruct;
1232
- if (void 0 !== frontendFee) suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1233
- const usedSui = suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1234
- const { receivedCurve } = package_MoonbagsPackage.Moonbags.buyExactInReturnsWithLock({
1235
- inputAmount: suiAmount,
1236
- amountIn: usedSui,
1237
- pool,
1238
- config,
1239
- dynamicVirtualTokenReserves
1240
- });
1241
- return receivedCurve;
1242
- }
1243
- MoonbagsCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1244
- async function getSuiAmountAfterSell(params, suiClient) {
1245
- const { curveAmount, poolId, frontendFee } = params;
1246
- const [poolMoveStruct, configMoveStruct] = await Promise.all([
1247
- getMoveObjectContent(suiClient, poolId),
1248
- getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID)
1249
- ]);
1250
- const pool = poolMoveStruct;
1251
- const config = configMoveStruct;
1252
- const { receivedSui } = package_MoonbagsPackage.Moonbags.sellReturns({
1253
- amountIn: curveAmount,
1254
- pool,
1255
- config
1256
- });
1257
- if (void 0 !== frontendFee) return getAmountAfterFee(receivedSui, frontendFee);
1258
- return receivedSui;
1259
- }
1260
- MoonbagsCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1261
- async function getUsedSuiForTx(params, suiClient) {
1262
- let { suiAmount, frontendFee } = params;
1263
- const configMoveStruct = await getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID);
1264
- const config = configMoveStruct;
1265
- if (void 0 !== frontendFee) suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1266
- return suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1267
- }
1268
- MoonbagsCalculation.getUsedSuiForTx = getUsedSuiForTx;
1269
- })(calculation_MoonbagsCalculation || (calculation_MoonbagsCalculation = {}));
1270
- var calculation_MoonbagsCalculation;
1271
- (function(MoonbagsTransaction) {
1272
- async function buildBuyTx(params, suiClient) {
1273
- const { tx, coinOut } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
1274
- tiny_invariant(coinOut, "Coin out is required");
1275
- const usedSui = await calculation_MoonbagsCalculation.getUsedSuiForTx({
1276
- suiAmount: BigInt(params.inputAmount),
1277
- frontendFee: params.frontendFee
1278
- }, suiClient);
1279
- const [suiCoin, curveCoin] = tx.moveCall({
1280
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::buy_exact_in_returns_with_lock`,
1281
- typeArguments: [
1282
- params.outCoinType
1283
- ],
1284
- arguments: [
1285
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1286
- tx.object(constants_MoonbagsConstants.LOCK_CONFIG_OBJECT_ID),
1287
- coinOut,
1288
- tx.pure.u64(usedSui),
1289
- tx.pure.u64(params.minAmountOut),
1290
- tx.object(constants_MoonbagsConstants.BURN_MANAGER_OBJECT_ID),
1291
- tx.object(constants_MoonbagsConstants.POOLS_OBJECT_ID),
1292
- tx.object(constants_MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID),
1293
- tx.object(SUI_METADATA_OBJECT_ID),
1294
- tx.object(CLOCK_OBJECT_ID)
1295
- ]
1296
- });
1297
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, suiCoin, params.accountAddress);
1298
- return {
1299
- tx,
1300
- coinOut: curveCoin
1301
- };
1302
- }
1303
- MoonbagsTransaction.buildBuyTx = buildBuyTx;
1304
- async function buildSellTx(params, suiClient) {
1305
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1306
- const { tx, coinData } = await getSplitCoinForTx({
1307
- amount: params.inputAmount,
1308
- coinType: params.inCoinType,
1309
- inheritTx: params.extendTx?.tx,
1310
- account: params.accountAddress,
1311
- splits: [
1312
- params.inputAmount
1313
- ]
1314
- }, suiClient);
1315
- const [inputCoin] = coinData;
1316
- const [suiCoin, curveCoin] = tx.moveCall({
1317
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::sell_returns`,
1318
- typeArguments: [
1319
- params.inCoinType
1320
- ],
1321
- arguments: [
1322
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1323
- inputCoin,
1324
- tx.pure.u64(params.minAmountOut),
1325
- tx.object(CLOCK_OBJECT_ID)
1326
- ]
1327
- });
1328
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, params.inCoinType, curveCoin, params.accountAddress);
1329
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
1330
- }
1331
- MoonbagsTransaction.buildSellTx = buildSellTx;
1332
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1333
- tiny_invariant(coinInType === SUI_TYPE, "coinInType must be SUI for buy transaction");
1334
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1335
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1336
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1337
- const inputAmount = coinInAmount;
1338
- const outputAmount = await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({
1339
- poolId: poolId,
1340
- suiAmount: inputAmount,
1341
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1342
- }, suiClient);
1343
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1344
- let { tx, coinOut } = await buildBuyTx({
1345
- accountAddress: walletAddress,
1346
- inCoinType: coinInType,
1347
- outCoinType: coinOutType,
1348
- inputAmount: inputAmount.toString(),
1349
- minAmountOut: minAmountOut.toString(),
1350
- poolId: poolId,
1351
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1352
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1353
- extendTx: void 0,
1354
- isSponsored: false
1355
- }, suiClient);
1356
- tiny_invariant(coinOut, "Coin out is required");
1357
- tx.transferObjects([
1358
- coinOut
1359
- ], tx.pure.address(walletAddress));
1360
- tx.setSender(walletAddress);
1361
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1362
- tx = await addGasFee({
1363
- inheritTx: tx,
1364
- sender: walletAddress,
1365
- feeAmount,
1366
- suiInputAmount: inputAmount
1367
- }, suiClient);
1368
- return tx.build({
1369
- client: suiClient
1370
- });
1371
- }
1372
- MoonbagsTransaction.getBuyTransaction = getBuyTransaction;
1373
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1374
- tiny_invariant(coinOutType === SUI_TYPE, "coinOutType must be SUI for sell transaction");
1375
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1376
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1377
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1378
- const inputAmount = coinInAmount;
1379
- const outputAmount = await calculation_MoonbagsCalculation.getSuiAmountAfterSell({
1380
- poolId: poolId,
1381
- curveAmount: inputAmount,
1382
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1383
- }, suiClient);
1384
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1385
- let { tx, coinOut } = await buildSellTx({
1386
- accountAddress: walletAddress,
1387
- inCoinType: coinInType,
1388
- outCoinType: coinOutType,
1389
- inputAmount: inputAmount.toString(),
1390
- minAmountOut: minAmountOut.toString(),
1391
- poolId: poolId,
1392
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1393
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1394
- extendTx: void 0,
1395
- isSponsored: false
1396
- }, suiClient);
1397
- tiny_invariant(coinOut, "Coin out is required");
1398
- tx.transferObjects([
1399
- coinOut
1400
- ], tx.pure.address(walletAddress));
1401
- tx.setSender(walletAddress);
1402
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1403
- tx = await addGasFee({
1404
- inheritTx: tx,
1405
- sender: walletAddress,
1406
- feeAmount
1407
- }, suiClient);
1408
- return tx.build({
1409
- client: suiClient
1410
- });
1411
- }
1412
- MoonbagsTransaction.getSellTransaction = getSellTransaction;
1413
- })(transaction_MoonbagsTransaction || (transaction_MoonbagsTransaction = {}));
1414
- var transaction_MoonbagsTransaction;
1415
- const CONSTANTS = {
1416
- GAS_FEE_BUFFER_PERCENTAGE: 0.1
1417
- };
1418
- class DraftTransferTx {
1419
- suiClient;
1420
- constructor(suiClient){
1421
- this.suiClient = suiClient;
1422
- }
1423
- validatePrivateKey(privateKey, expectedSender) {
1424
- tiny_invariant(privateKey?.trim(), "Private key is required");
1425
- const keypair = Ed25519Keypair.fromSecretKey(privateKey);
1426
- const derivedAddress = keypair.getPublicKey().toSuiAddress();
1427
- if (derivedAddress !== expectedSender) throw new Error(`Private key mismatch. Expected: ${expectedSender}, Got: ${derivedAddress}`);
1428
- return keypair;
1429
- }
1430
- async createDraft(sender, recipient, amountMIST) {
1431
- tiny_invariant(sender?.trim(), "Sender address is required");
1432
- tiny_invariant(recipient?.trim(), "Recipient address is required");
1433
- tiny_invariant(sender !== recipient, "Sender and recipient cannot be the same");
1434
- tiny_invariant(amountMIST > 0n, "Transfer amount must be at least 1 MIST");
1435
- try {
1436
- let transaction = new Transaction();
1437
- const [coin] = transaction.splitCoins(transaction.gas, [
1438
- amountMIST
1439
- ]);
1440
- transaction.transferObjects([
1441
- coin
1442
- ], recipient);
1443
- transaction.setSender(sender);
1444
- const referenceGasPrice = await this.suiClient.getReferenceGasPrice();
1445
- transaction.setGasPrice(referenceGasPrice);
1446
- const feeAmount = await getNeededGasFee(this.suiClient, transaction, sender, CONSTANTS.GAS_FEE_BUFFER_PERCENTAGE);
1447
- transaction = await addGasFee({
1448
- inheritTx: transaction,
1449
- sender,
1450
- feeAmount,
1451
- suiInputAmount: amountMIST
1452
- }, this.suiClient);
1453
- const txBytes = await transaction.build({
1454
- client: this.suiClient
1455
- });
1456
- const txDraftBase64 = Buffer.from(txBytes).toString("base64");
1457
- const txDigest = await transaction.getDigest();
1458
- return {
1459
- sender,
1460
- recipient,
1461
- amountMIST,
1462
- txDraftBase64,
1463
- txDigest
1464
- };
1465
- } catch (error) {
1466
- throw new Error(`Failed to create draft transaction: ${error instanceof Error ? error.message : "Unknown error"}`);
1467
- }
1468
- }
1469
- async execute(draftTx, privateKey) {
1470
- try {
1471
- tiny_invariant(draftTx, "Draft transaction is required");
1472
- tiny_invariant(draftTx.txDraftBase64?.trim(), "Transaction data is required");
1473
- const keypair = this.validatePrivateKey(privateKey, draftTx.sender);
1474
- const txBytes = fromBase64(draftTx.txDraftBase64);
1475
- const { signature } = await keypair.signTransaction(txBytes);
1476
- const result = await this.suiClient.executeTransactionBlock({
1477
- transactionBlock: txBytes,
1478
- signature
1479
- });
1480
- return {
1481
- success: true,
1482
- txDigest: result.digest,
1483
- effects: result.effects
1484
- };
1485
- } catch (error) {
1486
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1487
- return {
1488
- success: false,
1489
- error: errorMessage
1490
- };
1491
- }
1492
- }
1493
- async getTransactionStatus(txDigest) {
1494
- tiny_invariant(txDigest?.trim(), "Transaction digest is required");
1495
- try {
1496
- const txResponse = await this.suiClient.getTransactionBlock({
1497
- digest: txDigest,
1498
- options: {
1499
- showEffects: true
1500
- }
1501
- });
1502
- if (!txResponse?.effects?.status) return "pending";
1503
- return "success" === txResponse.effects.status.status ? "success" : "failure";
1504
- } catch (error) {
1505
- if (error instanceof Error) {
1506
- if (error.message.includes("not found") || error.message.includes("Could not find")) return "pending";
1507
- }
1508
- return "failure";
1509
- }
1510
- }
1511
- }
1512
- export { aftermath_AftermathAggregator as AftermathAggregator, astros_AstrosAggregator as AstrosAggregator, BASE_BPS, BLUEFIN_PACKAGE_ID, constants_BlastFunConstants as BlastFunConstants, custom_calculation_BlastFunCustomCalculation as BlastFunCustomCalculation, custom_transaction_BlastFunCustomTransaction as BlastFunCustomTransaction, package_BlastFunPackage as BlastFunPackage, sdk_calculation_BlastFunSDKCalculation as BlastFunSDKCalculation, sdk_transaction_BlastFunSDKTransaction as BlastFunSDKTransaction, bluefin_BluefinTx as BluefinTx, package_Bps as Bps, CLOCK_OBJECT_ID, cetus_CetusAggregator as CetusAggregator, DraftTransferTx, flowx_FlowXAggregator as FlowXAggregator, package_MathUtils as MathUtils, calculation_MoonbagsCalculation as MoonbagsCalculation, constants_MoonbagsConstants as MoonbagsConstants, package_MoonbagsPackage as MoonbagsPackage, transaction_MoonbagsTransaction as MoonbagsTransaction, NATIVE_USDC_TOKEN_TYPE, SUI_FULL_TYPE, SUI_METADATA_OBJECT_ID, SUI_TYPE, _7k_SevenKAggregator as SevenKAggregator, common_SupportedAggregator as SupportedAggregator, types_SupportedBondingCurve as SupportedBondingCurve, types_TradeFeeOptions as TradeFeeOptions, USDC_TOKEN_TYPE, adaptSuiClient, adaptTransaction, addGasFee, createCompatibleSuiClient, getAmountAfterFee, getCoinObjectIdsByAmount, getMemezPumpSDK, getMoveObject, getMoveObjectContent, getNeededGasFee, getSplitCoinForTx, getSplitCoinsAfterFee, splitSuiCoinAfterFeeFromBuyTx, splitSuiCoinAfterFeeFromSellTx };
1
+ import{BluefinXTx as e,Config as t,buildTx as n,getQuote as i}from"@7kprotocol/sdk-ts/cjs";import{Transaction as o}from"@mysten/sui/transactions";import r from"bignumber.js";import{Aftermath as a,Helpers as u}from"aftermath-ts-sdk";import{buildSwapPTBFromQuote as s,getCoins as c,getQuote as l}from"@naviprotocol/astros-aggregator-sdk";import{AggregatorClient as d,Env as f}from"@cetusprotocol/aggregator-sdk";import m from"bn.js";import{AggregatorQuoter as g,Coin as p,Commission as I,CommissionType as _,TradeBuilder as C}from"@flowx-finance/sdk";import A from"@minswap/tiny-invariant";import{fromBase64 as h,normalizeStructTag as y}from"@mysten/sui/utils";import{MemezPumpSDK as b}from"@interest-protocol/memez-fun-sdk";import{Network as T}from"@interest-protocol/sui-core-sdk";import{getFullnodeUrl as B}from"@mysten/sui/client";import{Ed25519Keypair as O}from"@mysten/sui/keypairs/ed25519";class F{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}async getTradeRoute({coinInAmount:e,coinInType:n,coinOutType:o,tradeFee:r}){try{this._config.sevenKApiKey&&t.setApiKey(this._config.sevenKApiKey);let a=r?r.tradeFeePercent:this._config.defaultTradeFee.tradeFeePercent;return i({tokenIn:n,tokenOut:o,amountIn:e.toString(),commissionBps:1e4*a})}catch(e){return null}}async getTransaction({walletAddress:t,completeRoute:i,slippage:r,tradeFee:a}){let u,s;a?(u=a.tradeFeePercent,s=a.tradeFeeRecipientAddress):(u=this._config.defaultTradeFee.tradeFeePercent,s=this._config.defaultTradeFee.tradeFeeRecipientAddress);let c=await n({quoteResponse:i,slippage:r,accountAddress:t,commission:{partner:s,commissionBps:1e4*u}});return c.tx instanceof e?o.from(c.tx.txBytes).build({client:this._suiClient}):(c.tx.setSender(t),c.tx.build({client:this._suiClient}))}}(F||(F={})).toCommonTradeRoutes=function(e){let t=[];if(!e.routes||0===e.routes.length)return null;for(let n of e.routes){let e=[],i={};for(let t of n.hops){for(let e of t.pool.allTokens)i[e.address]=e.decimal;let n=i[t.tokenIn]??0,o=i[t.tokenOut]??0,a=BigInt(new r(t.tokenInAmount).multipliedBy(10**n).toFixed(0,3)),u=BigInt(new r(t.tokenOutAmount).multipliedBy(10**o).toFixed(0,3));e.push({poolAddress:t.poolId,coinIn:t.tokenIn,coinOut:t.tokenOut,amountIn:a,amountOut:u})}if(0===e.length)continue;let o=i[n.tokenIn]??0,a=i[n.tokenOut]??0,u=BigInt(new r(n.tokenInAmount).multipliedBy(10**o).toFixed(0,3)),s=BigInt(new r(n.tokenOutAmount).multipliedBy(10**a).toFixed(0,3));t.push({paths:e,coinIn:n.tokenIn,coinOut:n.tokenOut,amountIn:u,amountOut:s})}return 0===t.length?null:{coinIn:e.tokenIn,coinOut:e.tokenOut,amountIn:BigInt(e.swapAmountWithDecimal),amountOut:BigInt(e.returnAmountWithDecimal),routes:t}};class v{_config;_aftermathClient;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}async aftermathClient(){if(this._aftermathClient)return this._aftermathClient;if(this._config.aftermathApiEndpoint?this._aftermathClient=new a(this._config.aftermathApiEndpoint):this._aftermathClient=new a("MAINNET"),await this._aftermathClient.init(),this._config.aftermathApiKey){let e=u.keypairFromPrivateKey(this._config.aftermathApiKey);await this._aftermathClient.Auth().init({async signMessageCallback({message:t}){let{signature:n}=await e.signPersonalMessage(t);return{signature:n}},walletAddress:e.toSuiAddress()})}return this._aftermathClient}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:i}){let o;return o=i?{recipient:i.tradeFeeRecipientAddress,feePercentage:i.tradeFeePercent}:{recipient:this._config.defaultTradeFee.tradeFeeRecipientAddress,feePercentage:this._config.defaultTradeFee.tradeFeePercent},(await this.aftermathClient()).Router().getCompleteTradeRouteGivenAmountIn({coinInAmount:e,coinInType:t,coinOutType:n,externalFee:o})}async getTransaction({completeRoute:e,walletAddress:t,slippage:n}){let i=await this.aftermathClient(),o=await i.Router().getTransactionForCompleteTradeRoute({completeRoute:e,walletAddress:t,slippage:n,isSponsoredTx:!1});return o.setSender(t),o.build({client:this._suiClient})}}(v||(v={})).toCommonTradeRoutes=function(e){if(0===e.routes.length)return null;let t=[];for(let n of e.routes){let e=[];for(let t of n.paths)e.push({poolAddress:t.poolId,coinIn:t.coinIn.type,coinOut:t.coinOut.type,amountIn:BigInt(t.coinIn.amount),amountOut:BigInt(t.coinOut.amount)});0!==e.length&&t.push({paths:e,coinIn:n.coinIn.type,coinOut:n.coinOut.type,amountIn:n.coinIn.amount,amountOut:n.coinOut.amount})}return 0===t.length?null:{coinIn:e.coinIn.type,coinOut:e.coinOut.type,amountIn:e.coinIn.amount,amountOut:e.coinOut.amount,routes:t}};class w{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:i}){try{let o;return o=i?{fee:i.tradeFeePercent,receiverAddress:i.tradeFeeRecipientAddress}:{fee:this._config.defaultTradeFee.tradeFeePercent,receiverAddress:this._config.defaultTradeFee.tradeFeeRecipientAddress},l(t,n,e,this._config.astrosApiKey,{byAmountIn:!0,serviceFee:o})}catch(e){return null}}returnMergedCoins(e,t,n){if(t.length<2)return e.object(t[0].coinObjectId);let i=0,o=[];t.sort((e,t)=>Number(t.balance)-Number(e.balance)).slice(1).forEach(e=>{i>=n||(i+=Number(e.balance),o.push(e.coinObjectId))});let r=t[0].coinObjectId;return e.mergeCoins(r,o),e.object(r)}async getTransaction({completeRoute:e,walletAddress:t,slippage:n,tradeFee:i}){var a;let u,l;u=i?{fee:i.tradeFeePercent,receiverAddress:i.tradeFeeRecipientAddress}:{fee:this._config.defaultTradeFee.tradeFeePercent,receiverAddress:this._config.defaultTradeFee.tradeFeeRecipientAddress};let d=new r(e.amount_out).multipliedBy(1-n-u.fee).toNumber(),f=new o;if("0x2::sui::SUI"===(a=e.from)||"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI"===a)l=f.splitCoins(f.gas,[f.pure.u64(e.amount_in)]);else{let n=await c(this._suiClient,t,e.from),i=this.returnMergedCoins(f,n.data,Number.parseFloat(e.amount_in));l=f.splitCoins(i,[f.pure.u64(e.amount_in)])}let m=await s(t,f,d,l,e,void 0,!1,this._config.astrosApiKey,{serviceFee:u});return f.transferObjects([m],t),f.setSender(t),f.build({client:this._suiClient})}}(w||(w={})).toCommonTradeRoutes=function(e,t,n){if(0===e.routes.length)return null;let i=[];for(let t of e.routes){let e=[];for(let n of t.path)e.push({poolAddress:n.id,coinIn:n.from,coinOut:n.target,amountIn:BigInt(n.amount_in),amountOut:BigInt(n.amount_out)});0!==e.length&&i.push({amountIn:BigInt(t.amount_in),amountOut:BigInt(t.amount_out),coinIn:e[0].coinIn,coinOut:e[e.length-1].coinOut,paths:e})}return 0===i.length?null:{coinIn:t,coinOut:n,amountIn:BigInt(e.amount_in),amountOut:BigInt(e.amount_out),routes:i}},(L||(L={})).equals=function(e,t){return e.tradeFeePercent===t.tradeFeePercent&&e.tradeFeeRecipientAddress===t.tradeFeeRecipientAddress};class S{_config;_suiClient;_cetusClient;constructor(e,t){this._config=e,this._suiClient=t}cetusClient(e,t){return t&&!L.equals(t,this._config.defaultTradeFee)?new d({client:this._suiClient,overlayFeeReceiver:t.tradeFeeRecipientAddress,overlayFeeRate:t.tradeFeePercent,env:f.Mainnet,signer:e,...this._config.cetusApiKey&&this._config.cetusApiEndpoint?{apiKey:this._config.cetusApiKey,endpoint:this._config.cetusApiEndpoint}:{},partner:this._config.cetusPartnerId}):(this._cetusClient||(this._cetusClient=new d({client:this._suiClient,overlayFeeReceiver:this._config.defaultTradeFee.tradeFeeRecipientAddress,overlayFeeRate:this._config.defaultTradeFee.tradeFeePercent,env:f.Mainnet,signer:e,...this._config.cetusApiKey&&this._config.cetusApiEndpoint?{apiKey:this._config.cetusApiKey,endpoint:this._config.cetusApiEndpoint}:{},partner:this._config.cetusPartnerId})),this._cetusClient)}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:i}){return this.cetusClient(void 0,i).findRouters({from:t,target:n,amount:new m(e.toString()),byAmountIn:!0})}async getTransaction({completeRoute:e,walletAddress:t,slippage:n,tradeFee:i}){let r=new o,a=this.cetusClient(t,i);return await a.fastRouterSwap({router:e,txb:r,slippage:n}),await a.devInspectTransactionBlock(r),r.setSender(t),r.build({client:this._suiClient})}}(S||(S={})).toCommonTradeRoutes=function(e,t,n){if(0===e.paths.length)return null;let i=[],o=[],r=[];for(let t=0;t<e.paths.length;t++){let n=e.paths[t],i={poolAddress:n.id,amountIn:BigInt(n.amountIn),amountOut:BigInt(n.amountOut),coinIn:n.from,coinOut:n.target};if(r.push(i),t===e.paths.length-1)o.push([...r]);else{let i=e.paths[t+1];n.target!==i.from&&(o.push([...r]),r=[])}}for(let e of o)0!==e.length&&i.push({amountIn:e[0].amountIn,amountOut:e[e.length-1].amountOut,coinIn:e[0].coinIn,coinOut:e[e.length-1].coinOut,paths:e});return 0===i.length?null:{coinIn:t,coinOut:n,amountIn:BigInt(e.amountIn.toString(10)),amountOut:BigInt(e.amountOut.toString(10)),routes:i}};var x,E,R,P,k,D,M,N,U,j,K,q,G,z,L,J,$,V,W,Z,X,Y,H,Q,ee,et,en,ei,eo=((z={}).ASTROS="ASTROS",z.AFTERMATH="AFTERMATH",z.SEVENK="7K",z.CETUS="CETUS",z.FLOWX="FLOWX",z);class er{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}getCommission(e,t){let n,i;return t?(n=t.tradeFeePercent,i=t.tradeFeeRecipientAddress):(n=this._config.defaultTradeFee.tradeFeePercent,i=this._config.defaultTradeFee.tradeFeeRecipientAddress),new I(i,new p(e),_.PERCENTAGE,1e6*n,!0)}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:i}){let o=new g("mainnet",this._config.flowxApiKey);try{return o.getRoutes({tokenIn:t,tokenOut:n,amountIn:e.toString(),commission:this.getCommission(t,i)})}catch(e){return null}}async getTransaction({walletAddress:e,completeRoute:t,slippage:n,tradeFee:i}){return new C("mainnet",t.routes).sender(e).slippage(1e6*n).commission(this.getCommission(t.coinIn.coinType,i)).build().buildTransaction({client:this._suiClient}).then(t=>(t.setSender(e),t.build({client:this._suiClient})))}}async function ea(e,t){return(await eu(e,t)).fields}async function eu(e,t){let n=await e.getObject({id:t,options:{showContent:!0}}),i=n.data?.content;return A(i,"Pool object not found or has no content"),A("moveObject"===i.dataType,"Object is not a Move object"),i}(er||(er={})).toCommonTradeRoutes=function(e){if(0===e.routes.length)return null;let t=[];for(let n of e.routes){let e=[];for(let t of n.paths)e.push({amountIn:BigInt(t.amountIn.toString()),amountOut:BigInt(t.amountOut.toString()),coinIn:t.input.coinType,coinOut:t.output.coinType,poolAddress:t.pool.id});0!==e.length&&t.push({amountIn:BigInt(n.amountIn.toString()),amountOut:BigInt(n.amountOut.toString()),coinIn:n.input.coinType,coinOut:n.output.coinType,paths:e})}return 0===t.length?null:{coinIn:e.coinIn.coinType,coinOut:e.coinOut.coinType,amountIn:BigInt(e.amountIn.toString()),amountOut:BigInt(e.amountOut.toString()),routes:t}},(x=J||(J={})).PACKAGE_ID_V4="0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd",x.MEMEZ_AV_OBJECT_ID="0x2319e3e76dfad73d8f4684bdbf42be4f32d8ce4521dd61becc8261dc918d82c0";let es=1e4;function ec(e,t){let n=BigInt(e),i=BigInt(Number(t)*es);if(i===BigInt(0))return[n.toString()];let o=n*i/BigInt(es);return[(n-o).toString(),o.toString()]}function el(e,t){if(!t||0>=Number(t))return BigInt(e);let n=BigInt(e),i=BigInt(Number(t)*es);if(i===BigInt(0))return n;let o=n*i/BigInt(es);return n-o}async function ed(e,t,n,i){let{effects:{gasUsed:o,status:r}}=await e.devInspectTransactionBlock({sender:n,transactionBlock:t});if("success"!==r.status)throw Error(`Transaction failed during dev inspect: ${r.error??""}`);let a=BigInt(o.computationCost)+BigInt(o.storageCost)-BigInt(o.storageRebate),u=BigInt(Number(i)*es);return a*(BigInt(es)+u)/BigInt(es)}((E=$||($={})).U64||(E.U64={})).mulDivUp=function(e,t,n){let i=BigInt(0);return e*t%n>BigInt(0)&&(i=BigInt(1)),e*t/n+i};var ef=V||(V={});function em(e){return A(BigInt(e)<=BigInt(1e4),"Bps overflow"),BigInt(e)}ef.calcUp=function(e,t){let n,i=BigInt(e.pos0),o=BigInt(1e4);return n=i*t%o!==BigInt(0)?BigInt(1):BigInt(0),i*t/o+n},ef.sub=function(e,t){return A(BigInt(e.pos0)>=BigInt(t.pos0),"Bps underflow"),{pos0:(BigInt(e.pos0)-BigInt(t.pos0)).toString()}},ef.value=function(e){return BigInt(e.pos0)},ef.new_=function(e){return{pos0:em(e).toString()}},ef.assertOverflow=em,((R=W||(W={})).MemezFun||(R.MemezFun={})).isSniperProtectedMemezFun=async function(e,t){return(await ea(e,t)).public_key.length>0},(P=R.MemezFees||(R.MemezFees={})).takeWithDiscount=function(e,t,n){if("Value"===e.variant){let n=BigInt(e.fields.pos0);if(n===BigInt(0))return BigInt(0);if(t>=n)return n;throw Error(`Insufficient amount to cover fee. Required: ${n}, provided: ${t}`)}if("Percentage"===e.variant){let i=e.fields.pos0.fields;if(BigInt(i.pos0)===BigInt(0))return BigInt(0);let o=V.calcUp(V.sub(i,n),t);if(t>=o)return o;throw Error(`Insufficient amount to cover fee. Required: ${o}, provided: ${t}`)}throw Error("Unknown fee variant")},P.calculateWithDiscount=function(e,t,n){if("Value"===e.variant)return BigInt(e.fields.pos0);if("Percentage"===e.variant){let i=e.fields.pos0.fields;return V.calcUp(V.sub(i,t),n)}throw Error("Unknown fee variant")},(R.MemezBurner||(R.MemezBurner={})).calculate=function(e,t){if(V.value(e.fee.fields)===BigInt(0)||t===BigInt(0)||t>=BigInt(e.target_liquidity))return V.new_(0);let n=BigInt(1e4);return V.new_($.U64.mulDivUp(V.value(e.fee.fields),$.U64.mulDivUp(t,n,BigInt(e.target_liquidity)),n))},(k=R.MemezPump||(R.MemezPump={})).getPumpState=async function(e,t){return await ea(e,t.inner_state)},k.pump=function(e,t){let n=e.constant_product.fields,i=R.MemezFees.takeWithDiscount(n.quote_swap_fee,t,n.quote_referrer_fee.fields),o=t-i,r=BigInt(n.meme_balance),a=BigInt(n.quote_balance),u=r*o/(BigInt(n.virtual_liquidity)+a+o),s=R.MemezFees.takeWithDiscount(n.meme_swap_fee,u,n.meme_referrer_fee.fields);return u-s},k.dump=function(e,t){let n=e.constant_product.fields,i=R.MemezFees.takeWithDiscount(n.meme_swap_fee,t,n.meme_referrer_fee.fields),o=t-i,r=BigInt(n.meme_balance),a=BigInt(n.quote_balance),u=BigInt(n.virtual_liquidity),s=R.MemezBurner.calculate(n.burner.fields,a),c=V.calcUp(s,o),l=o-(V.value(s)!==BigInt(0)?c:BigInt(0)),d=(u+a)*l/(r+l);d>a&&(d=a);let f=R.MemezFees.takeWithDiscount(n.quote_swap_fee,d,n.quote_referrer_fee.fields);return d-f},(D=Z||(Z={})).getCurveAmountAfterBuy=async function(e,t){let{suiAmount:n,poolId:i,frontendFee:o}=e,r=await ea(t,i),a=await W.MemezPump.getPumpState(t,r);return n=el(n,o),W.MemezPump.pump(a,n)},D.getSuiAmountAfterSell=async function(e,t){let{curveAmount:n,poolId:i,frontendFee:o}=e,r=await ea(t,i),a=await W.MemezPump.getPumpState(t,r);return el(W.MemezPump.dump(a,n),o)};let eg="0x2::sui::SUI",ep="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",eI="0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",e_="0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",eC="0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3",eA="0x0000000000000000000000000000000000000000000000000000000000000006",eh=async(e,t,n,i)=>{let o,r=[],a=!0;for(;a;)try{let n=await e.getCoins({owner:t,coinType:i,cursor:o});r=[...r,...n.data],a=n.hasNextPage,o=n.nextCursor}catch(e){console.error("Error fetching data:",e),a=!1}let u=((e,t,n)=>{let i;if(e?.length){do{i=!1;for(let o=0;o<e.length-1;o++){let r=BigInt(e[o][t]),a=BigInt(e[o+1][t]);if("desc"===n?r<a:r>a){let t=e[o];e[o]=e[o+1],e[o+1]=t,i=!0}}}while(i);return e}})(r.map(e=>({...e,balance:e.balance})),"balance","desc")??[],s="0",c=[],l=[];for(let e of u)if(s=(BigInt(e.balance)+BigInt(s)).toString(10),c.push(e.coinObjectId),l.push(e),BigInt(s)>=BigInt(n))break;return{objectIds:c,balance:s,objectCoins:l}};async function ey(e,t){let{account:n,amount:i,splits:r,coinType:a,inheritTx:u,inspecTransaction:s,isSponsored:c=!1}=e,l=u??new o,{objectIds:d}=await eh(t,n,i,a),f=d[0];if(y(a)===y(ep)&&!c){let e;return s?(d.length>1&&l.mergeCoins(l.object(f),d.slice(1).map(e=>l.object(e))),e=l.splitCoins(l.object(f),r)):e=l.splitCoins(l.gas,r),{tx:l,coinData:e}}d.length>1&&l.mergeCoins(l.object(f),d.slice(1).map(e=>l.object(e)));let m=l.splitCoins(l.object(f),r);return{tx:l,coinData:m}}let eb="0x62412b7268c35f3808336aee57a52836501f40b8ba5d936f8ad275e672befd04";async function eT(e,t){let n,i,{inputAmount:r,accountAddress:a,frontendFee:u,frontendFeeRecipient:s,extendTx:c,isSponsored:l}=e;A(e.inCoinType===ep||e.inCoinType===eg,"Input must be SUI");let{tx:d,coinIn:f}=c||{},m=ec(r,u||"0"),g=d||new o;if(f)n=g.splitCoins(f,m),X.transferOrDestroyZeroCoin(g,ep,f,a);else{let{coinData:e}=await ey({account:a,amount:r,splits:m,coinType:ep,inheritTx:g,isSponsored:l||!1},t);n=e}if(u&&s){let[e,t]=n;i=e,g.transferObjects([t],g.pure.address(s||a))}else[i]=n;return{tx:g,coinOut:i}}async function eB(e,t,n){if(A(t.outCoinType===ep||t.outCoinType===eg,"Output must be SUI"),0>=Number(t.frontendFee||0))return{tx:e,coinOut:n};let i=e.moveCall({target:"0x2::coin::value",typeArguments:[t.outCoinType],arguments:[n]}),o=e.moveCall({target:`${eb}::math::mul_div_u64`,typeArguments:[],arguments:[i,e.pure.u64(BigInt(Number(t.frontendFee||"0")*es)),e.pure.u64(BigInt(es))]}),r=e.moveCall({target:"0x2::coin::split",typeArguments:[t.outCoinType],arguments:[n,o]});return e.transferObjects([r],e.pure.address(t.frontendFeeRecipient||t.accountAddress)),{tx:e,coinOut:n}}(X||(X={})).transferOrDestroyZeroCoin=function(e,t,n,i){e.moveCall({target:`${eb}::utils::transfer_or_destroy`,typeArguments:[t],arguments:[n,e.pure.address(i)]})};var eO=Y||(Y={});async function eF(e){let t=e||new o;return t.moveCall({target:`${J.PACKAGE_ID_V4}::memez_allowed_versions::get_allowed_versions`,arguments:[t.object(J.MEMEZ_AV_OBJECT_ID)],typeArguments:[]})}eO.getAllowedVersions=eF,eO.buildBuyTx=async function(e,t){A(!await W.MemezFun.isSniperProtectedMemezFun(t,e.poolId),"This coin is a sniper protected coin, please use the Blast Fun website to trade it.");let{tx:n,coinOut:i}=await eT(e,t);A(i,"Coin out is required");let o=n.moveCall({target:`${J.PACKAGE_ID_V4}::memez_pump::pump`,typeArguments:[e.outCoinType,ep],arguments:[n.object(e.poolId),i,n.pure.vector("address",[]),n.pure.vector("vector<u8>",[]),n.pure.u64(e.minAmountOut),await eF(n)]});return{tx:n,coinOut:o}},eO.buildSellTx=async function(e,t){A(e.outCoinType===ep||e.outCoinType===eg,"Output must be SUI");let n=await ea(t,e.poolId),{tx:i,coinData:o}=await ey({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},t),[r]=o,[a]=i.moveCall({target:`${J.PACKAGE_ID_V4}::memez_pump::dump`,typeArguments:[e.inCoinType,e.outCoinType],arguments:[i.object(e.poolId),i.object(n.ipx_meme_coin_treasury),r,i.pure.vector("address",[]),i.pure.u64(e.minAmountOut),await eF(i)]});return await eB(i,e,a)};let ev=new b({network:T.MAINNET,fullNodeUrl:B("mainnet")});function ew(){return ev}async function eS(e,t){let{inheritTx:n,sender:i,feeAmount:r,suiInputAmount:a}=e,u=n||new o;u.setGasBudget(r);let{objectCoins:s}=await eh(t,i,(BigInt(a||"0")+r).toString(),ep);return u.setGasPayment(s.map(e=>({objectId:e.coinObjectId,version:e.version,digest:e.digest}))),u}(M=H||(H={})).getCurveAmountAfterBuy=async function(e){let{suiAmount:t,poolId:n,frontendFee:i}=e;t=el(t,i);let{memeAmountOut:o}=await ew().quotePump({pool:n,amount:t});return o},M.getSuiAmountAfterSell=async function(e){let{curveAmount:t,poolId:n,frontendFee:i}=e,{quoteAmountOut:o}=await ew().quoteDump({pool:n,amount:t});return el(o,i)};var ex=Q||(Q={});async function eE(e,t){let{tx:n,coinOut:i}=await eT(e,t);A(i,"Coin out is required");let{memeCoin:o,tx:r}=await ew().pump({pool:e.poolId,quoteCoin:i,minAmountOut:e.minAmountOut,tx:n});return{tx:r,coinOut:o}}async function eR(e,t){A(e.outCoinType===ep||e.outCoinType===eg,"Output must be SUI");let{tx:n,coinData:i}=await ey({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},t),[o]=i,{quoteCoin:r,tx:a}=await ew().dump({pool:e.poolId,memeCoin:o,tx:n,minAmountOut:e.minAmountOut});return await eB(a,e,r)}ex.buildBuyTx=eE,ex.buildSellTx=eR,ex.getBuyTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:n,poolId:i,slippage:o,walletAddress:a,tradeFee:u},s){A(t===eg,"coinInType must be SUI for buy transaction"),A(n!==t,"coinOutType must be different from coinInType"),A(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),A(e>0,"coinInAmount must be greater than 0");let c=BigInt(new r((await H.getCurveAmountAfterBuy({poolId:i,suiAmount:e,frontendFee:u?u.tradeFeePercent:void 0})).toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await eE({accountAddress:a,inCoinType:t,outCoinType:n,inputAmount:e.toString(),minAmountOut:c.toString(),poolId:i,frontendFee:u?u.tradeFeePercent:void 0,frontendFeeRecipient:u?u.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},s);A(d,"Coin out is required"),l.transferObjects([d],l.pure.address(a)),l.setSender(a);let f=await ed(s,l,a,0);return(l=await eS({inheritTx:l,sender:a,feeAmount:f,suiInputAmount:e},s)).build({client:s})},ex.getSellTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:n,poolId:i,slippage:o,walletAddress:a,tradeFee:u},s){A(n===eg,"coinOutType must be SUI for sell transaction"),A(n!==t,"coinOutType must be different from coinInType"),A(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),A(e>0,"coinInAmount must be greater than 0");let c=BigInt(new r((await H.getSuiAmountAfterSell({poolId:i,curveAmount:e,frontendFee:u?u.tradeFeePercent:void 0})).toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await eR({accountAddress:a,inCoinType:t,outCoinType:n,inputAmount:e.toString(),minAmountOut:c.toString(),poolId:i,frontendFee:u?u.tradeFeePercent:void 0,frontendFeeRecipient:u?u.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},s);A(d,"Coin out is required"),l.transferObjects([d],l.pure.address(a)),l.setSender(a);let f=await ed(s,l,a,0);return(l=await eS({inheritTx:l,sender:a,feeAmount:f},s)).build({client:s})};var eP=((N={}).BLAST_FUN="BLAST_FUN",N.MOONBAGS="MOONBAGS",N);(U=ee||(ee={})).PACKAGE_ID="0xb8df325010942634a4afb3db3901ee215546af43a4ec4af781e7213b0bba7290",U.CONFIG_OBJECT_ID="0x74aecf86067c6913960ba4925333aefd2b1f929cafca7e21fd55a8f244b70499",U.LOCK_CONFIG_OBJECT_ID="0xfb09822d9808980abd04c51321adb850701f5f55535c6206658ef4d910c3e9be",U.BURN_MANAGER_OBJECT_ID="0x1d94aa32518d0cb00f9de6ed60d450c9a2090761f326752ffad06b2e9404f845",U.POOLS_OBJECT_ID="0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",U.GLOBAL_CONFIG_OBJECT_ID="0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",U.FEE_DENOMINATOR=BigInt(1e4),(K=(j=et||(et={})).Curves||(j.Curves={})).calculateAddLiquidityCost=function(e,t,n){return e*t/(t-n)-e},K.calculateRemoveLiquidityReturn=function(e,t,n){return t-e*t/(e+n)},K.calculateTokenAmountReceived=function(e,t,n){return t-e*t/(e+n)},(q=j.Moonbags||(j.Moonbags={})).getDynamicVirtualTokenReserves=async function(e,t){let n=await e.getDynamicFieldObject({parentId:t,name:{type:"vector<u8>",value:"virtual_token_reserves"}});if(n.data)return BigInt(n.data.content.fields.value)},q.buyExactInReturnsWithLock=function(e){let{inputAmount:t,amountIn:n,pool:i,config:o,dynamicVirtualTokenReserves:r}=e,a=BigInt(i.virtual_sui_reserves),u=BigInt(i.virtual_token_reserves),s=BigInt(i.remain_token_reserves.fields.balance),c=j.Curves.calculateRemoveLiquidityReturn(a,u,n),l=u-(r||s),d=c,f=n;c>l&&(d=l,f=j.Curves.calculateAddLiquidityCost(a,u,l)+BigInt(1));let m=f*BigInt(o.platform_fee)/ee.FEE_DENOMINATOR;return A(t>=f+m,"Input amount is less than used SUI + fee"),{receivedCurve:d,receivedSui:t-f-m}},q.sellReturns=function(e){let{amountIn:t,pool:n,config:i}=e,o=BigInt(n.virtual_sui_reserves),r=BigInt(n.virtual_token_reserves),a=BigInt(n.real_sui_reserves.fields.balance),u=j.Curves.calculateRemoveLiquidityReturn(r,o,t);u>a&&(u=a);let s=u*BigInt(i.platform_fee)/ee.FEE_DENOMINATOR,c=u-s;return{receivedCurve:BigInt(0),receivedSui:c}},(G=en||(en={})).getCurveAmountAfterBuy=async function(e,t){let{suiAmount:n,poolId:i,frontendFee:o}=e,[r,a,u]=await Promise.all([ea(t,i),ea(t,ee.CONFIG_OBJECT_ID),et.Moonbags.getDynamicVirtualTokenReserves(t,i)]);void 0!==o&&(n=el(n,o));let s=n*ee.FEE_DENOMINATOR/(ee.FEE_DENOMINATOR+BigInt(a.platform_fee)),{receivedCurve:c}=et.Moonbags.buyExactInReturnsWithLock({inputAmount:n,amountIn:s,pool:r,config:a,dynamicVirtualTokenReserves:u});return c},G.getSuiAmountAfterSell=async function(e,t){let{curveAmount:n,poolId:i,frontendFee:o}=e,[r,a]=await Promise.all([ea(t,i),ea(t,ee.CONFIG_OBJECT_ID)]),{receivedSui:u}=et.Moonbags.sellReturns({amountIn:n,pool:r,config:a});return void 0!==o?el(u,o):u},G.getUsedSuiForTx=async function(e,t){let{suiAmount:n,frontendFee:i}=e,o=await ea(t,ee.CONFIG_OBJECT_ID);return void 0!==i&&(n=el(n,i)),n*ee.FEE_DENOMINATOR/(ee.FEE_DENOMINATOR+BigInt(o.platform_fee))};var ek=ei||(ei={});async function eD(e,t){let{tx:n,coinOut:i}=await eT(e,t);A(i,"Coin out is required");let o=await en.getUsedSuiForTx({suiAmount:BigInt(e.inputAmount),frontendFee:e.frontendFee},t),[r,a]=n.moveCall({target:`${ee.PACKAGE_ID}::moonbags::buy_exact_in_returns_with_lock`,typeArguments:[e.outCoinType],arguments:[n.object(ee.CONFIG_OBJECT_ID),n.object(ee.LOCK_CONFIG_OBJECT_ID),i,n.pure.u64(o),n.pure.u64(e.minAmountOut),n.object(ee.BURN_MANAGER_OBJECT_ID),n.object(ee.POOLS_OBJECT_ID),n.object(ee.GLOBAL_CONFIG_OBJECT_ID),n.object(eC),n.object(eA)]});return X.transferOrDestroyZeroCoin(n,ep,r,e.accountAddress),{tx:n,coinOut:a}}async function eM(e,t){A(e.outCoinType===ep||e.outCoinType===eg,"Output must be SUI");let{tx:n,coinData:i}=await ey({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},t),[o]=i,[r,a]=n.moveCall({target:`${ee.PACKAGE_ID}::moonbags::sell_returns`,typeArguments:[e.inCoinType],arguments:[n.object(ee.CONFIG_OBJECT_ID),o,n.pure.u64(e.minAmountOut),n.object(eA)]});return X.transferOrDestroyZeroCoin(n,e.inCoinType,a,e.accountAddress),await eB(n,e,r)}function eN(e){return e}function eU(e){return e}function ej(e){return new Proxy(e,{get(e,t){let n=e[t];return"function"==typeof n?n.bind(e):n}})}ek.buildBuyTx=eD,ek.buildSellTx=eM,ek.getBuyTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:n,poolId:i,slippage:o,walletAddress:a,tradeFee:u},s){A(t===eg,"coinInType must be SUI for buy transaction"),A(n!==t,"coinOutType must be different from coinInType"),A(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),A(e>0,"coinInAmount must be greater than 0");let c=BigInt(new r((await en.getCurveAmountAfterBuy({poolId:i,suiAmount:e,frontendFee:u?u.tradeFeePercent:void 0},s)).toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await eD({accountAddress:a,inCoinType:t,outCoinType:n,inputAmount:e.toString(),minAmountOut:c.toString(),poolId:i,frontendFee:u?u.tradeFeePercent:void 0,frontendFeeRecipient:u?u.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},s);A(d,"Coin out is required"),l.transferObjects([d],l.pure.address(a)),l.setSender(a);let f=await ed(s,l,a,0);return(l=await eS({inheritTx:l,sender:a,feeAmount:f,suiInputAmount:e},s)).build({client:s})},ek.getSellTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:n,poolId:i,slippage:o,walletAddress:a,tradeFee:u},s){A(n===eg,"coinOutType must be SUI for sell transaction"),A(n!==t,"coinOutType must be different from coinInType"),A(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),A(e>0,"coinInAmount must be greater than 0");let c=BigInt(new r((await en.getSuiAmountAfterSell({poolId:i,curveAmount:e,frontendFee:u?u.tradeFeePercent:void 0},s)).toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await eM({accountAddress:a,inCoinType:t,outCoinType:n,inputAmount:e.toString(),minAmountOut:c.toString(),poolId:i,frontendFee:u?u.tradeFeePercent:void 0,frontendFeeRecipient:u?u.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},s);A(d,"Coin out is required"),l.transferObjects([d],l.pure.address(a)),l.setSender(a);let f=await ed(s,l,a,0);return(l=await eS({inheritTx:l,sender:a,feeAmount:f},s)).build({client:s})};class eK{suiClient;constructor(e){this.suiClient=e}validatePrivateKey(e,t){A(e?.trim(),"Private key is required");let n=O.fromSecretKey(e),i=n.getPublicKey().toSuiAddress();if(i!==t)throw Error(`Private key mismatch. Expected: ${t}, Got: ${i}`);return n}async createDraft(e,t,n){A(e?.trim(),"Sender address is required"),A(t?.trim(),"Recipient address is required"),A(e!==t,"Sender and recipient cannot be the same"),A(n>0n,"Transfer amount must be at least 1 MIST");try{let i=new o,[r]=i.splitCoins(i.gas,[n]);i.transferObjects([r],t),i.setSender(e);let a=await this.suiClient.getReferenceGasPrice();i.setGasPrice(a);let u=await ed(this.suiClient,i,e,.1);i=await eS({inheritTx:i,sender:e,feeAmount:u,suiInputAmount:n},this.suiClient);let s=await i.build({client:this.suiClient}),c=Buffer.from(s).toString("base64"),l=await i.getDigest();return{sender:e,recipient:t,amountMIST:n,txDraftBase64:c,txDigest:l}}catch(e){throw Error(`Failed to create draft transaction: ${e instanceof Error?e.message:"Unknown error"}`)}}async execute(e,t){try{A(e,"Draft transaction is required"),A(e.txDraftBase64?.trim(),"Transaction data is required");let n=this.validatePrivateKey(t,e.sender),i=h(e.txDraftBase64),{signature:o}=await n.signTransaction(i),r=await this.suiClient.executeTransactionBlock({transactionBlock:i,signature:o});return{success:!0,txDigest:r.digest,effects:r.effects}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error occurred"}}}async getTransactionStatus(e){A(e?.trim(),"Transaction digest is required");try{let t=await this.suiClient.getTransactionBlock({digest:e,options:{showEffects:!0}});if(!t?.effects?.status)return"pending";return"success"===t.effects.status.status?"success":"failure"}catch(e){if(e instanceof Error&&(e.message.includes("not found")||e.message.includes("Could not find")))return"pending";return"failure"}}}export{v as AftermathAggregator,w as AstrosAggregator,es as BASE_BPS,eb as BLUEFIN_PACKAGE_ID,J as BlastFunConstants,Z as BlastFunCustomCalculation,Y as BlastFunCustomTransaction,W as BlastFunPackage,H as BlastFunSDKCalculation,Q as BlastFunSDKTransaction,X as BluefinTx,V as Bps,eA as CLOCK_OBJECT_ID,S as CetusAggregator,eK as DraftTransferTx,er as FlowXAggregator,$ as MathUtils,en as MoonbagsCalculation,ee as MoonbagsConstants,et as MoonbagsPackage,ei as MoonbagsTransaction,e_ as NATIVE_USDC_TOKEN_TYPE,ep as SUI_FULL_TYPE,eC as SUI_METADATA_OBJECT_ID,eg as SUI_TYPE,F as SevenKAggregator,eo as SupportedAggregator,eP as SupportedBondingCurve,L as TradeFeeOptions,eI as USDC_TOKEN_TYPE,eN as adaptSuiClient,eU as adaptTransaction,eS as addGasFee,ej as createCompatibleSuiClient,el as getAmountAfterFee,eh as getCoinObjectIdsByAmount,ew as getMemezPumpSDK,eu as getMoveObject,ea as getMoveObjectContent,ed as getNeededGasFee,ey as getSplitCoinForTx,ec as getSplitCoinsAfterFee,eT as splitSuiCoinAfterFeeFromBuyTx,eB as splitSuiCoinAfterFeeFromSellTx};