@minswap/noodles-sdk 0.0.11 → 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.
package/dist/index.js CHANGED
@@ -1,1519 +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 { SuiClient, getFullnodeUrl } from "@mysten/sui/client";
10
- import { fromBase64, normalizeStructTag } from "@mysten/sui/utils";
11
- import tiny_invariant from "@minswap/tiny-invariant";
12
- import { MemezPumpSDK } from "@interest-protocol/memez-fun-sdk";
13
- import { Network } from "@interest-protocol/sui-core-sdk";
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 config_suiClient = new SuiClient({
524
- url: getFullnodeUrl("mainnet")
525
- });
526
- function getSuiClient() {
527
- return config_suiClient;
528
- }
529
- const orderByKey = (array, key, sortBy)=>{
530
- if (!array?.length) return;
531
- let swapped;
532
- do {
533
- swapped = false;
534
- for(let i = 0; i < array.length - 1; i++){
535
- const a = BigInt(array[i][key]);
536
- const b = BigInt(array[i + 1][key]);
537
- if ("desc" === sortBy ? a < b : a > b) {
538
- const temp = array[i];
539
- array[i] = array[i + 1];
540
- array[i + 1] = temp;
541
- swapped = true;
542
- }
543
- }
544
- }while (swapped);
545
- return array;
546
- };
547
- const getCoinObjectIdsByAmount = async (address, amount, coinType)=>{
548
- let coinBalances = [];
549
- let hasNextPage = true;
550
- let nextCursor;
551
- while(hasNextPage)try {
552
- const coins = await getSuiClient().getCoins({
553
- owner: address,
554
- coinType,
555
- cursor: nextCursor
556
- });
557
- coinBalances = [
558
- ...coinBalances,
559
- ...coins.data
560
- ];
561
- hasNextPage = coins.hasNextPage;
562
- nextCursor = coins.nextCursor;
563
- } catch (error) {
564
- console.error("Error fetching data:", error);
565
- hasNextPage = false;
566
- }
567
- const coinObj = orderByKey(coinBalances.map((item)=>({
568
- ...item,
569
- balance: item.balance
570
- })), "balance", "desc") ?? [];
571
- let balance = "0";
572
- const objectIds = [];
573
- const objectCoins = [];
574
- for (const coin of coinObj){
575
- balance = (BigInt(coin.balance) + BigInt(balance)).toString(10);
576
- objectIds.push(coin.coinObjectId);
577
- objectCoins.push(coin);
578
- if (BigInt(balance) >= BigInt(amount)) break;
579
- }
580
- return {
581
- objectIds,
582
- balance,
583
- objectCoins
584
- };
585
- };
586
- async function addGasFee(params) {
587
- const { inheritTx, sender, feeAmount, suiInputAmount } = params;
588
- const tx = inheritTx || new Transaction();
589
- tx.setGasBudget(feeAmount);
590
- const { objectCoins } = await getCoinObjectIdsByAmount(sender, (BigInt(suiInputAmount || "0") + feeAmount).toString(), SUI_FULL_TYPE);
591
- tx.setGasPayment(objectCoins.map((c)=>({
592
- objectId: c.coinObjectId,
593
- version: c.version,
594
- digest: c.digest
595
- })));
596
- return tx;
597
- }
598
- (function(BluefinTx) {
599
- function transferOrDestroyZeroCoin(tx, coinType, coin, address) {
600
- tx.moveCall({
601
- target: `${BLUEFIN_PACKAGE_ID}::utils::transfer_or_destroy`,
602
- typeArguments: [
603
- coinType
604
- ],
605
- arguments: [
606
- coin,
607
- tx.pure.address(address)
608
- ]
609
- });
610
- }
611
- BluefinTx.transferOrDestroyZeroCoin = transferOrDestroyZeroCoin;
612
- })(bluefin_BluefinTx || (bluefin_BluefinTx = {}));
613
- var bluefin_BluefinTx;
614
- async function getSplitCoinForTx(params) {
615
- const { account, amount, splits, coinType, inheritTx, inspecTransaction, isSponsored = false } = params;
616
- const tx = inheritTx ?? new Transaction();
617
- const { objectIds } = await getCoinObjectIdsByAmount(account, amount, coinType);
618
- const coinObjectId = objectIds[0];
619
- if (normalizeStructTag(coinType) === normalizeStructTag(SUI_FULL_TYPE) && !isSponsored) {
620
- let coin;
621
- if (inspecTransaction) {
622
- if (objectIds.length > 1) tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
623
- coin = tx.splitCoins(tx.object(coinObjectId), splits);
624
- } else coin = tx.splitCoins(tx.gas, splits);
625
- return {
626
- tx,
627
- coinData: coin
628
- };
629
- }
630
- if (objectIds.length > 1) tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
631
- const coinData = tx.splitCoins(tx.object(coinObjectId), splits);
632
- return {
633
- tx,
634
- coinData
635
- };
636
- }
637
- const BASE_BPS = 10000;
638
- function getSplitCoinsAfterFee(amount, fee) {
639
- const amountNum = BigInt(amount);
640
- const feeNum = BigInt(Number(fee) * BASE_BPS);
641
- if (feeNum === BigInt(0)) return [
642
- amountNum.toString()
643
- ];
644
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
645
- const remainingAmount = amountNum - feeAmount;
646
- return [
647
- remainingAmount.toString(),
648
- feeAmount.toString()
649
- ];
650
- }
651
- function getAmountAfterFee(amount, fee) {
652
- if (!fee || Number(fee) <= 0) return BigInt(amount);
653
- const amountNum = BigInt(amount);
654
- const feeNum = BigInt(Number(fee) * BASE_BPS);
655
- if (feeNum === BigInt(0)) return amountNum;
656
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
657
- return amountNum - feeAmount;
658
- }
659
- async function getNeededGasFee(tx, sender, bufferPercent) {
660
- const { effects: { gasUsed, status } } = await getSuiClient().devInspectTransactionBlock({
661
- sender,
662
- transactionBlock: tx
663
- });
664
- if ("success" !== status.status) throw new Error(`Transaction failed during dev inspect: ${status.error ?? ""}`);
665
- const fee = BigInt(gasUsed.computationCost) + BigInt(gasUsed.storageCost) - BigInt(gasUsed.storageRebate);
666
- const feeNum = BigInt(Number(bufferPercent) * BASE_BPS);
667
- return fee * (BigInt(BASE_BPS) + feeNum) / BigInt(BASE_BPS);
668
- }
669
- async function getMoveObjectContent(objectId) {
670
- const moveObject = await getMoveObject(objectId);
671
- return moveObject.fields;
672
- }
673
- async function getMoveObject(objectId) {
674
- const client = getSuiClient();
675
- const objRes = await client.getObject({
676
- id: objectId,
677
- options: {
678
- showContent: true
679
- }
680
- });
681
- const content = objRes.data?.content;
682
- tiny_invariant(content, "Pool object not found or has no content");
683
- tiny_invariant("moveObject" === content.dataType, "Object is not a Move object");
684
- return content;
685
- }
686
- function adaptSuiClient(client) {
687
- return client;
688
- }
689
- function adaptTransaction(transaction) {
690
- return transaction;
691
- }
692
- function createCompatibleSuiClient(client) {
693
- return new Proxy(client, {
694
- get (target, prop) {
695
- const value = target[prop];
696
- if ("function" == typeof value) return value.bind(target);
697
- return value;
698
- }
699
- });
700
- }
701
- (function(MathUtils) {
702
- (function(U64) {
703
- function mulDivUp(a, b, c) {
704
- let roundUp = BigInt(0);
705
- if (a * b % c > BigInt(0)) roundUp = BigInt(1);
706
- return a * b / c + roundUp;
707
- }
708
- U64.mulDivUp = mulDivUp;
709
- })(MathUtils.U64 || (MathUtils.U64 = {}));
710
- })(package_MathUtils || (package_MathUtils = {}));
711
- (function(Bps) {
712
- function calcUp(bps, amount) {
713
- const bpsValue = BigInt(bps.pos0);
714
- const denominator = BigInt(10000);
715
- let roundUp;
716
- roundUp = bpsValue * amount % denominator !== BigInt(0) ? BigInt(1) : BigInt(0);
717
- return bpsValue * amount / denominator + roundUp;
718
- }
719
- Bps.calcUp = calcUp;
720
- function sub(lhs, rhs) {
721
- tiny_invariant(BigInt(lhs.pos0) >= BigInt(rhs.pos0), "Bps underflow");
722
- return {
723
- pos0: (BigInt(lhs.pos0) - BigInt(rhs.pos0)).toString()
724
- };
725
- }
726
- Bps.sub = sub;
727
- function value(bps) {
728
- return BigInt(bps.pos0);
729
- }
730
- Bps.value = value;
731
- function new_(bps) {
732
- return {
733
- pos0: assertOverflow(bps).toString()
734
- };
735
- }
736
- Bps.new_ = new_;
737
- function assertOverflow(bps) {
738
- tiny_invariant(BigInt(bps) <= BigInt(10000), "Bps overflow");
739
- return BigInt(bps);
740
- }
741
- Bps.assertOverflow = assertOverflow;
742
- })(package_Bps || (package_Bps = {}));
743
- (function(BlastFunPackage) {
744
- (function(MemezFun) {
745
- async function isSniperProtectedMemezFun(poolId) {
746
- const memezFun = await getMoveObjectContent(poolId);
747
- return memezFun.public_key.length > 0;
748
- }
749
- MemezFun.isSniperProtectedMemezFun = isSniperProtectedMemezFun;
750
- })(BlastFunPackage.MemezFun || (BlastFunPackage.MemezFun = {}));
751
- (function(MemezFees) {
752
- function takeWithDiscount(fee, amount, discountBps) {
753
- if ("Value" === fee.variant) {
754
- const amountRequired = BigInt(fee.fields.pos0);
755
- if (amountRequired === BigInt(0)) return BigInt(0);
756
- if (amount >= amountRequired) return amountRequired;
757
- throw new Error(`Insufficient amount to cover fee. Required: ${amountRequired}, provided: ${amount}`);
758
- }
759
- if ("Percentage" === fee.variant) {
760
- const feeBps = fee.fields.pos0.fields;
761
- if (BigInt(feeBps.pos0) === BigInt(0)) return BigInt(0);
762
- const discountedFee = package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
763
- if (amount >= discountedFee) return discountedFee;
764
- throw new Error(`Insufficient amount to cover fee. Required: ${discountedFee}, provided: ${amount}`);
765
- }
766
- throw new Error("Unknown fee variant");
767
- }
768
- MemezFees.takeWithDiscount = takeWithDiscount;
769
- function calculateWithDiscount(fee, discountBps, amount) {
770
- if ("Value" === fee.variant) return BigInt(fee.fields.pos0);
771
- if ("Percentage" === fee.variant) {
772
- const feeBps = fee.fields.pos0.fields;
773
- return package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
774
- }
775
- throw new Error("Unknown fee variant");
776
- }
777
- MemezFees.calculateWithDiscount = calculateWithDiscount;
778
- })(BlastFunPackage.MemezFees || (BlastFunPackage.MemezFees = {}));
779
- (function(MemezBurner) {
780
- function calculate(burner, poolMemeBalance) {
781
- const burnerFee = package_Bps.value(burner.fee.fields);
782
- if (burnerFee === BigInt(0) || poolMemeBalance === BigInt(0)) return package_Bps.new_(0);
783
- if (poolMemeBalance >= BigInt(burner.target_liquidity)) return package_Bps.new_(0);
784
- const baseBps = BigInt(10000);
785
- 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));
786
- }
787
- MemezBurner.calculate = calculate;
788
- })(BlastFunPackage.MemezBurner || (BlastFunPackage.MemezBurner = {}));
789
- (function(MemezPump) {
790
- async function getPumpState(memezFun) {
791
- return await getMoveObjectContent(memezFun.inner_state);
792
- }
793
- MemezPump.getPumpState = getPumpState;
794
- function pump(pumpState, quoteAmount) {
795
- const constantProduct = pumpState.constant_product.fields;
796
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteAmount, constantProduct.quote_referrer_fee.fields);
797
- const quoteAfterFee = quoteAmount - quoteSwapFee;
798
- const memeBalance = BigInt(constantProduct.meme_balance);
799
- const quoteBalance = BigInt(constantProduct.quote_balance);
800
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
801
- const memeOutExpected = memeBalance * quoteAfterFee / (virtualLiquidity + quoteBalance + quoteAfterFee);
802
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeOutExpected, constantProduct.meme_referrer_fee.fields);
803
- return memeOutExpected - memeSwapFee;
804
- }
805
- MemezPump.pump = pump;
806
- function dump(pumpState, memeAmount) {
807
- const constantProduct = pumpState.constant_product.fields;
808
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeAmount, constantProduct.meme_referrer_fee.fields);
809
- const inputAmount = memeAmount - memeSwapFee;
810
- const memeBalance = BigInt(constantProduct.meme_balance);
811
- const quoteBalance = BigInt(constantProduct.quote_balance);
812
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
813
- const burnBps = BlastFunPackage.MemezBurner.calculate(constantProduct.burner.fields, quoteBalance);
814
- const burnAmount = package_Bps.calcUp(burnBps, inputAmount);
815
- const inputAmountAfterFee = inputAmount - (package_Bps.value(burnBps) !== BigInt(0) ? burnAmount : BigInt(0));
816
- let quoteOutBeforeFee = (virtualLiquidity + quoteBalance) * inputAmountAfterFee / (memeBalance + inputAmountAfterFee);
817
- if (quoteOutBeforeFee > quoteBalance) quoteOutBeforeFee = quoteBalance;
818
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteOutBeforeFee, constantProduct.quote_referrer_fee.fields);
819
- return quoteOutBeforeFee - quoteSwapFee;
820
- }
821
- MemezPump.dump = dump;
822
- })(BlastFunPackage.MemezPump || (BlastFunPackage.MemezPump = {}));
823
- })(package_BlastFunPackage || (package_BlastFunPackage = {}));
824
- var package_MathUtils, package_Bps, package_BlastFunPackage;
825
- (function(BlastFunCustomCalculation) {
826
- async function getCurveAmountAfterBuy(params) {
827
- let { suiAmount, poolId, frontendFee } = params;
828
- const memezFun = await getMoveObjectContent(poolId);
829
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(memezFun);
830
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
831
- return package_BlastFunPackage.MemezPump.pump(pumpState, suiAmount);
832
- }
833
- BlastFunCustomCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
834
- async function getSuiAmountAfterSell(params) {
835
- const { curveAmount, poolId, frontendFee } = params;
836
- const memezFun = await getMoveObjectContent(poolId);
837
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(memezFun);
838
- const suiAmount = package_BlastFunPackage.MemezPump.dump(pumpState, curveAmount);
839
- return getAmountAfterFee(suiAmount, frontendFee);
840
- }
841
- BlastFunCustomCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
842
- })(custom_calculation_BlastFunCustomCalculation || (custom_calculation_BlastFunCustomCalculation = {}));
843
- var custom_calculation_BlastFunCustomCalculation;
844
- async function splitSuiCoinAfterFeeFromBuyTx(params) {
845
- const { inputAmount, accountAddress, frontendFee, frontendFeeRecipient, extendTx, isSponsored } = params;
846
- tiny_invariant(params.inCoinType === SUI_FULL_TYPE || params.inCoinType === SUI_TYPE, "Input must be SUI");
847
- const { tx: _tx, coinIn } = extendTx || {};
848
- const splitSui = getSplitCoinsAfterFee(inputAmount, frontendFee || "0");
849
- const tx = _tx || new Transaction();
850
- let coinData;
851
- if (coinIn) {
852
- coinData = tx.splitCoins(coinIn, splitSui);
853
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, coinIn, accountAddress);
854
- } else {
855
- const { coinData: _data } = await getSplitCoinForTx({
856
- account: accountAddress,
857
- amount: inputAmount,
858
- splits: splitSui,
859
- coinType: SUI_FULL_TYPE,
860
- inheritTx: tx,
861
- isSponsored: isSponsored || false
862
- });
863
- coinData = _data;
864
- }
865
- let inputSuiCoin;
866
- if (frontendFee && frontendFeeRecipient) {
867
- const [_inputSuiCoin, frontendFeeCoin] = coinData;
868
- inputSuiCoin = _inputSuiCoin;
869
- tx.transferObjects([
870
- frontendFeeCoin
871
- ], tx.pure.address(frontendFeeRecipient || accountAddress));
872
- } else [inputSuiCoin] = coinData;
873
- return {
874
- tx,
875
- coinOut: inputSuiCoin
876
- };
877
- }
878
- async function splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin) {
879
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
880
- if (Number(params.frontendFee || 0) <= 0) return {
881
- tx,
882
- coinOut: suiCoin
883
- };
884
- const suiCoinValue = tx.moveCall({
885
- target: "0x2::coin::value",
886
- typeArguments: [
887
- params.outCoinType
888
- ],
889
- arguments: [
890
- suiCoin
891
- ]
892
- });
893
- const suiCoinFeeValue = tx.moveCall({
894
- target: `${BLUEFIN_PACKAGE_ID}::math::mul_div_u64`,
895
- typeArguments: [],
896
- arguments: [
897
- suiCoinValue,
898
- tx.pure.u64(BigInt(Number(params.frontendFee || "0") * BASE_BPS)),
899
- tx.pure.u64(BigInt(BASE_BPS))
900
- ]
901
- });
902
- const suiCoinFee = tx.moveCall({
903
- target: "0x2::coin::split",
904
- typeArguments: [
905
- params.outCoinType
906
- ],
907
- arguments: [
908
- suiCoin,
909
- suiCoinFeeValue
910
- ]
911
- });
912
- tx.transferObjects([
913
- suiCoinFee
914
- ], tx.pure.address(params.frontendFeeRecipient || params.accountAddress));
915
- return {
916
- tx,
917
- coinOut: suiCoin
918
- };
919
- }
920
- var types_SupportedBondingCurve = /*#__PURE__*/ function(SupportedBondingCurve) {
921
- SupportedBondingCurve["BLAST_FUN"] = "BLAST_FUN";
922
- SupportedBondingCurve["MOONBAGS"] = "MOONBAGS";
923
- return SupportedBondingCurve;
924
- }({});
925
- (function(BlastFunCustomTransaction) {
926
- async function getAllowedVersions(_tx) {
927
- const tx = _tx || new Transaction();
928
- return tx.moveCall({
929
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_allowed_versions::get_allowed_versions`,
930
- arguments: [
931
- tx.object(constants_BlastFunConstants.MEMEZ_AV_OBJECT_ID)
932
- ],
933
- typeArguments: []
934
- });
935
- }
936
- BlastFunCustomTransaction.getAllowedVersions = getAllowedVersions;
937
- async function buildBuyTx(params) {
938
- tiny_invariant(!await package_BlastFunPackage.MemezFun.isSniperProtectedMemezFun(params.poolId), "This coin is a sniper protected coin, please use the Blast Fun website to trade it.");
939
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params);
940
- tiny_invariant(suiCoinIn, "Coin out is required");
941
- const curveCoin = tx.moveCall({
942
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::pump`,
943
- typeArguments: [
944
- params.outCoinType,
945
- SUI_FULL_TYPE
946
- ],
947
- arguments: [
948
- tx.object(params.poolId),
949
- suiCoinIn,
950
- tx.pure.vector("address", []),
951
- tx.pure.vector("vector<u8>", []),
952
- tx.pure.u64(params.minAmountOut),
953
- await getAllowedVersions(tx)
954
- ]
955
- });
956
- return {
957
- tx,
958
- coinOut: curveCoin
959
- };
960
- }
961
- BlastFunCustomTransaction.buildBuyTx = buildBuyTx;
962
- async function buildSellTx(params) {
963
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
964
- const memezFun = await getMoveObjectContent(params.poolId);
965
- const { tx, coinData } = await getSplitCoinForTx({
966
- amount: params.inputAmount,
967
- coinType: params.inCoinType,
968
- inheritTx: params.extendTx?.tx,
969
- account: params.accountAddress,
970
- splits: [
971
- params.inputAmount
972
- ]
973
- });
974
- const [inputCoin] = coinData;
975
- const [suiCoin] = tx.moveCall({
976
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::dump`,
977
- typeArguments: [
978
- params.inCoinType,
979
- params.outCoinType
980
- ],
981
- arguments: [
982
- tx.object(params.poolId),
983
- tx.object(memezFun.ipx_meme_coin_treasury),
984
- inputCoin,
985
- tx.pure.vector("address", []),
986
- tx.pure.u64(params.minAmountOut),
987
- await getAllowedVersions(tx)
988
- ]
989
- });
990
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
991
- }
992
- BlastFunCustomTransaction.buildSellTx = buildSellTx;
993
- })(custom_transaction_BlastFunCustomTransaction || (custom_transaction_BlastFunCustomTransaction = {}));
994
- var custom_transaction_BlastFunCustomTransaction;
995
- const payload = {
996
- network: Network.MAINNET,
997
- fullNodeUrl: getFullnodeUrl("mainnet")
998
- };
999
- const memezPump = new MemezPumpSDK(payload);
1000
- function getMemezPumpSDK() {
1001
- return memezPump;
1002
- }
1003
- (function(BlastFunSDKCalculation) {
1004
- async function getCurveAmountAfterBuy(params) {
1005
- let { suiAmount, poolId, frontendFee } = params;
1006
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1007
- const { memeAmountOut } = await getMemezPumpSDK().quotePump({
1008
- pool: poolId,
1009
- amount: suiAmount
1010
- });
1011
- return memeAmountOut;
1012
- }
1013
- BlastFunSDKCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1014
- async function getSuiAmountAfterSell(params) {
1015
- const { curveAmount, poolId, frontendFee } = params;
1016
- const { quoteAmountOut } = await getMemezPumpSDK().quoteDump({
1017
- pool: poolId,
1018
- amount: curveAmount
1019
- });
1020
- return getAmountAfterFee(quoteAmountOut, frontendFee);
1021
- }
1022
- BlastFunSDKCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1023
- })(sdk_calculation_BlastFunSDKCalculation || (sdk_calculation_BlastFunSDKCalculation = {}));
1024
- var sdk_calculation_BlastFunSDKCalculation;
1025
- (function(BlastFunSDKTransaction) {
1026
- async function buildBuyTx(params) {
1027
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params);
1028
- tiny_invariant(suiCoinIn, "Coin out is required");
1029
- const { memeCoin, tx: tx2 } = await getMemezPumpSDK().pump({
1030
- pool: params.poolId,
1031
- quoteCoin: suiCoinIn,
1032
- minAmountOut: params.minAmountOut,
1033
- tx
1034
- });
1035
- return {
1036
- tx: tx2,
1037
- coinOut: memeCoin
1038
- };
1039
- }
1040
- BlastFunSDKTransaction.buildBuyTx = buildBuyTx;
1041
- async function buildSellTx(params) {
1042
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1043
- const { tx, coinData } = await getSplitCoinForTx({
1044
- amount: params.inputAmount,
1045
- coinType: params.inCoinType,
1046
- inheritTx: params.extendTx?.tx,
1047
- account: params.accountAddress,
1048
- splits: [
1049
- params.inputAmount
1050
- ]
1051
- });
1052
- const [inputCoin] = coinData;
1053
- const { quoteCoin, tx: tx2 } = await getMemezPumpSDK().dump({
1054
- pool: params.poolId,
1055
- memeCoin: inputCoin,
1056
- tx,
1057
- minAmountOut: params.minAmountOut
1058
- });
1059
- return await splitSuiCoinAfterFeeFromSellTx(tx2, params, quoteCoin);
1060
- }
1061
- BlastFunSDKTransaction.buildSellTx = buildSellTx;
1062
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1063
- tiny_invariant(coinInType === SUI_TYPE, "coinInType must be SUI for buy transaction");
1064
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1065
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1066
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1067
- const inputAmount = coinInAmount;
1068
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({
1069
- poolId: poolId,
1070
- suiAmount: inputAmount,
1071
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1072
- });
1073
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1074
- let { tx, coinOut } = await buildBuyTx({
1075
- accountAddress: walletAddress,
1076
- inCoinType: coinInType,
1077
- outCoinType: coinOutType,
1078
- inputAmount: inputAmount.toString(),
1079
- minAmountOut: minAmountOut.toString(),
1080
- poolId: poolId,
1081
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1082
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1083
- extendTx: void 0,
1084
- isSponsored: false
1085
- });
1086
- tiny_invariant(coinOut, "Coin out is required");
1087
- tx.transferObjects([
1088
- coinOut
1089
- ], tx.pure.address(walletAddress));
1090
- tx.setSender(walletAddress);
1091
- const feeAmount = await getNeededGasFee(tx, walletAddress, 0);
1092
- tx = await addGasFee({
1093
- inheritTx: tx,
1094
- sender: walletAddress,
1095
- feeAmount,
1096
- suiInputAmount: inputAmount
1097
- });
1098
- return tx.build({
1099
- client: suiClient
1100
- });
1101
- }
1102
- BlastFunSDKTransaction.getBuyTransaction = getBuyTransaction;
1103
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1104
- tiny_invariant(coinOutType === SUI_TYPE, "coinOutType must be SUI for sell transaction");
1105
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1106
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1107
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1108
- const inputAmount = coinInAmount;
1109
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({
1110
- poolId: poolId,
1111
- curveAmount: inputAmount,
1112
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1113
- });
1114
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1115
- let { tx, coinOut } = await buildSellTx({
1116
- accountAddress: walletAddress,
1117
- inCoinType: coinInType,
1118
- outCoinType: coinOutType,
1119
- inputAmount: inputAmount.toString(),
1120
- minAmountOut: minAmountOut.toString(),
1121
- poolId: poolId,
1122
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1123
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1124
- extendTx: void 0,
1125
- isSponsored: false
1126
- });
1127
- tiny_invariant(coinOut, "Coin out is required");
1128
- tx.transferObjects([
1129
- coinOut
1130
- ], tx.pure.address(walletAddress));
1131
- tx.setSender(walletAddress);
1132
- const feeAmount = await getNeededGasFee(tx, walletAddress, 0);
1133
- tx = await addGasFee({
1134
- inheritTx: tx,
1135
- sender: walletAddress,
1136
- feeAmount
1137
- });
1138
- return tx.build({
1139
- client: suiClient
1140
- });
1141
- }
1142
- BlastFunSDKTransaction.getSellTransaction = getSellTransaction;
1143
- })(sdk_transaction_BlastFunSDKTransaction || (sdk_transaction_BlastFunSDKTransaction = {}));
1144
- var sdk_transaction_BlastFunSDKTransaction;
1145
- (function(MoonbagsConstants) {
1146
- MoonbagsConstants.PACKAGE_ID = "0xb8df325010942634a4afb3db3901ee215546af43a4ec4af781e7213b0bba7290";
1147
- MoonbagsConstants.CONFIG_OBJECT_ID = "0x74aecf86067c6913960ba4925333aefd2b1f929cafca7e21fd55a8f244b70499";
1148
- MoonbagsConstants.LOCK_CONFIG_OBJECT_ID = "0xfb09822d9808980abd04c51321adb850701f5f55535c6206658ef4d910c3e9be";
1149
- MoonbagsConstants.BURN_MANAGER_OBJECT_ID = "0x1d94aa32518d0cb00f9de6ed60d450c9a2090761f326752ffad06b2e9404f845";
1150
- MoonbagsConstants.POOLS_OBJECT_ID = "0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0";
1151
- MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID = "0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f";
1152
- MoonbagsConstants.FEE_DENOMINATOR = BigInt(10000);
1153
- })(constants_MoonbagsConstants || (constants_MoonbagsConstants = {}));
1154
- var constants_MoonbagsConstants;
1155
- (function(MoonbagsPackage) {
1156
- (function(Curves) {
1157
- function calculateAddLiquidityCost(tokenIn, tokenReserve, tokenAmount) {
1158
- const availableReserve = tokenReserve - tokenAmount;
1159
- const numerator = tokenIn * tokenReserve;
1160
- const fraction = numerator / availableReserve;
1161
- return fraction - tokenIn;
1162
- }
1163
- Curves.calculateAddLiquidityCost = calculateAddLiquidityCost;
1164
- function calculateRemoveLiquidityReturn(tokenIn, tokenReserve, tokenRemoved) {
1165
- const denominator = tokenIn + tokenRemoved;
1166
- const fraction = tokenIn * tokenReserve / denominator;
1167
- return tokenReserve - fraction;
1168
- }
1169
- Curves.calculateRemoveLiquidityReturn = calculateRemoveLiquidityReturn;
1170
- function calculateTokenAmountReceived(tokenIn, tokenReserve, tokenOutReserve) {
1171
- const denominator = tokenIn + tokenOutReserve;
1172
- const fraction = tokenIn * tokenReserve / denominator;
1173
- return tokenReserve - fraction;
1174
- }
1175
- Curves.calculateTokenAmountReceived = calculateTokenAmountReceived;
1176
- })(MoonbagsPackage.Curves || (MoonbagsPackage.Curves = {}));
1177
- (function(Moonbags) {
1178
- async function getDynamicVirtualTokenReserves(poolId) {
1179
- const result = await getSuiClient().getDynamicFieldObject({
1180
- parentId: poolId,
1181
- name: {
1182
- type: "vector<u8>",
1183
- value: "virtual_token_reserves"
1184
- }
1185
- });
1186
- if (!result.data) return;
1187
- return BigInt(result.data.content.fields.value);
1188
- }
1189
- Moonbags.getDynamicVirtualTokenReserves = getDynamicVirtualTokenReserves;
1190
- function buyExactInReturnsWithLock(params) {
1191
- const { inputAmount, amountIn, pool, config, dynamicVirtualTokenReserves } = params;
1192
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1193
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1194
- const remainTokenReserves = BigInt(pool.remain_token_reserves.fields.balance);
1195
- const expectedOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualSuiReserves, virtualTokenReserves, amountIn);
1196
- const availableOut = virtualTokenReserves - (dynamicVirtualTokenReserves || remainTokenReserves);
1197
- let finalOut = expectedOut;
1198
- let usedSui = amountIn;
1199
- if (expectedOut > availableOut) {
1200
- finalOut = availableOut;
1201
- usedSui = MoonbagsPackage.Curves.calculateAddLiquidityCost(virtualSuiReserves, virtualTokenReserves, availableOut) + BigInt(1);
1202
- }
1203
- const feeAmount = usedSui * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1204
- tiny_invariant(inputAmount >= usedSui + feeAmount, "Input amount is less than used SUI + fee");
1205
- return {
1206
- receivedCurve: finalOut,
1207
- receivedSui: inputAmount - usedSui - feeAmount
1208
- };
1209
- }
1210
- Moonbags.buyExactInReturnsWithLock = buyExactInReturnsWithLock;
1211
- function sellReturns(params) {
1212
- const { amountIn, pool, config } = params;
1213
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1214
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1215
- const realSuiReserves = BigInt(pool.real_sui_reserves.fields.balance);
1216
- let rawSuiOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualTokenReserves, virtualSuiReserves, amountIn);
1217
- if (rawSuiOut > realSuiReserves) rawSuiOut = realSuiReserves;
1218
- const feeAmount = rawSuiOut * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1219
- const finalSuiOut = rawSuiOut - feeAmount;
1220
- return {
1221
- receivedCurve: BigInt(0),
1222
- receivedSui: finalSuiOut
1223
- };
1224
- }
1225
- Moonbags.sellReturns = sellReturns;
1226
- })(MoonbagsPackage.Moonbags || (MoonbagsPackage.Moonbags = {}));
1227
- })(package_MoonbagsPackage || (package_MoonbagsPackage = {}));
1228
- var package_MoonbagsPackage;
1229
- (function(MoonbagsCalculation) {
1230
- async function getCurveAmountAfterBuy(params) {
1231
- let { suiAmount, poolId, frontendFee } = params;
1232
- const [poolMoveStruct, configMoveStruct, dynamicVirtualTokenReserves] = await Promise.all([
1233
- getMoveObjectContent(poolId),
1234
- getMoveObjectContent(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1235
- package_MoonbagsPackage.Moonbags.getDynamicVirtualTokenReserves(poolId)
1236
- ]);
1237
- const pool = poolMoveStruct;
1238
- const config = configMoveStruct;
1239
- if (void 0 !== frontendFee) suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1240
- const usedSui = suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1241
- const { receivedCurve } = package_MoonbagsPackage.Moonbags.buyExactInReturnsWithLock({
1242
- inputAmount: suiAmount,
1243
- amountIn: usedSui,
1244
- pool,
1245
- config,
1246
- dynamicVirtualTokenReserves
1247
- });
1248
- return receivedCurve;
1249
- }
1250
- MoonbagsCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1251
- async function getSuiAmountAfterSell(params) {
1252
- const { curveAmount, poolId, frontendFee } = params;
1253
- const [poolMoveStruct, configMoveStruct] = await Promise.all([
1254
- getMoveObjectContent(poolId),
1255
- getMoveObjectContent(constants_MoonbagsConstants.CONFIG_OBJECT_ID)
1256
- ]);
1257
- const pool = poolMoveStruct;
1258
- const config = configMoveStruct;
1259
- const { receivedSui } = package_MoonbagsPackage.Moonbags.sellReturns({
1260
- amountIn: curveAmount,
1261
- pool,
1262
- config
1263
- });
1264
- if (void 0 !== frontendFee) return getAmountAfterFee(receivedSui, frontendFee);
1265
- return receivedSui;
1266
- }
1267
- MoonbagsCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1268
- async function getUsedSuiForTx(params) {
1269
- let { suiAmount, frontendFee } = params;
1270
- const configMoveStruct = await getMoveObjectContent(constants_MoonbagsConstants.CONFIG_OBJECT_ID);
1271
- const config = configMoveStruct;
1272
- if (void 0 !== frontendFee) suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1273
- return suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1274
- }
1275
- MoonbagsCalculation.getUsedSuiForTx = getUsedSuiForTx;
1276
- })(calculation_MoonbagsCalculation || (calculation_MoonbagsCalculation = {}));
1277
- var calculation_MoonbagsCalculation;
1278
- (function(MoonbagsTransaction) {
1279
- async function buildBuyTx(params) {
1280
- const { tx, coinOut } = await splitSuiCoinAfterFeeFromBuyTx(params);
1281
- tiny_invariant(coinOut, "Coin out is required");
1282
- const usedSui = await calculation_MoonbagsCalculation.getUsedSuiForTx({
1283
- suiAmount: BigInt(params.inputAmount),
1284
- frontendFee: params.frontendFee
1285
- });
1286
- const [suiCoin, curveCoin] = tx.moveCall({
1287
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::buy_exact_in_returns_with_lock`,
1288
- typeArguments: [
1289
- params.outCoinType
1290
- ],
1291
- arguments: [
1292
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1293
- tx.object(constants_MoonbagsConstants.LOCK_CONFIG_OBJECT_ID),
1294
- coinOut,
1295
- tx.pure.u64(usedSui),
1296
- tx.pure.u64(params.minAmountOut),
1297
- tx.object(constants_MoonbagsConstants.BURN_MANAGER_OBJECT_ID),
1298
- tx.object(constants_MoonbagsConstants.POOLS_OBJECT_ID),
1299
- tx.object(constants_MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID),
1300
- tx.object(SUI_METADATA_OBJECT_ID),
1301
- tx.object(CLOCK_OBJECT_ID)
1302
- ]
1303
- });
1304
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, suiCoin, params.accountAddress);
1305
- return {
1306
- tx,
1307
- coinOut: curveCoin
1308
- };
1309
- }
1310
- MoonbagsTransaction.buildBuyTx = buildBuyTx;
1311
- async function buildSellTx(params) {
1312
- tiny_invariant(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1313
- const { tx, coinData } = await getSplitCoinForTx({
1314
- amount: params.inputAmount,
1315
- coinType: params.inCoinType,
1316
- inheritTx: params.extendTx?.tx,
1317
- account: params.accountAddress,
1318
- splits: [
1319
- params.inputAmount
1320
- ]
1321
- });
1322
- const [inputCoin] = coinData;
1323
- const [suiCoin, curveCoin] = tx.moveCall({
1324
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::sell_returns`,
1325
- typeArguments: [
1326
- params.inCoinType
1327
- ],
1328
- arguments: [
1329
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1330
- inputCoin,
1331
- tx.pure.u64(params.minAmountOut),
1332
- tx.object(CLOCK_OBJECT_ID)
1333
- ]
1334
- });
1335
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, params.inCoinType, curveCoin, params.accountAddress);
1336
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
1337
- }
1338
- MoonbagsTransaction.buildSellTx = buildSellTx;
1339
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1340
- tiny_invariant(coinInType === SUI_TYPE, "coinInType must be SUI for buy transaction");
1341
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1342
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1343
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1344
- const inputAmount = coinInAmount;
1345
- const outputAmount = await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({
1346
- poolId: poolId,
1347
- suiAmount: inputAmount,
1348
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1349
- });
1350
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1351
- let { tx, coinOut } = await buildBuyTx({
1352
- accountAddress: walletAddress,
1353
- inCoinType: coinInType,
1354
- outCoinType: coinOutType,
1355
- inputAmount: inputAmount.toString(),
1356
- minAmountOut: minAmountOut.toString(),
1357
- poolId: poolId,
1358
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1359
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1360
- extendTx: void 0,
1361
- isSponsored: false
1362
- });
1363
- tiny_invariant(coinOut, "Coin out is required");
1364
- tx.transferObjects([
1365
- coinOut
1366
- ], tx.pure.address(walletAddress));
1367
- tx.setSender(walletAddress);
1368
- const feeAmount = await getNeededGasFee(tx, walletAddress, 0);
1369
- tx = await addGasFee({
1370
- inheritTx: tx,
1371
- sender: walletAddress,
1372
- feeAmount,
1373
- suiInputAmount: inputAmount
1374
- });
1375
- return tx.build({
1376
- client: suiClient
1377
- });
1378
- }
1379
- MoonbagsTransaction.getBuyTransaction = getBuyTransaction;
1380
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1381
- tiny_invariant(coinOutType === SUI_TYPE, "coinOutType must be SUI for sell transaction");
1382
- tiny_invariant(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1383
- tiny_invariant(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1384
- tiny_invariant(coinInAmount > 0, "coinInAmount must be greater than 0");
1385
- const inputAmount = coinInAmount;
1386
- const outputAmount = await calculation_MoonbagsCalculation.getSuiAmountAfterSell({
1387
- poolId: poolId,
1388
- curveAmount: inputAmount,
1389
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0
1390
- });
1391
- const minAmountOut = BigInt(new bignumber(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1392
- let { tx, coinOut } = await buildSellTx({
1393
- accountAddress: walletAddress,
1394
- inCoinType: coinInType,
1395
- outCoinType: coinOutType,
1396
- inputAmount: inputAmount.toString(),
1397
- minAmountOut: minAmountOut.toString(),
1398
- poolId: poolId,
1399
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : void 0,
1400
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : void 0,
1401
- extendTx: void 0,
1402
- isSponsored: false
1403
- });
1404
- tiny_invariant(coinOut, "Coin out is required");
1405
- tx.transferObjects([
1406
- coinOut
1407
- ], tx.pure.address(walletAddress));
1408
- tx.setSender(walletAddress);
1409
- const feeAmount = await getNeededGasFee(tx, walletAddress, 0);
1410
- tx = await addGasFee({
1411
- inheritTx: tx,
1412
- sender: walletAddress,
1413
- feeAmount
1414
- });
1415
- return tx.build({
1416
- client: suiClient
1417
- });
1418
- }
1419
- MoonbagsTransaction.getSellTransaction = getSellTransaction;
1420
- })(transaction_MoonbagsTransaction || (transaction_MoonbagsTransaction = {}));
1421
- var transaction_MoonbagsTransaction;
1422
- const CONSTANTS = {
1423
- GAS_FEE_BUFFER_PERCENTAGE: 0.1
1424
- };
1425
- class DraftTransferTx {
1426
- suiClient;
1427
- constructor(suiClient){
1428
- this.suiClient = suiClient;
1429
- }
1430
- validatePrivateKey(privateKey, expectedSender) {
1431
- tiny_invariant(privateKey?.trim(), "Private key is required");
1432
- const keypair = Ed25519Keypair.fromSecretKey(privateKey);
1433
- const derivedAddress = keypair.getPublicKey().toSuiAddress();
1434
- if (derivedAddress !== expectedSender) throw new Error(`Private key mismatch. Expected: ${expectedSender}, Got: ${derivedAddress}`);
1435
- return keypair;
1436
- }
1437
- async createDraft(sender, recipient, amountMIST) {
1438
- tiny_invariant(sender?.trim(), "Sender address is required");
1439
- tiny_invariant(recipient?.trim(), "Recipient address is required");
1440
- tiny_invariant(sender !== recipient, "Sender and recipient cannot be the same");
1441
- tiny_invariant(amountMIST > 0n, "Transfer amount must be at least 1 MIST");
1442
- try {
1443
- let transaction = new Transaction();
1444
- const [coin] = transaction.splitCoins(transaction.gas, [
1445
- amountMIST
1446
- ]);
1447
- transaction.transferObjects([
1448
- coin
1449
- ], recipient);
1450
- transaction.setSender(sender);
1451
- const referenceGasPrice = await this.suiClient.getReferenceGasPrice();
1452
- transaction.setGasPrice(referenceGasPrice);
1453
- const feeAmount = await getNeededGasFee(transaction, sender, CONSTANTS.GAS_FEE_BUFFER_PERCENTAGE);
1454
- transaction = await addGasFee({
1455
- inheritTx: transaction,
1456
- sender,
1457
- feeAmount,
1458
- suiInputAmount: amountMIST
1459
- });
1460
- const txBytes = await transaction.build({
1461
- client: this.suiClient
1462
- });
1463
- const txDraftBase64 = Buffer.from(txBytes).toString("base64");
1464
- const txDigest = await transaction.getDigest();
1465
- return {
1466
- sender,
1467
- recipient,
1468
- amountMIST,
1469
- txDraftBase64,
1470
- txDigest
1471
- };
1472
- } catch (error) {
1473
- throw new Error(`Failed to create draft transaction: ${error instanceof Error ? error.message : "Unknown error"}`);
1474
- }
1475
- }
1476
- async execute(draftTx, privateKey) {
1477
- try {
1478
- tiny_invariant(draftTx, "Draft transaction is required");
1479
- tiny_invariant(draftTx.txDraftBase64?.trim(), "Transaction data is required");
1480
- const keypair = this.validatePrivateKey(privateKey, draftTx.sender);
1481
- const txBytes = fromBase64(draftTx.txDraftBase64);
1482
- const { signature } = await keypair.signTransaction(txBytes);
1483
- const result = await this.suiClient.executeTransactionBlock({
1484
- transactionBlock: txBytes,
1485
- signature
1486
- });
1487
- return {
1488
- success: true,
1489
- txDigest: result.digest,
1490
- effects: result.effects
1491
- };
1492
- } catch (error) {
1493
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
1494
- return {
1495
- success: false,
1496
- error: errorMessage
1497
- };
1498
- }
1499
- }
1500
- async getTransactionStatus(txDigest) {
1501
- tiny_invariant(txDigest?.trim(), "Transaction digest is required");
1502
- try {
1503
- const txResponse = await this.suiClient.getTransactionBlock({
1504
- digest: txDigest,
1505
- options: {
1506
- showEffects: true
1507
- }
1508
- });
1509
- if (!txResponse?.effects?.status) return "pending";
1510
- return "success" === txResponse.effects.status.status ? "success" : "failure";
1511
- } catch (error) {
1512
- if (error instanceof Error) {
1513
- if (error.message.includes("not found") || error.message.includes("Could not find")) return "pending";
1514
- }
1515
- return "failure";
1516
- }
1517
- }
1518
- }
1519
- 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, getSuiClient, 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};