@minswap/noodles-sdk 0.0.38-next.2 → 0.0.39

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.cjs CHANGED
@@ -1,3316 +1 @@
1
- "use strict";
2
- const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
3
- return typeof document === 'undefined'
4
- ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
5
- : (document.currentScript && document.currentScript.src) ||
6
- new URL('main.js', document.baseURI).href;
7
- })();
8
- ;
9
- // The require scope
10
- var __webpack_require__ = {};
11
-
12
- // webpack/runtime/compat_get_default_export
13
- (() => {
14
- // getDefaultExport function for compatibility with non-ESM modules
15
- __webpack_require__.n = (module) => {
16
- var getter = module && module.__esModule ?
17
- () => (module['default']) :
18
- () => (module);
19
- __webpack_require__.d(getter, { a: getter });
20
- return getter;
21
- };
22
-
23
- })();
24
- // webpack/runtime/define_property_getters
25
- (() => {
26
- __webpack_require__.d = (exports, definition) => {
27
- for(var key in definition) {
28
- if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
29
- Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
30
- }
31
- }
32
- };
33
- })();
34
- // webpack/runtime/has_own_property
35
- (() => {
36
- __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
37
- })();
38
- // webpack/runtime/make_namespace_object
39
- (() => {
40
- // define __esModule on exports
41
- __webpack_require__.r = (exports) => {
42
- if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
43
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
44
- }
45
- Object.defineProperty(exports, '__esModule', { value: true });
46
- };
47
- })();
48
- var __webpack_exports__ = {};
49
- // ESM COMPAT FLAG
50
- __webpack_require__.r(__webpack_exports__);
51
-
52
- // EXPORTS
53
- __webpack_require__.d(__webpack_exports__, {
54
- addGasFee: () => (/* reexport */ addGasFee),
55
- TradeFeeOptions: () => (/* reexport */ types_TradeFeeOptions),
56
- SUBSCRIPTION_CONFIG_ID: () => (/* reexport */ SUBSCRIPTION_CONFIG_ID),
57
- getMemezPumpSDK: () => (/* reexport */ getMemezPumpSDK),
58
- DraftTransferTx: () => (/* reexport */ DraftTransferTx),
59
- BlastFunSDKCalculation: () => (/* reexport */ sdk_calculation_BlastFunSDKCalculation),
60
- MoonbagsConstants: () => (/* reexport */ constants_MoonbagsConstants),
61
- NoodlesPaySdk: () => (/* reexport */ NoodlesPaySdk),
62
- Bps: () => (/* reexport */ package_Bps),
63
- ADMIN_CAP_ID: () => (/* reexport */ ADMIN_CAP_ID),
64
- splitSuiCoinAfterFeeFromBuyTx: () => (/* reexport */ splitSuiCoinAfterFeeFromBuyTx),
65
- getMoveObject: () => (/* reexport */ getMoveObject),
66
- SUBSCRIPTION_PACKAGE_ID: () => (/* reexport */ SUBSCRIPTION_PACKAGE_ID),
67
- MoonbagsCalculation: () => (/* reexport */ calculation_MoonbagsCalculation),
68
- SUBSCRIPTION_ADMIN_CAP_ID: () => (/* reexport */ SUBSCRIPTION_ADMIN_CAP_ID),
69
- getSplitCoinsAfterFee: () => (/* reexport */ getSplitCoinsAfterFee),
70
- AstrosAggregator: () => (/* reexport */ astros_AstrosAggregator),
71
- BlastFunSDKTransaction: () => (/* reexport */ sdk_transaction_BlastFunSDKTransaction),
72
- CONFIG_ID: () => (/* reexport */ CONFIG_ID),
73
- AftermathAggregator: () => (/* reexport */ aftermath_AftermathAggregator),
74
- FlowXAggregator: () => (/* reexport */ flowx_FlowXAggregator),
75
- adaptSuiClient: () => (/* reexport */ adaptSuiClient),
76
- getNeededGasFee: () => (/* reexport */ getNeededGasFee),
77
- AggregatorModule: () => (/* reexport */ AggregatorModule),
78
- adaptTransaction: () => (/* reexport */ adaptTransaction),
79
- createCompatibleSuiClient: () => (/* reexport */ createCompatibleSuiClient),
80
- splitSuiCoinAfterFeeFromSellTx: () => (/* reexport */ splitSuiCoinAfterFeeFromSellTx),
81
- SupportedAggregator: () => (/* reexport */ common_SupportedAggregator),
82
- NATIVE_USDC_TOKEN_TYPE: () => (/* reexport */ NATIVE_USDC_TOKEN_TYPE),
83
- BOOSTING_PACKAGE_ID: () => (/* reexport */ BOOSTING_PACKAGE_ID),
84
- SUI_TYPE: () => (/* reexport */ SUI_TYPE),
85
- USDC_TOKEN_TYPE: () => (/* reexport */ USDC_TOKEN_TYPE),
86
- isSuiCoinType: () => (/* reexport */ isSuiCoinType),
87
- MoonbagsPackage: () => (/* reexport */ package_MoonbagsPackage),
88
- getCoinObjectIdsByAmount: () => (/* reexport */ getCoinObjectIdsByAmount),
89
- SUI_FULL_TYPE: () => (/* reexport */ SUI_FULL_TYPE),
90
- getAmountAfterFee: () => (/* reexport */ getAmountAfterFee),
91
- BLUEFIN_PACKAGE_ID: () => (/* reexport */ BLUEFIN_PACKAGE_ID),
92
- SubscriptionModule: () => (/* reexport */ SubscriptionModule),
93
- MathUtils: () => (/* reexport */ package_MathUtils),
94
- CLOCK_OBJECT_ID: () => (/* reexport */ CLOCK_OBJECT_ID),
95
- CurveModule: () => (/* reexport */ CurveModule),
96
- MoonbagsTransaction: () => (/* reexport */ transaction_MoonbagsTransaction),
97
- BlastFunPackage: () => (/* reexport */ package_BlastFunPackage),
98
- CetusAggregator: () => (/* reexport */ cetus_CetusAggregator),
99
- DEFAULT_TRADE_FEE: () => (/* reexport */ DEFAULT_TRADE_FEE),
100
- BlastFunCustomTransaction: () => (/* reexport */ custom_transaction_BlastFunCustomTransaction),
101
- NoodlesSdk: () => (/* reexport */ NoodlesSdk),
102
- BoostingModule: () => (/* reexport */ BoostingModule),
103
- getMoveObjectContent: () => (/* reexport */ getMoveObjectContent),
104
- getSplitCoinForTx: () => (/* reexport */ getSplitCoinForTx),
105
- BlastFunCustomCalculation: () => (/* reexport */ custom_calculation_BlastFunCustomCalculation),
106
- SupportedBondingCurve: () => (/* reexport */ types_SupportedBondingCurve),
107
- PAYMENT_COIN_TYPE: () => (/* reexport */ PAYMENT_COIN_TYPE),
108
- BASE_BPS: () => (/* reexport */ /* inlined export .BASE_BPS */ (10000)),
109
- BluefinTx: () => (/* reexport */ bluefin_BluefinTx),
110
- SUI_METADATA_OBJECT_ID: () => (/* reexport */ SUI_METADATA_OBJECT_ID),
111
- SevenKAggregator: () => (/* reexport */ _7k_SevenKAggregator),
112
- BlastFunConstants: () => (/* reexport */ constants_BlastFunConstants)
113
- });
114
-
115
- ;// CONCATENATED MODULE: external "@7kprotocol/sdk-ts"
116
- const sdk_ts_namespaceObject = require("@7kprotocol/sdk-ts");
117
- ;// CONCATENATED MODULE: external "@mysten/sui/transactions"
118
- const transactions_namespaceObject = require("@mysten/sui/transactions");
119
- ;// CONCATENATED MODULE: external "bignumber.js"
120
- const external_bignumber_js_namespaceObject = require("bignumber.js");
121
- var external_bignumber_js_default = /*#__PURE__*/__webpack_require__.n(external_bignumber_js_namespaceObject);
122
- ;// CONCATENATED MODULE: ./src/aggregator/7k.ts
123
-
124
-
125
-
126
- /**
127
- * 7K Protocol DEX aggregator client for routing trades across multiple pools
128
- * 7K Protocol aggregates liquidity from various DEXs to find optimal trade routes
129
- */ class _7k_SevenKAggregator {
130
- /** Configuration settings for the aggregator */ _config;
131
- /** Sui blockchain client */ _suiClient;
132
- /**
133
- * Creates a new SevenKAggregator instance
134
- * @param config - Aggregator configuration including fee settings and optional API key
135
- * @param suiClient - Sui client for blockchain interactions
136
- */ constructor(config, suiClient){
137
- this._config = config;
138
- this._suiClient = suiClient;
139
- // Config will be set lazily when the module is loaded
140
- }
141
- /**
142
- * Finds the optimal trade route for swapping tokens using 7K Protocol
143
- * @param params - Trade route parameters
144
- * @param params.coinInAmount - Amount of input token to swap
145
- * @param params.coinInType - Type/address of input token
146
- * @param params.coinOutType - Type/address of output token
147
- * @returns Promise resolving to quote response with pricing and route information, or null if no route found
148
- */ async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
149
- try {
150
- // Set API key if provided
151
- if (this._config.sevenKApiKey) {
152
- sdk_ts_namespaceObject.Config.setApiKey(this._config.sevenKApiKey);
153
- }
154
- const tradeFeePercent = tradeFee ? tradeFee.tradeFeePercent : this._config.defaultTradeFee.tradeFeePercent;
155
- return await (0,sdk_ts_namespaceObject.getQuote)({
156
- tokenIn: coinInType,
157
- tokenOut: coinOutType,
158
- amountIn: coinInAmount.toString(),
159
- commissionBps: tradeFeePercent * 10000
160
- });
161
- } catch (_err) {
162
- return null;
163
- }
164
- }
165
- /**
166
- * Builds a transaction for executing a trade route from 7K Protocol
167
- * @param params - Transaction parameters
168
- * @param params.walletAddress - Address of the wallet executing the trade
169
- * @param params.completeRoute - Complete quote response from getTradeRoute()
170
- * @param params.slippage - Maximum acceptable slippage (e.g., 0.01 for 1%)
171
- * @returns Promise resolving to built transaction bytes ready for signing and execution
172
- */ async getTransaction({ walletAddress, completeRoute, slippage, tradeFee }) {
173
- let tradeFeePercent;
174
- let tradeFeeRecipientAddress;
175
- if (tradeFee) {
176
- tradeFeePercent = tradeFee.tradeFeePercent;
177
- tradeFeeRecipientAddress = tradeFee.tradeFeeRecipientAddress;
178
- } else {
179
- tradeFeePercent = this._config.defaultTradeFee.tradeFeePercent;
180
- tradeFeeRecipientAddress = this._config.defaultTradeFee.tradeFeeRecipientAddress;
181
- }
182
- const transaction = await (0,sdk_ts_namespaceObject.buildTx)({
183
- quoteResponse: completeRoute,
184
- slippage,
185
- accountAddress: walletAddress,
186
- commission: {
187
- partner: tradeFeeRecipientAddress,
188
- commissionBps: tradeFeePercent * 10000
189
- }
190
- });
191
- if (transaction.tx instanceof sdk_ts_namespaceObject.BluefinXTx) {
192
- const newTransaction = transactions_namespaceObject.Transaction.from(transaction.tx.txBytes);
193
- return newTransaction.build({
194
- client: this._suiClient
195
- });
196
- }
197
- transaction.tx.setSender(walletAddress);
198
- return transaction.tx.build({
199
- client: this._suiClient
200
- });
201
- }
202
- }
203
- (function(SevenKAggregator) {
204
- function toCommonTradeRoutes(tradeRouteResponse) {
205
- const routes = [];
206
- if (!tradeRouteResponse.routes || tradeRouteResponse.routes.length === 0) {
207
- return null;
208
- }
209
- for (const route of tradeRouteResponse.routes){
210
- const paths = [];
211
- const allTokenDecimal = {};
212
- for (const path of route.hops){
213
- for (const t of path.pool.allTokens){
214
- allTokenDecimal[t.address] = t.decimal;
215
- }
216
- const pathDecimalIn = allTokenDecimal[path.tokenIn] ?? 0;
217
- const pathDecimalOut = allTokenDecimal[path.tokenOut] ?? 0;
218
- const pathAmountIn = BigInt(new (external_bignumber_js_default())(path.tokenInAmount).multipliedBy(10 ** pathDecimalIn).toFixed(0, 3));
219
- const pathAmountOut = BigInt(new (external_bignumber_js_default())(path.tokenOutAmount).multipliedBy(10 ** pathDecimalOut).toFixed(0, 3));
220
- paths.push({
221
- poolAddress: path.poolId,
222
- coinIn: path.tokenIn,
223
- coinOut: path.tokenOut,
224
- amountIn: pathAmountIn,
225
- amountOut: pathAmountOut
226
- });
227
- }
228
- if (paths.length === 0) {
229
- continue;
230
- }
231
- const routeDecimalIn = allTokenDecimal[route.tokenIn] ?? 0;
232
- const routeDecimalOut = allTokenDecimal[route.tokenOut] ?? 0;
233
- const routeAmountIn = BigInt(new (external_bignumber_js_default())(route.tokenInAmount).multipliedBy(10 ** routeDecimalIn).toFixed(0, 3));
234
- const routeAmountOut = BigInt(new (external_bignumber_js_default())(route.tokenOutAmount).multipliedBy(10 ** routeDecimalOut).toFixed(0, 3));
235
- routes.push({
236
- paths: paths,
237
- coinIn: route.tokenIn,
238
- coinOut: route.tokenOut,
239
- amountIn: routeAmountIn,
240
- amountOut: routeAmountOut
241
- });
242
- }
243
- if (routes.length === 0) {
244
- return null;
245
- }
246
- return {
247
- coinIn: tradeRouteResponse.tokenIn,
248
- coinOut: tradeRouteResponse.tokenOut,
249
- amountIn: BigInt(tradeRouteResponse.swapAmountWithDecimal),
250
- amountOut: BigInt(tradeRouteResponse.returnAmountWithDecimal),
251
- routes: routes
252
- };
253
- }
254
- SevenKAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
255
- })(_7k_SevenKAggregator || (_7k_SevenKAggregator = {}));
256
-
257
- ;// CONCATENATED MODULE: external "aftermath-ts-sdk"
258
- const external_aftermath_ts_sdk_namespaceObject = require("aftermath-ts-sdk");
259
- ;// CONCATENATED MODULE: ./src/aggregator/aftermath.ts
260
-
261
- /**
262
- * Aftermath DEX aggregator client for routing trades across multiple pools
263
- */ class aftermath_AftermathAggregator {
264
- /** Configuration settings for the aggregator */ _config;
265
- /** Aftermath SDK client instance (lazy-loaded on first use) */ _aftermathClient;
266
- /** Sui blockchain client */ _suiClient;
267
- /**
268
- * Creates a new AftermathAggregator instance
269
- * @param config - Aggregator configuration including optional API settings
270
- * @param suiClient - Sui client for blockchain interactions
271
- */ constructor(config, suiClient){
272
- this._config = config;
273
- this._suiClient = suiClient;
274
- }
275
- /**
276
- * Lazy-loads and returns the Aftermath client, initializing it on first use
277
- * Handles authentication if API key is provided in config
278
- * @returns Promise resolving to initialized Aftermath client
279
- */ async aftermathClient() {
280
- if (this._aftermathClient) {
281
- return this._aftermathClient;
282
- }
283
- if (this._config.aftermathApiEndpoint) {
284
- this._aftermathClient = new external_aftermath_ts_sdk_namespaceObject.Aftermath(this._config.aftermathApiEndpoint);
285
- } else {
286
- this._aftermathClient = new external_aftermath_ts_sdk_namespaceObject.Aftermath("MAINNET");
287
- }
288
- await this._aftermathClient.init();
289
- if (this._config.aftermathApiKey) {
290
- const keypair = external_aftermath_ts_sdk_namespaceObject.Helpers.keypairFromPrivateKey(this._config.aftermathApiKey);
291
- await this._aftermathClient.Auth().init({
292
- async signMessageCallback ({ message }) {
293
- const { signature } = await keypair.signPersonalMessage(message);
294
- return {
295
- signature
296
- };
297
- },
298
- walletAddress: keypair.toSuiAddress()
299
- });
300
- }
301
- return this._aftermathClient;
302
- }
303
- /**
304
- * Finds the optimal trade route for swapping tokens
305
- * @param params - Trade route parameters
306
- * @param params.coinInAmount - Amount of input token to swap
307
- * @param params.coinInType - Type/address of input token
308
- * @param params.coinOutType - Type/address of output token
309
- * @returns Promise resolving to complete trade route with pricing and path information
310
- */ async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
311
- try {
312
- let externalFee;
313
- if (tradeFee) {
314
- externalFee = {
315
- recipient: tradeFee.tradeFeeRecipientAddress,
316
- feePercentage: tradeFee.tradeFeePercent
317
- };
318
- } else {
319
- externalFee = {
320
- recipient: this._config.defaultTradeFee.tradeFeeRecipientAddress,
321
- feePercentage: this._config.defaultTradeFee.tradeFeePercent
322
- };
323
- }
324
- const client = await this.aftermathClient();
325
- return await client.Router().getCompleteTradeRouteGivenAmountIn({
326
- coinInAmount,
327
- coinInType,
328
- coinOutType,
329
- externalFee
330
- });
331
- } catch (_err) {
332
- return null;
333
- }
334
- }
335
- /**
336
- * Builds a transaction for executing a trade route
337
- * @param params - Transaction parameters
338
- * @param params.completeRoute - Complete trade route from getTradeRoute()
339
- * @param params.walletAddress - Address of the wallet executing the trade
340
- * @param params.slippage - Maximum acceptable slippage (e.g., 0.01 for 1%)
341
- * @returns Promise resolving to built transaction bytes ready for signing and execution
342
- */ async getTransaction({ completeRoute, walletAddress, slippage }) {
343
- const client = await this.aftermathClient();
344
- const transaction = await client.Router().getTransactionForCompleteTradeRoute({
345
- completeRoute,
346
- walletAddress,
347
- slippage,
348
- isSponsoredTx: false
349
- });
350
- transaction.setSender(walletAddress);
351
- return transaction.build({
352
- client: this._suiClient
353
- });
354
- }
355
- }
356
- (function(AftermathAggregator) {
357
- function toCommonTradeRoutes(tradeRoute) {
358
- if (tradeRoute.routes.length === 0) {
359
- return null;
360
- }
361
- const routes = [];
362
- for (const route of tradeRoute.routes){
363
- const paths = [];
364
- for (const path of route.paths){
365
- paths.push({
366
- poolAddress: path.poolId,
367
- coinIn: path.coinIn.type,
368
- coinOut: path.coinOut.type,
369
- amountIn: BigInt(path.coinIn.amount),
370
- amountOut: BigInt(path.coinOut.amount)
371
- });
372
- }
373
- if (paths.length === 0) {
374
- continue;
375
- }
376
- routes.push({
377
- paths: paths,
378
- coinIn: route.coinIn.type,
379
- coinOut: route.coinOut.type,
380
- amountIn: route.coinIn.amount,
381
- amountOut: route.coinOut.amount
382
- });
383
- }
384
- if (routes.length === 0) {
385
- return null;
386
- }
387
- return {
388
- coinIn: tradeRoute.coinIn.type,
389
- coinOut: tradeRoute.coinOut.type,
390
- amountIn: tradeRoute.coinIn.amount,
391
- amountOut: tradeRoute.coinOut.amount,
392
- routes: routes
393
- };
394
- }
395
- AftermathAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
396
- })(aftermath_AftermathAggregator || (aftermath_AftermathAggregator = {}));
397
-
398
- ;// CONCATENATED MODULE: external "@naviprotocol/astros-aggregator-sdk"
399
- const astros_aggregator_sdk_namespaceObject = require("@naviprotocol/astros-aggregator-sdk");
400
- ;// CONCATENATED MODULE: ./src/aggregator/astros.ts
401
-
402
-
403
-
404
- /**
405
- * Utility function to check if a coin type is SUI
406
- * @param coin - The coin type string to check
407
- * @returns True if the coin is SUI, false otherwise
408
- */ function isSuiCoin(coin) {
409
- return coin === "0x2::sui::SUI" || coin === "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";
410
- }
411
- /**
412
- * Astros DEX aggregator client for routing trades across multiple pools
413
- * Provides access to liquidity aggregation from various DEX protocols
414
- */ class astros_AstrosAggregator {
415
- /** Configuration settings for the aggregator */ _config;
416
- /** Sui blockchain client */ _suiClient;
417
- /**
418
- * Creates a new AstrosAggregator instance
419
- * @param config - Aggregator configuration including optional fee settings
420
- * @param suiClient - Sui client for blockchain interactions
421
- */ constructor(config, suiClient){
422
- this._config = config;
423
- this._suiClient = suiClient;
424
- }
425
- /**
426
- * Finds the optimal trade route for swapping tokens using Astros aggregator
427
- * @param params - Trade route parameters
428
- * @param params.coinInAmount - Amount of input token to swap
429
- * @param params.coinInType - Type/address of input token
430
- * @param params.coinOutType - Type/address of output token
431
- * @returns Promise resolving to quote with pricing and route information, or null if no route found
432
- */ async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
433
- try {
434
- let serviceFee;
435
- if (tradeFee) {
436
- serviceFee = {
437
- fee: tradeFee.tradeFeePercent,
438
- receiverAddress: tradeFee.tradeFeeRecipientAddress
439
- };
440
- } else {
441
- serviceFee = {
442
- fee: this._config.defaultTradeFee.tradeFeePercent,
443
- receiverAddress: this._config.defaultTradeFee.tradeFeeRecipientAddress
444
- };
445
- }
446
- return await (0,astros_aggregator_sdk_namespaceObject.getQuote)(coinInType, coinOutType, coinInAmount, this._config.astrosApiKey, {
447
- byAmountIn: true,
448
- serviceFee: serviceFee
449
- });
450
- } catch (_err) {
451
- return null;
452
- }
453
- }
454
- /**
455
- * Merges multiple coin objects into a single coin for trading
456
- * Optimizes coin usage by merging smaller coins into larger ones
457
- * @param txb - Transaction builder instance
458
- * @param coins - Array of coin objects to merge
459
- * @param amount - Required amount for the trade
460
- * @returns Transaction object reference for the merged coin
461
- */ returnMergedCoins(txb, coins, amount) {
462
- if (coins.length < 2) {
463
- return txb.object(coins[0].coinObjectId);
464
- }
465
- let mergedBalance = 0;
466
- const mergeList = [];
467
- coins.sort((a, b)=>Number(b.balance) - Number(a.balance)).slice(1).forEach((coin)=>{
468
- if (mergedBalance >= amount) {
469
- return;
470
- }
471
- mergedBalance += Number(coin.balance);
472
- mergeList.push(coin.coinObjectId);
473
- });
474
- const baseObj = coins[0].coinObjectId;
475
- txb.mergeCoins(baseObj, mergeList);
476
- return txb.object(baseObj);
477
- }
478
- /**
479
- * Builds a transaction for executing a trade route from Astros aggregator
480
- * @param params - Transaction parameters
481
- * @param params.completeRoute - Complete quote from getTradeRoute() (aliased as quote)
482
- * @param params.walletAddress - Address of the wallet executing the trade
483
- * @param params.slippage - Maximum acceptable slippage (e.g., 0.01 for 1%)
484
- * @returns Promise resolving to built transaction bytes ready for signing and execution
485
- */ async getTransaction({ completeRoute: quote, walletAddress, slippage, tradeFee }) {
486
- let serviceFee;
487
- if (tradeFee) {
488
- serviceFee = {
489
- fee: tradeFee.tradeFeePercent,
490
- receiverAddress: tradeFee.tradeFeeRecipientAddress
491
- };
492
- } else {
493
- serviceFee = {
494
- fee: this._config.defaultTradeFee.tradeFeePercent,
495
- receiverAddress: this._config.defaultTradeFee.tradeFeeRecipientAddress
496
- };
497
- }
498
- const minAmountOut = new (external_bignumber_js_default())(quote.amount_out).multipliedBy(1 - slippage - serviceFee.fee).toNumber();
499
- const txb = new transactions_namespaceObject.Transaction();
500
- let coinIn;
501
- if (isSuiCoin(quote.from)) {
502
- coinIn = txb.splitCoins(txb.gas, [
503
- txb.pure.u64(quote.amount_in)
504
- ]);
505
- } else {
506
- const coins = await (0,astros_aggregator_sdk_namespaceObject.getCoins)(this._suiClient, walletAddress, quote.from);
507
- const mergedCoins = this.returnMergedCoins(txb, coins.data, Number.parseFloat(quote.amount_in));
508
- coinIn = txb.splitCoins(mergedCoins, [
509
- txb.pure.u64(quote.amount_in)
510
- ]);
511
- }
512
- const coinB = await (0,astros_aggregator_sdk_namespaceObject.buildSwapPTBFromQuote)(walletAddress, txb, minAmountOut, coinIn, quote, undefined, false, this._config.astrosApiKey, {
513
- serviceFee: serviceFee
514
- });
515
- txb.transferObjects([
516
- coinB
517
- ], walletAddress);
518
- txb.setSender(walletAddress);
519
- return txb.build({
520
- client: this._suiClient
521
- });
522
- }
523
- }
524
- (function(AstrosAggregator) {
525
- function toCommonTradeRoutes(tradeRoute, coinInType, coinOutType) {
526
- if (tradeRoute.routes.length === 0) {
527
- return null;
528
- }
529
- const routes = [];
530
- for (const route of tradeRoute.routes){
531
- const paths = [];
532
- for (const path of route.path){
533
- paths.push({
534
- poolAddress: path.id,
535
- coinIn: path.from,
536
- coinOut: path.target,
537
- amountIn: BigInt(path.amount_in),
538
- amountOut: BigInt(path.amount_out)
539
- });
540
- }
541
- if (paths.length === 0) {
542
- continue;
543
- }
544
- routes.push({
545
- amountIn: BigInt(route.amount_in),
546
- amountOut: BigInt(route.amount_out),
547
- coinIn: paths[0].coinIn,
548
- coinOut: paths[paths.length - 1].coinOut,
549
- paths: paths
550
- });
551
- }
552
- if (routes.length === 0) {
553
- return null;
554
- }
555
- return {
556
- coinIn: coinInType,
557
- coinOut: coinOutType,
558
- amountIn: BigInt(tradeRoute.amount_in),
559
- amountOut: BigInt(tradeRoute.amount_out),
560
- routes: routes
561
- };
562
- }
563
- AstrosAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
564
- })(astros_AstrosAggregator || (astros_AstrosAggregator = {}));
565
-
566
- ;// CONCATENATED MODULE: external "@cetusprotocol/aggregator-sdk"
567
- const aggregator_sdk_namespaceObject = require("@cetusprotocol/aggregator-sdk");
568
- ;// CONCATENATED MODULE: external "bn.js"
569
- const external_bn_js_namespaceObject = require("bn.js");
570
- var external_bn_js_default = /*#__PURE__*/__webpack_require__.n(external_bn_js_namespaceObject);
571
- ;// CONCATENATED MODULE: ./src/fee/types.ts
572
- /**
573
- * Configuration options for trade fees applied to aggregator transactions
574
- */ (function(TradeFeeOptions) {
575
- function equals(a, b) {
576
- return a.tradeFeePercent === b.tradeFeePercent && a.tradeFeeRecipientAddress === b.tradeFeeRecipientAddress;
577
- }
578
- TradeFeeOptions.equals = equals;
579
- })(types_TradeFeeOptions || (types_TradeFeeOptions = {}));
580
- var types_TradeFeeOptions;
581
-
582
- ;// CONCATENATED MODULE: ./src/aggregator/cetus.ts
583
-
584
-
585
-
586
-
587
- /**
588
- * Cetus DEX aggregator client for routing trades across multiple pools
589
- * Cetus is a concentrated liquidity protocol that provides efficient trading
590
- */ class cetus_CetusAggregator {
591
- /** Configuration settings for the aggregator */ _config;
592
- /** Sui blockchain client */ _suiClient;
593
- /** Cetus aggregator client instance (lazy-loaded) */ _cetusClient;
594
- /**
595
- * Creates a new CetusAggregator instance
596
- * @param config - Aggregator configuration including fee settings and optional API credentials
597
- * @param suiClient - Sui client for blockchain interactions
598
- */ constructor(config, suiClient){
599
- this._config = config;
600
- this._suiClient = suiClient;
601
- }
602
- /**
603
- * Lazy-loads and returns the Cetus aggregator client, initializing it on first use
604
- * Configures the client with overlay fees, API credentials, and partner information
605
- * @param walletAddress - Optional wallet address for signing transactions
606
- * @param tradeFee - Optional custom trade fee settings for this client instance
607
- * @returns Initialized Cetus AggregatorClient instance
608
- */ cetusClient(walletAddress, tradeFee) {
609
- if (tradeFee && !types_TradeFeeOptions.equals(tradeFee, this._config.defaultTradeFee)) {
610
- return new aggregator_sdk_namespaceObject.AggregatorClient({
611
- client: this._suiClient,
612
- overlayFeeReceiver: tradeFee.tradeFeeRecipientAddress,
613
- overlayFeeRate: tradeFee.tradeFeePercent,
614
- env: aggregator_sdk_namespaceObject.Env.Mainnet,
615
- signer: walletAddress,
616
- ...this._config.cetusApiKey && this._config.cetusApiEndpoint ? {
617
- apiKey: this._config.cetusApiKey,
618
- endpoint: this._config.cetusApiEndpoint
619
- } : {},
620
- partner: this._config.cetusPartnerId
621
- });
622
- }
623
- if (this._cetusClient) {
624
- return this._cetusClient;
625
- }
626
- this._cetusClient = new aggregator_sdk_namespaceObject.AggregatorClient({
627
- client: this._suiClient,
628
- overlayFeeReceiver: this._config.defaultTradeFee.tradeFeeRecipientAddress,
629
- overlayFeeRate: this._config.defaultTradeFee.tradeFeePercent,
630
- env: aggregator_sdk_namespaceObject.Env.Mainnet,
631
- signer: walletAddress,
632
- ...this._config.cetusApiKey && this._config.cetusApiEndpoint ? {
633
- apiKey: this._config.cetusApiKey,
634
- endpoint: this._config.cetusApiEndpoint
635
- } : {},
636
- partner: this._config.cetusPartnerId
637
- });
638
- return this._cetusClient;
639
- }
640
- /**
641
- * Finds the optimal trade route for swapping tokens using Cetus aggregator
642
- * @param params - Trade route parameters
643
- * @param params.coinInAmount - Amount of input token to swap
644
- * @param params.coinInType - Type/address of input token
645
- * @param params.coinOutType - Type/address of output token
646
- * @returns Promise resolving to router data with pricing and route information, or null if no route found
647
- */ async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
648
- try {
649
- const client = this.cetusClient(undefined, tradeFee);
650
- return await client.findRouters({
651
- from: coinInType,
652
- target: coinOutType,
653
- amount: new (external_bn_js_default())(coinInAmount.toString()),
654
- byAmountIn: true
655
- });
656
- } catch (_err) {
657
- return null;
658
- }
659
- }
660
- /**
661
- * Builds a transaction for executing a trade route from Cetus aggregator
662
- * @param params - Transaction parameters
663
- * @param params.completeRoute - Complete router data from getTradeRoute() (aliased as routers)
664
- * @param params.walletAddress - Address of the wallet executing the trade
665
- * @param params.slippage - Maximum acceptable slippage (e.g., 0.01 for 1%)
666
- * @returns Promise resolving to built transaction bytes ready for signing and execution
667
- */ async getTransaction({ completeRoute: routers, walletAddress, slippage, tradeFee }) {
668
- const client = this.cetusClient(walletAddress, tradeFee);
669
- const txb = new transactions_namespaceObject.Transaction();
670
- txb.setSender(walletAddress);
671
- await client.fastRouterSwap({
672
- router: routers,
673
- txb,
674
- slippage
675
- });
676
- return txb.build({
677
- client: this._suiClient
678
- });
679
- }
680
- }
681
- (function(CetusAggregator) {
682
- function toCommonTradeRoutes(tradeRoute, coinInType, coinOutType) {
683
- if (tradeRoute.paths.length === 0) {
684
- return null;
685
- }
686
- const routes = [];
687
- const allPaths = [];
688
- let currentRoute = [];
689
- for(let i = 0; i < tradeRoute.paths.length; i++){
690
- const currentPath = tradeRoute.paths[i];
691
- const tradePath = {
692
- poolAddress: currentPath.id,
693
- amountIn: BigInt(currentPath.amountIn),
694
- amountOut: BigInt(currentPath.amountOut),
695
- coinIn: currentPath.from,
696
- coinOut: currentPath.target
697
- };
698
- // Add current path to the current route
699
- currentRoute.push(tradePath);
700
- // Check if this is the last path or if the next path starts a new route
701
- if (i === tradeRoute.paths.length - 1) {
702
- // This is the last path, finish the current route
703
- allPaths.push([
704
- ...currentRoute
705
- ]);
706
- } else {
707
- const nextPath = tradeRoute.paths[i + 1];
708
- if (currentPath.target !== nextPath.from) {
709
- // Next path doesn't connect, so current route is complete
710
- allPaths.push([
711
- ...currentRoute
712
- ]);
713
- currentRoute = []; // Start a new route
714
- }
715
- // If currentPath.target === nextPath.from, continue building the current route
716
- }
717
- }
718
- for (const pathGroup of allPaths){
719
- if (pathGroup.length === 0) {
720
- continue;
721
- }
722
- routes.push({
723
- amountIn: pathGroup[0].amountIn,
724
- amountOut: pathGroup[pathGroup.length - 1].amountOut,
725
- coinIn: pathGroup[0].coinIn,
726
- coinOut: pathGroup[pathGroup.length - 1].coinOut,
727
- paths: pathGroup
728
- });
729
- }
730
- if (routes.length === 0) {
731
- return null;
732
- }
733
- return {
734
- coinIn: coinInType,
735
- coinOut: coinOutType,
736
- amountIn: BigInt(tradeRoute.amountIn.toString(10)),
737
- amountOut: BigInt(tradeRoute.amountOut.toString(10)),
738
- routes: routes
739
- };
740
- }
741
- CetusAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
742
- })(cetus_CetusAggregator || (cetus_CetusAggregator = {}));
743
-
744
- ;// CONCATENATED MODULE: ./src/aggregator/common.ts
745
- var common_SupportedAggregator = /*#__PURE__*/ function(SupportedAggregator) {
746
- SupportedAggregator["ASTROS"] = "ASTROS";
747
- SupportedAggregator["AFTERMATH"] = "AFTERMATH";
748
- SupportedAggregator["SEVENK"] = "7K";
749
- SupportedAggregator["CETUS"] = "CETUS";
750
- SupportedAggregator["FLOWX"] = "FLOWX";
751
- return SupportedAggregator;
752
- }({});
753
-
754
- ;// CONCATENATED MODULE: external "@flowx-finance/sdk"
755
- const sdk_namespaceObject = require("@flowx-finance/sdk");
756
- ;// CONCATENATED MODULE: ./src/aggregator/flowx.ts
757
-
758
- /**
759
- * Converts percentage to FlowX's expected format (1e6 multiplier)
760
- * @param percent - Percentage value (e.g., 0.01 for 1%)
761
- * @returns Percentage in FlowX format (1% = 1,000,000)
762
- */ function getInputPercent(percent) {
763
- return 1e6 * percent;
764
- }
765
- /**
766
- * FlowX DEX aggregator client for routing trades across multiple pools
767
- * FlowX provides liquidity aggregation and optimized routing for Sui ecosystem
768
- */ class flowx_FlowXAggregator {
769
- /** Configuration settings for the aggregator */ _config;
770
- /** Sui blockchain client */ _suiClient;
771
- /**
772
- * Creates a new FlowXAggregator instance
773
- * @param config - Aggregator configuration including fee settings and optional API key
774
- * @param suiClient - Sui client for blockchain interactions
775
- */ constructor(config, suiClient){
776
- this._config = config;
777
- this._suiClient = suiClient;
778
- }
779
- /**
780
- * Creates a commission configuration for FlowX trades
781
- * @param coinInType - Type/address of the input coin for commission calculation
782
- * @param tradeFee - Optional custom trade fee settings for this commission
783
- * @returns Commission instance configured with fee recipient, percentage, and coin type
784
- */ getCommission(coinInType, tradeFee) {
785
- let tradeFeePercent;
786
- let tradeFeeRecipientAddress;
787
- if (tradeFee) {
788
- tradeFeePercent = tradeFee.tradeFeePercent;
789
- tradeFeeRecipientAddress = tradeFee.tradeFeeRecipientAddress;
790
- } else {
791
- tradeFeePercent = this._config.defaultTradeFee.tradeFeePercent;
792
- tradeFeeRecipientAddress = this._config.defaultTradeFee.tradeFeeRecipientAddress;
793
- }
794
- return new sdk_namespaceObject.Commission(tradeFeeRecipientAddress, new sdk_namespaceObject.Coin(coinInType), sdk_namespaceObject.CommissionType.PERCENTAGE, getInputPercent(tradeFeePercent), true);
795
- }
796
- /**
797
- * Finds the optimal trade route for swapping tokens using FlowX aggregator
798
- * @param params - Trade route parameters
799
- * @param params.coinInAmount - Amount of input token to swap
800
- * @param params.coinInType - Type/address of input token
801
- * @param params.coinOutType - Type/address of output token
802
- * @returns Promise resolving to routes result with pricing and path information, or null if no route found
803
- */ async getTradeRoute({ coinInAmount, coinInType, coinOutType, tradeFee }) {
804
- const quoter = new sdk_namespaceObject.AggregatorQuoter("mainnet", this._config.flowxApiKey);
805
- try {
806
- return await quoter.getRoutes({
807
- tokenIn: coinInType,
808
- tokenOut: coinOutType,
809
- amountIn: coinInAmount.toString(),
810
- commission: this.getCommission(coinInType, tradeFee)
811
- });
812
- } catch (_err) {
813
- return null;
814
- }
815
- }
816
- /**
817
- * Builds a transaction for executing a trade route from FlowX aggregator
818
- * @param params - Transaction parameters
819
- * @param params.walletAddress - Address of the wallet executing the trade
820
- * @param params.completeRoute - Complete routes result from getTradeRoute()
821
- * @param params.slippage - Maximum acceptable slippage (e.g., 0.01 for 1%)
822
- * @returns Promise resolving to built transaction bytes ready for signing and execution
823
- */ async getTransaction({ walletAddress, completeRoute, slippage, tradeFee }) {
824
- const tradeBuilder = new sdk_namespaceObject.TradeBuilder("mainnet", completeRoute.routes);
825
- const result = tradeBuilder.sender(walletAddress).slippage(getInputPercent(slippage)).commission(this.getCommission(completeRoute.coinIn.coinType, tradeFee)).build();
826
- return result.buildTransaction({
827
- client: this._suiClient
828
- }).then((tx)=>{
829
- tx.setSender(walletAddress);
830
- return tx.build({
831
- client: this._suiClient
832
- });
833
- });
834
- }
835
- }
836
- (function(FlowXAggregator) {
837
- function toCommonTradeRoutes(tradeRoute) {
838
- if (tradeRoute.routes.length === 0) {
839
- return null;
840
- }
841
- const routes = [];
842
- for (const route of tradeRoute.routes){
843
- const paths = [];
844
- for (const path of route.paths){
845
- paths.push({
846
- amountIn: BigInt(path.amountIn.toString()),
847
- amountOut: BigInt(path.amountOut.toString()),
848
- coinIn: path.input.coinType,
849
- coinOut: path.output.coinType,
850
- poolAddress: path.pool.id
851
- });
852
- }
853
- if (paths.length === 0) {
854
- continue;
855
- }
856
- routes.push({
857
- amountIn: BigInt(route.amountIn.toString()),
858
- amountOut: BigInt(route.amountOut.toString()),
859
- coinIn: route.input.coinType,
860
- coinOut: route.output.coinType,
861
- paths: paths
862
- });
863
- }
864
- if (routes.length === 0) {
865
- return null;
866
- }
867
- return {
868
- coinIn: tradeRoute.coinIn.coinType,
869
- coinOut: tradeRoute.coinOut.coinType,
870
- amountIn: BigInt(tradeRoute.amountIn.toString()),
871
- amountOut: BigInt(tradeRoute.amountOut.toString()),
872
- routes: routes
873
- };
874
- }
875
- FlowXAggregator.toCommonTradeRoutes = toCommonTradeRoutes;
876
- })(flowx_FlowXAggregator || (flowx_FlowXAggregator = {}));
877
-
878
- ;// CONCATENATED MODULE: ./src/aggregator/index.ts
879
-
880
-
881
-
882
-
883
-
884
-
885
-
886
-
887
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/constants.ts
888
- (function(BlastFunConstants) {
889
- BlastFunConstants.PACKAGE_ID_V4 = "0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd";
890
- BlastFunConstants.MEMEZ_AV_OBJECT_ID = "0x2319e3e76dfad73d8f4684bdbf42be4f32d8ce4521dd61becc8261dc918d82c0";
891
- })(constants_BlastFunConstants || (constants_BlastFunConstants = {}));
892
- var constants_BlastFunConstants;
893
-
894
- ;// CONCATENATED MODULE: external "@minswap/tiny-invariant"
895
- const tiny_invariant_namespaceObject = require("@minswap/tiny-invariant");
896
- var tiny_invariant_default = /*#__PURE__*/__webpack_require__.n(tiny_invariant_namespaceObject);
897
- ;// CONCATENATED MODULE: ./src/libs/move/index.ts
898
-
899
- async function getMoveObjectContent(suiClient, objectId) {
900
- const moveObject = await getMoveObject(suiClient, objectId);
901
- return moveObject.fields;
902
- }
903
- async function getMoveObject(suiClient, objectId) {
904
- const objRes = await suiClient.getObject({
905
- id: objectId,
906
- options: {
907
- showContent: true
908
- }
909
- });
910
- const content = objRes.data?.content;
911
- tiny_invariant_default()(content, "Pool object not found or has no content");
912
- tiny_invariant_default()(content.dataType === "moveObject", "Object is not a Move object");
913
- return content;
914
- }
915
-
916
- ;// CONCATENATED MODULE: ./src/libs/math/fee.ts
917
- const BASE_BPS = 10000;
918
- function getSplitCoinsAfterFee(amount, fee) {
919
- const amountNum = BigInt(amount);
920
- const feeNum = BigInt(Number(fee) * BASE_BPS);
921
- if (feeNum === BigInt(0)) {
922
- return [
923
- amountNum.toString()
924
- ];
925
- }
926
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
927
- const remainingAmount = amountNum - feeAmount;
928
- return [
929
- remainingAmount.toString(),
930
- feeAmount.toString()
931
- ];
932
- }
933
- function getAmountAfterFee(amount, fee) {
934
- if (!fee || Number(fee) <= 0) {
935
- return BigInt(amount);
936
- }
937
- const amountNum = BigInt(amount);
938
- const feeNum = BigInt(Number(fee) * BASE_BPS);
939
- if (feeNum === BigInt(0)) {
940
- return amountNum;
941
- }
942
- const feeAmount = amountNum * feeNum / BigInt(BASE_BPS);
943
- return amountNum - feeAmount;
944
- }
945
- async function getNeededGasFee(suiClient, tx, sender, bufferPercent) {
946
- const { effects: { gasUsed, status } } = await suiClient.devInspectTransactionBlock({
947
- sender,
948
- transactionBlock: tx
949
- });
950
- if (status.status !== "success") {
951
- throw new Error(`Transaction failed during dev inspect: ${status.error ?? ""}`);
952
- }
953
- const fee = BigInt(gasUsed.computationCost) + BigInt(gasUsed.storageCost) - BigInt(gasUsed.storageRebate);
954
- const feeNum = BigInt(Number(bufferPercent) * BASE_BPS);
955
- return fee * (BigInt(BASE_BPS) + feeNum) / BigInt(BASE_BPS);
956
- }
957
-
958
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/package.ts
959
-
960
-
961
- (function(MathUtils) {
962
- (function(U64) {
963
- function mulDivUp(a, b, c) {
964
- let roundUp = BigInt(0);
965
- if (a * b % c > BigInt(0)) {
966
- roundUp = BigInt(1);
967
- }
968
- return a * b / c + roundUp;
969
- }
970
- U64.mulDivUp = mulDivUp;
971
- })(MathUtils.U64 || (MathUtils.U64 = {}));
972
- })(package_MathUtils || (package_MathUtils = {}));
973
- (function(Bps) {
974
- function calcUp(bps, amount) {
975
- const bpsValue = BigInt(bps.pos0);
976
- const denominator = BigInt(10000);
977
- let roundUp;
978
- if (bpsValue * amount % denominator !== BigInt(0)) {
979
- roundUp = BigInt(1);
980
- } else {
981
- roundUp = BigInt(0);
982
- }
983
- return bpsValue * amount / denominator + roundUp;
984
- }
985
- Bps.calcUp = calcUp;
986
- function sub(lhs, rhs) {
987
- tiny_invariant_default()(BigInt(lhs.pos0) >= BigInt(rhs.pos0), "Bps underflow");
988
- return {
989
- pos0: (BigInt(lhs.pos0) - BigInt(rhs.pos0)).toString()
990
- };
991
- }
992
- Bps.sub = sub;
993
- function value(bps) {
994
- return BigInt(bps.pos0);
995
- }
996
- Bps.value = value;
997
- function new_(bps) {
998
- return {
999
- pos0: assertOverflow(bps).toString()
1000
- };
1001
- }
1002
- Bps.new_ = new_;
1003
- function assertOverflow(bps) {
1004
- tiny_invariant_default()(BigInt(bps) <= BigInt(10000), "Bps overflow");
1005
- return BigInt(bps);
1006
- }
1007
- Bps.assertOverflow = assertOverflow;
1008
- })(package_Bps || (package_Bps = {}));
1009
- (function(BlastFunPackage) {
1010
- (function(MemezFun) {
1011
- async function isSniperProtectedMemezFun(suiClient, poolId) {
1012
- const memezFun = await getMoveObjectContent(suiClient, poolId);
1013
- return memezFun.public_key.length > 0;
1014
- }
1015
- MemezFun.isSniperProtectedMemezFun = isSniperProtectedMemezFun;
1016
- })(BlastFunPackage.MemezFun || (BlastFunPackage.MemezFun = {}));
1017
- (function(MemezFees) {
1018
- function takeWithDiscount(fee, amount, discountBps) {
1019
- if (fee.variant === "Value") {
1020
- const amountRequired = BigInt(fee.fields.pos0);
1021
- if (amountRequired === BigInt(0)) {
1022
- return BigInt(0);
1023
- }
1024
- if (amount >= amountRequired) {
1025
- return amountRequired;
1026
- }
1027
- throw new Error(`Insufficient amount to cover fee. Required: ${amountRequired}, provided: ${amount}`);
1028
- } else if (fee.variant === "Percentage") {
1029
- const feeBps = fee.fields.pos0.fields;
1030
- if (BigInt(feeBps.pos0) === BigInt(0)) {
1031
- return BigInt(0);
1032
- }
1033
- const discountedFee = package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
1034
- if (amount >= discountedFee) {
1035
- return discountedFee;
1036
- } else {
1037
- throw new Error(`Insufficient amount to cover fee. Required: ${discountedFee}, provided: ${amount}`);
1038
- }
1039
- }
1040
- throw new Error(`Unknown fee variant`);
1041
- }
1042
- // return fee amount taken from `amount`
1043
- MemezFees.takeWithDiscount = takeWithDiscount;
1044
- function calculateWithDiscount(fee, discountBps, amount) {
1045
- if (fee.variant === "Value") {
1046
- return BigInt(fee.fields.pos0);
1047
- } else if (fee.variant === "Percentage") {
1048
- const feeBps = fee.fields.pos0.fields;
1049
- return package_Bps.calcUp(package_Bps.sub(feeBps, discountBps), amount);
1050
- }
1051
- throw new Error(`Unknown fee variant`);
1052
- }
1053
- MemezFees.calculateWithDiscount = calculateWithDiscount;
1054
- })(BlastFunPackage.MemezFees || (BlastFunPackage.MemezFees = {}));
1055
- (function(MemezBurner) {
1056
- function calculate(burner, poolMemeBalance) {
1057
- const burnerFee = package_Bps.value(burner.fee.fields);
1058
- if (burnerFee === BigInt(0) || poolMemeBalance === BigInt(0)) {
1059
- return package_Bps.new_(0);
1060
- }
1061
- if (poolMemeBalance >= BigInt(burner.target_liquidity)) {
1062
- return package_Bps.new_(0);
1063
- }
1064
- const baseBps = BigInt(10000);
1065
- 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));
1066
- }
1067
- MemezBurner.calculate = calculate;
1068
- })(BlastFunPackage.MemezBurner || (BlastFunPackage.MemezBurner = {}));
1069
- (function(MemezPump) {
1070
- async function getPumpState(suiClient, memezFun) {
1071
- return await getMoveObjectContent(suiClient, memezFun.inner_state);
1072
- }
1073
- MemezPump.getPumpState = getPumpState;
1074
- function pump(pumpState, quoteAmount) {
1075
- const constantProduct = pumpState.constant_product.fields;
1076
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteAmount, constantProduct.quote_referrer_fee.fields);
1077
- const quoteAfterFee = quoteAmount - quoteSwapFee;
1078
- const memeBalance = BigInt(constantProduct.meme_balance);
1079
- const quoteBalance = BigInt(constantProduct.quote_balance);
1080
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
1081
- const memeOutExpected = memeBalance * quoteAfterFee / (virtualLiquidity + quoteBalance + quoteAfterFee);
1082
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeOutExpected, constantProduct.meme_referrer_fee.fields);
1083
- return memeOutExpected - memeSwapFee;
1084
- }
1085
- MemezPump.pump = pump;
1086
- function dump(pumpState, memeAmount) {
1087
- const constantProduct = pumpState.constant_product.fields;
1088
- const memeSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.meme_swap_fee, memeAmount, constantProduct.meme_referrer_fee.fields);
1089
- const inputAmount = memeAmount - memeSwapFee;
1090
- const memeBalance = BigInt(constantProduct.meme_balance);
1091
- const quoteBalance = BigInt(constantProduct.quote_balance);
1092
- const virtualLiquidity = BigInt(constantProduct.virtual_liquidity);
1093
- const burnBps = BlastFunPackage.MemezBurner.calculate(constantProduct.burner.fields, quoteBalance);
1094
- const burnAmount = package_Bps.calcUp(burnBps, inputAmount);
1095
- const inputAmountAfterFee = inputAmount - (package_Bps.value(burnBps) !== BigInt(0) ? burnAmount : BigInt(0));
1096
- let quoteOutBeforeFee = (virtualLiquidity + quoteBalance) * inputAmountAfterFee / (memeBalance + inputAmountAfterFee);
1097
- if (quoteOutBeforeFee > quoteBalance) {
1098
- quoteOutBeforeFee = quoteBalance;
1099
- }
1100
- const quoteSwapFee = BlastFunPackage.MemezFees.takeWithDiscount(constantProduct.quote_swap_fee, quoteOutBeforeFee, constantProduct.quote_referrer_fee.fields);
1101
- return quoteOutBeforeFee - quoteSwapFee;
1102
- }
1103
- MemezPump.dump = dump;
1104
- })(BlastFunPackage.MemezPump || (BlastFunPackage.MemezPump = {}));
1105
- })(package_BlastFunPackage || (package_BlastFunPackage = {}));
1106
- var package_MathUtils, package_Bps, package_BlastFunPackage;
1107
-
1108
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/custom-calculation.ts
1109
-
1110
-
1111
- (function(BlastFunCustomCalculation) {
1112
- async function getCurveAmountAfterBuy(params, suiClient) {
1113
- let { suiAmount, poolId, frontendFee } = params;
1114
- const memezFun = await getMoveObjectContent(suiClient, poolId);
1115
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(suiClient, memezFun);
1116
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1117
- return package_BlastFunPackage.MemezPump.pump(pumpState, suiAmount);
1118
- }
1119
- BlastFunCustomCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1120
- async function getSuiAmountAfterSell(params, suiClient) {
1121
- const { curveAmount, poolId, frontendFee } = params;
1122
- const memezFun = await getMoveObjectContent(suiClient, poolId);
1123
- const pumpState = await package_BlastFunPackage.MemezPump.getPumpState(suiClient, memezFun);
1124
- const suiAmount = package_BlastFunPackage.MemezPump.dump(pumpState, curveAmount);
1125
- return getAmountAfterFee(suiAmount, frontendFee);
1126
- }
1127
- BlastFunCustomCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1128
- })(custom_calculation_BlastFunCustomCalculation || (custom_calculation_BlastFunCustomCalculation = {}));
1129
- var custom_calculation_BlastFunCustomCalculation;
1130
-
1131
- ;// CONCATENATED MODULE: ./src/constant/sui.ts
1132
- const SUI_TYPE = "0x2::sui::SUI";
1133
- const SUI_FULL_TYPE = "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";
1134
- const USDC_TOKEN_TYPE = "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN";
1135
- const NATIVE_USDC_TOKEN_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
1136
- const SUI_METADATA_OBJECT_ID = "0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3";
1137
- const CLOCK_OBJECT_ID = "0x0000000000000000000000000000000000000000000000000000000000000006";
1138
- function isSuiCoinType(coinType) {
1139
- return coinType === SUI_TYPE || coinType === SUI_FULL_TYPE;
1140
- }
1141
-
1142
- ;// CONCATENATED MODULE: external "@mysten/sui/utils"
1143
- const utils_namespaceObject = require("@mysten/sui/utils");
1144
- ;// CONCATENATED MODULE: ./src/libs/getCoinOjectIdsByAmount.ts
1145
- const orderByKey = (array, key, sortBy)=>{
1146
- if (!array?.length) {
1147
- return;
1148
- }
1149
- let swapped;
1150
- do {
1151
- swapped = false;
1152
- for(let i = 0; i < array.length - 1; i++){
1153
- const a = BigInt(array[i][key]);
1154
- const b = BigInt(array[i + 1][key]);
1155
- if (sortBy === "desc" ? a < b : a > b) {
1156
- const temp = array[i];
1157
- array[i] = array[i + 1];
1158
- array[i + 1] = temp;
1159
- swapped = true;
1160
- }
1161
- }
1162
- }while (swapped);
1163
- return array;
1164
- };
1165
- const getCoinObjectIdsByAmount = async (suiClient, address, amount, coinType)=>{
1166
- let coinBalances = [];
1167
- let hasNextPage = true;
1168
- let nextCursor;
1169
- while(hasNextPage){
1170
- try {
1171
- const coins = await suiClient.getCoins({
1172
- owner: address,
1173
- coinType,
1174
- cursor: nextCursor
1175
- });
1176
- coinBalances = [
1177
- ...coinBalances,
1178
- ...coins.data
1179
- ];
1180
- hasNextPage = coins.hasNextPage;
1181
- nextCursor = coins.nextCursor;
1182
- } catch (error) {
1183
- console.error("Error fetching data:", error);
1184
- hasNextPage = false;
1185
- }
1186
- }
1187
- // sort coin balance before get object id
1188
- const coinObj = orderByKey(coinBalances.map((item)=>{
1189
- return {
1190
- ...item,
1191
- balance: item.balance
1192
- };
1193
- }), "balance", "desc") ?? [];
1194
- let balance = "0";
1195
- const objectIds = [];
1196
- const objectCoins = [];
1197
- for (const coin of coinObj){
1198
- balance = (BigInt(coin.balance) + BigInt(balance)).toString(10);
1199
- objectIds.push(coin.coinObjectId);
1200
- objectCoins.push(coin);
1201
- if (BigInt(balance) >= BigInt(amount)) {
1202
- break;
1203
- }
1204
- }
1205
- return {
1206
- objectIds,
1207
- balance,
1208
- objectCoins
1209
- };
1210
- };
1211
-
1212
- ;// CONCATENATED MODULE: ./src/libs/getSplitCoinForTx.ts
1213
-
1214
-
1215
-
1216
-
1217
- async function getSplitCoinForTx(params, suiClient) {
1218
- const { account, amount, splits, coinType, inheritTx, inspecTransaction, isSponsored = false } = params;
1219
- const tx = inheritTx ?? new transactions_namespaceObject.Transaction();
1220
- const { objectIds } = await getCoinObjectIdsByAmount(suiClient, account, amount, coinType);
1221
- const coinObjectId = objectIds[0];
1222
- if ((0,utils_namespaceObject.normalizeStructTag)(coinType) === (0,utils_namespaceObject.normalizeStructTag)(SUI_FULL_TYPE) && !isSponsored) {
1223
- let coin;
1224
- if (inspecTransaction) {
1225
- if (objectIds.length > 1) {
1226
- tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
1227
- }
1228
- coin = tx.splitCoins(tx.object(coinObjectId), splits);
1229
- } else {
1230
- coin = tx.splitCoins(tx.gas, splits);
1231
- }
1232
- return {
1233
- tx,
1234
- coinData: coin
1235
- };
1236
- }
1237
- if (objectIds.length > 1) {
1238
- tx.mergeCoins(tx.object(coinObjectId), objectIds.slice(1).map((item)=>tx.object(item)));
1239
- }
1240
- // split correct amount to swap
1241
- const coinData = tx.splitCoins(tx.object(coinObjectId), splits);
1242
- return {
1243
- tx,
1244
- coinData
1245
- };
1246
- }
1247
-
1248
- ;// CONCATENATED MODULE: ./src/constant/bluefin.ts
1249
- const BLUEFIN_PACKAGE_ID = "0x62412b7268c35f3808336aee57a52836501f40b8ba5d936f8ad275e672befd04";
1250
-
1251
- ;// CONCATENATED MODULE: ./src/libs/bluefin.ts
1252
-
1253
- (function(BluefinTx) {
1254
- function transferOrDestroyZeroCoin(tx, coinType, coin, address) {
1255
- tx.moveCall({
1256
- target: `${BLUEFIN_PACKAGE_ID}::utils::transfer_or_destroy`,
1257
- typeArguments: [
1258
- coinType
1259
- ],
1260
- arguments: [
1261
- coin,
1262
- tx.pure.address(address)
1263
- ]
1264
- });
1265
- }
1266
- BluefinTx.transferOrDestroyZeroCoin = transferOrDestroyZeroCoin;
1267
- })(bluefin_BluefinTx || (bluefin_BluefinTx = {}));
1268
- var bluefin_BluefinTx;
1269
-
1270
- ;// CONCATENATED MODULE: ./src/bonding-curve/common/transaction.ts
1271
-
1272
-
1273
-
1274
-
1275
- async function splitSuiCoinAfterFeeFromBuyTx(params, suiClient) {
1276
- const { inputAmount, accountAddress, frontendFee, frontendFeeRecipient, extendTx, isSponsored } = params;
1277
- tiny_invariant_default()(params.inCoinType === SUI_FULL_TYPE || params.inCoinType === SUI_TYPE, "Input must be SUI");
1278
- const { tx: _tx, coinIn } = extendTx || {};
1279
- const splitSui = getSplitCoinsAfterFee(inputAmount, frontendFee || "0");
1280
- const tx = _tx || new transactions_namespaceObject.Transaction();
1281
- let coinData;
1282
- if (coinIn) {
1283
- // Must be SUI
1284
- coinData = tx.splitCoins(coinIn, splitSui);
1285
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, coinIn, accountAddress);
1286
- } else {
1287
- const { coinData: _data } = await getSplitCoinForTx({
1288
- account: accountAddress,
1289
- amount: inputAmount,
1290
- splits: splitSui,
1291
- coinType: SUI_FULL_TYPE,
1292
- inheritTx: tx,
1293
- isSponsored: isSponsored || false
1294
- }, suiClient);
1295
- coinData = _data;
1296
- }
1297
- let inputSuiCoin;
1298
- if (frontendFee && frontendFeeRecipient) {
1299
- const [_inputSuiCoin, frontendFeeCoin] = coinData;
1300
- inputSuiCoin = _inputSuiCoin;
1301
- tx.transferObjects([
1302
- frontendFeeCoin
1303
- ], tx.pure.address(frontendFeeRecipient || accountAddress));
1304
- } else {
1305
- [inputSuiCoin] = coinData;
1306
- }
1307
- return {
1308
- tx,
1309
- coinOut: inputSuiCoin
1310
- };
1311
- }
1312
- async function splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin) {
1313
- tiny_invariant_default()(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1314
- if (Number(params.frontendFee || 0) <= 0) {
1315
- return {
1316
- tx,
1317
- coinOut: suiCoin
1318
- };
1319
- }
1320
- const suiCoinValue = tx.moveCall({
1321
- target: `0x2::coin::value`,
1322
- typeArguments: [
1323
- params.outCoinType
1324
- ],
1325
- arguments: [
1326
- suiCoin
1327
- ]
1328
- });
1329
- const suiCoinFeeValue = tx.moveCall({
1330
- target: `${BLUEFIN_PACKAGE_ID}::math::mul_div_u64`,
1331
- typeArguments: [],
1332
- arguments: [
1333
- suiCoinValue,
1334
- tx.pure.u64(BigInt(Number(params.frontendFee || "0") * /* inlined export .BASE_BPS */ (10000))),
1335
- tx.pure.u64(BigInt(/* inlined export .BASE_BPS */ (10000)))
1336
- ]
1337
- });
1338
- const suiCoinFee = tx.moveCall({
1339
- target: `0x2::coin::split`,
1340
- typeArguments: [
1341
- params.outCoinType
1342
- ],
1343
- arguments: [
1344
- suiCoin,
1345
- suiCoinFeeValue
1346
- ]
1347
- });
1348
- tx.transferObjects([
1349
- suiCoinFee
1350
- ], tx.pure.address(params.frontendFeeRecipient || params.accountAddress));
1351
- return {
1352
- tx,
1353
- coinOut: suiCoin
1354
- };
1355
- }
1356
-
1357
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/custom-transaction.ts
1358
-
1359
-
1360
-
1361
-
1362
-
1363
-
1364
-
1365
- (function(BlastFunCustomTransaction) {
1366
- async function getAllowedVersions(_tx) {
1367
- const tx = _tx || new transactions_namespaceObject.Transaction();
1368
- return tx.moveCall({
1369
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_allowed_versions::get_allowed_versions`,
1370
- arguments: [
1371
- tx.object(constants_BlastFunConstants.MEMEZ_AV_OBJECT_ID)
1372
- ],
1373
- typeArguments: []
1374
- });
1375
- }
1376
- BlastFunCustomTransaction.getAllowedVersions = getAllowedVersions;
1377
- async function buildBuyTx(params, suiClient) {
1378
- tiny_invariant_default()(!await package_BlastFunPackage.MemezFun.isSniperProtectedMemezFun(suiClient, params.poolId), "This coin is a sniper protected coin, please use the Blast Fun website to trade it.");
1379
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
1380
- tiny_invariant_default()(suiCoinIn, "Coin out is required");
1381
- const curveCoin = tx.moveCall({
1382
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::pump`,
1383
- typeArguments: [
1384
- params.outCoinType,
1385
- SUI_FULL_TYPE
1386
- ],
1387
- arguments: [
1388
- tx.object(params.poolId),
1389
- suiCoinIn,
1390
- tx.pure.vector("address", []),
1391
- tx.pure.vector("vector<u8>", []),
1392
- tx.pure.u64(params.minAmountOut),
1393
- await getAllowedVersions(tx)
1394
- ]
1395
- });
1396
- return {
1397
- tx,
1398
- coinOut: curveCoin
1399
- };
1400
- }
1401
- BlastFunCustomTransaction.buildBuyTx = buildBuyTx;
1402
- async function buildSellTx(params, suiClient) {
1403
- tiny_invariant_default()(params.outCoinType === SUI_FULL_TYPE || params.outCoinType === SUI_TYPE, "Output must be SUI");
1404
- const memezFun = await getMoveObjectContent(suiClient, params.poolId);
1405
- const { tx, coinData } = await getSplitCoinForTx({
1406
- amount: params.inputAmount,
1407
- coinType: params.inCoinType,
1408
- inheritTx: params.extendTx?.tx,
1409
- account: params.accountAddress,
1410
- splits: [
1411
- params.inputAmount
1412
- ]
1413
- }, suiClient);
1414
- const [inputCoin] = coinData;
1415
- const [suiCoin] = tx.moveCall({
1416
- target: `${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::dump`,
1417
- typeArguments: [
1418
- params.inCoinType,
1419
- params.outCoinType
1420
- ],
1421
- arguments: [
1422
- tx.object(params.poolId),
1423
- tx.object(memezFun.ipx_meme_coin_treasury),
1424
- inputCoin,
1425
- tx.pure.vector("address", []),
1426
- tx.pure.u64(params.minAmountOut),
1427
- await getAllowedVersions(tx)
1428
- ]
1429
- });
1430
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
1431
- }
1432
- BlastFunCustomTransaction.buildSellTx = buildSellTx;
1433
- })(custom_transaction_BlastFunCustomTransaction || (custom_transaction_BlastFunCustomTransaction = {}));
1434
- var custom_transaction_BlastFunCustomTransaction;
1435
-
1436
- ;// CONCATENATED MODULE: external "@interest-protocol/memez-fun-sdk"
1437
- const memez_fun_sdk_namespaceObject = require("@interest-protocol/memez-fun-sdk");
1438
- ;// CONCATENATED MODULE: external "@interest-protocol/sui-core-sdk"
1439
- const sui_core_sdk_namespaceObject = require("@interest-protocol/sui-core-sdk");
1440
- ;// CONCATENATED MODULE: external "@mysten/sui/client"
1441
- const client_namespaceObject = require("@mysten/sui/client");
1442
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/meme-pump-sdk.ts
1443
-
1444
-
1445
-
1446
- const payload = {
1447
- network: sui_core_sdk_namespaceObject.Network.MAINNET,
1448
- fullNodeUrl: (0,client_namespaceObject.getFullnodeUrl)("mainnet")
1449
- };
1450
- const memezPump = new memez_fun_sdk_namespaceObject.MemezPumpSDK(payload);
1451
- function getMemezPumpSDK() {
1452
- return memezPump;
1453
- }
1454
-
1455
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/sdk-calculation.ts
1456
-
1457
-
1458
- (function(BlastFunSDKCalculation) {
1459
- async function getCurveAmountAfterBuy(params) {
1460
- let { suiAmount, poolId, frontendFee } = params;
1461
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1462
- const { memeAmountOut } = await getMemezPumpSDK().quotePump({
1463
- pool: poolId,
1464
- amount: suiAmount
1465
- });
1466
- return memeAmountOut;
1467
- }
1468
- BlastFunSDKCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1469
- async function getSuiAmountAfterSell(params) {
1470
- const { curveAmount, poolId, frontendFee } = params;
1471
- const { quoteAmountOut } = await getMemezPumpSDK().quoteDump({
1472
- pool: poolId,
1473
- amount: curveAmount
1474
- });
1475
- return getAmountAfterFee(quoteAmountOut, frontendFee);
1476
- }
1477
- BlastFunSDKCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1478
- })(sdk_calculation_BlastFunSDKCalculation || (sdk_calculation_BlastFunSDKCalculation = {}));
1479
- var sdk_calculation_BlastFunSDKCalculation;
1480
-
1481
- ;// CONCATENATED MODULE: ./src/libs/addGasFee.ts
1482
-
1483
-
1484
-
1485
- async function addGasFee(params, suiClient) {
1486
- const { inheritTx, sender, feeAmount, suiInputAmount } = params;
1487
- const tx = inheritTx || new transactions_namespaceObject.Transaction();
1488
- tx.setGasBudget(feeAmount);
1489
- const { objectCoins } = await getCoinObjectIdsByAmount(suiClient, sender, (BigInt(suiInputAmount || "0") + feeAmount).toString(), SUI_FULL_TYPE);
1490
- tx.setGasPayment(objectCoins.map((c)=>({
1491
- objectId: c.coinObjectId,
1492
- version: c.version,
1493
- digest: c.digest
1494
- })));
1495
- return tx;
1496
- }
1497
-
1498
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/sdk-transaction.ts
1499
-
1500
-
1501
-
1502
-
1503
-
1504
-
1505
-
1506
-
1507
- (function(BlastFunSDKTransaction) {
1508
- async function buildBuyTx(params, suiClient) {
1509
- const { tx, coinOut: suiCoinIn } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
1510
- tiny_invariant_default()(suiCoinIn, "Coin out is required");
1511
- const { memeCoin, tx: tx2 } = await getMemezPumpSDK().pump({
1512
- pool: params.poolId,
1513
- quoteCoin: suiCoinIn,
1514
- minAmountOut: params.minAmountOut,
1515
- tx
1516
- });
1517
- return {
1518
- tx: tx2,
1519
- coinOut: memeCoin
1520
- };
1521
- }
1522
- BlastFunSDKTransaction.buildBuyTx = buildBuyTx;
1523
- async function buildSellTx(params, suiClient) {
1524
- tiny_invariant_default()(isSuiCoinType(params.outCoinType), "Output must be SUI");
1525
- const { tx, coinData } = await getSplitCoinForTx({
1526
- amount: params.inputAmount,
1527
- coinType: params.inCoinType,
1528
- inheritTx: params.extendTx?.tx,
1529
- account: params.accountAddress,
1530
- splits: [
1531
- params.inputAmount
1532
- ]
1533
- }, suiClient);
1534
- const [inputCoin] = coinData;
1535
- const { quoteCoin, tx: tx2 } = await getMemezPumpSDK().dump({
1536
- pool: params.poolId,
1537
- memeCoin: inputCoin,
1538
- tx,
1539
- minAmountOut: params.minAmountOut
1540
- });
1541
- return await splitSuiCoinAfterFeeFromSellTx(tx2, params, quoteCoin);
1542
- }
1543
- BlastFunSDKTransaction.buildSellTx = buildSellTx;
1544
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1545
- tiny_invariant_default()(isSuiCoinType(coinInType), "coinInType must be SUI for buy transaction");
1546
- tiny_invariant_default()(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1547
- tiny_invariant_default()(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1548
- tiny_invariant_default()(coinInAmount > 0, "coinInAmount must be greater than 0");
1549
- const inputAmount = coinInAmount;
1550
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({
1551
- poolId: poolId,
1552
- suiAmount: inputAmount,
1553
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined
1554
- });
1555
- const minAmountOut = BigInt(new (external_bignumber_js_default())(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1556
- let { tx, coinOut } = await buildBuyTx({
1557
- accountAddress: walletAddress,
1558
- inCoinType: coinInType,
1559
- outCoinType: coinOutType,
1560
- inputAmount: inputAmount.toString(),
1561
- minAmountOut: minAmountOut.toString(),
1562
- poolId: poolId,
1563
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined,
1564
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : undefined,
1565
- extendTx: undefined,
1566
- isSponsored: false
1567
- }, suiClient);
1568
- tiny_invariant_default()(coinOut, "Coin out is required");
1569
- tx.transferObjects([
1570
- coinOut
1571
- ], tx.pure.address(walletAddress));
1572
- tx.setSender(walletAddress);
1573
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1574
- tx = await addGasFee({
1575
- inheritTx: tx,
1576
- sender: walletAddress,
1577
- feeAmount,
1578
- suiInputAmount: inputAmount
1579
- }, suiClient);
1580
- return tx.build({
1581
- client: suiClient
1582
- });
1583
- }
1584
- BlastFunSDKTransaction.getBuyTransaction = getBuyTransaction;
1585
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1586
- tiny_invariant_default()(isSuiCoinType(coinOutType), "coinOutType must be SUI for sell transaction");
1587
- tiny_invariant_default()(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1588
- tiny_invariant_default()(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1589
- tiny_invariant_default()(coinInAmount > 0, "coinInAmount must be greater than 0");
1590
- const inputAmount = coinInAmount;
1591
- const outputAmount = await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({
1592
- poolId: poolId,
1593
- curveAmount: inputAmount,
1594
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined
1595
- });
1596
- const minAmountOut = BigInt(new (external_bignumber_js_default())(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1597
- let { tx, coinOut } = await buildSellTx({
1598
- accountAddress: walletAddress,
1599
- inCoinType: coinInType,
1600
- outCoinType: coinOutType,
1601
- inputAmount: inputAmount.toString(),
1602
- minAmountOut: minAmountOut.toString(),
1603
- poolId: poolId,
1604
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined,
1605
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : undefined,
1606
- extendTx: undefined,
1607
- isSponsored: false
1608
- }, suiClient);
1609
- tiny_invariant_default()(coinOut, "Coin out is required");
1610
- tx.transferObjects([
1611
- coinOut
1612
- ], tx.pure.address(walletAddress));
1613
- tx.setSender(walletAddress);
1614
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1615
- tx = await addGasFee({
1616
- inheritTx: tx,
1617
- sender: walletAddress,
1618
- feeAmount
1619
- }, suiClient);
1620
- return tx.build({
1621
- client: suiClient
1622
- });
1623
- }
1624
- BlastFunSDKTransaction.getSellTransaction = getSellTransaction;
1625
- })(sdk_transaction_BlastFunSDKTransaction || (sdk_transaction_BlastFunSDKTransaction = {}));
1626
- var sdk_transaction_BlastFunSDKTransaction;
1627
-
1628
- ;// CONCATENATED MODULE: ./src/bonding-curve/blast-fun/index.ts
1629
-
1630
-
1631
-
1632
-
1633
-
1634
-
1635
-
1636
-
1637
- ;// CONCATENATED MODULE: ./src/bonding-curve/common/types.ts
1638
- var types_SupportedBondingCurve = /*#__PURE__*/ function(SupportedBondingCurve) {
1639
- SupportedBondingCurve["BLAST_FUN"] = "BLAST_FUN";
1640
- SupportedBondingCurve["MOONBAGS"] = "MOONBAGS";
1641
- return SupportedBondingCurve;
1642
- }({});
1643
-
1644
- ;// CONCATENATED MODULE: ./src/bonding-curve/common/index.ts
1645
-
1646
-
1647
-
1648
- ;// CONCATENATED MODULE: ./src/bonding-curve/moonbags/constants.ts
1649
- (function(MoonbagsConstants) {
1650
- MoonbagsConstants.PACKAGE_ID = "0xb8df325010942634a4afb3db3901ee215546af43a4ec4af781e7213b0bba7290";
1651
- MoonbagsConstants.CONFIG_OBJECT_ID = "0x74aecf86067c6913960ba4925333aefd2b1f929cafca7e21fd55a8f244b70499";
1652
- MoonbagsConstants.LOCK_CONFIG_OBJECT_ID = "0xfb09822d9808980abd04c51321adb850701f5f55535c6206658ef4d910c3e9be";
1653
- MoonbagsConstants.BURN_MANAGER_OBJECT_ID = "0x1d94aa32518d0cb00f9de6ed60d450c9a2090761f326752ffad06b2e9404f845";
1654
- MoonbagsConstants.POOLS_OBJECT_ID = "0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0";
1655
- MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID = "0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f";
1656
- MoonbagsConstants.FEE_DENOMINATOR = BigInt(10000);
1657
- })(constants_MoonbagsConstants || (constants_MoonbagsConstants = {}));
1658
- var constants_MoonbagsConstants;
1659
-
1660
- ;// CONCATENATED MODULE: ./src/bonding-curve/moonbags/package.ts
1661
-
1662
-
1663
- (function(MoonbagsPackage) {
1664
- (function(Curves) {
1665
- function calculateAddLiquidityCost(tokenIn, tokenReserve, tokenAmount) {
1666
- const availableReserve = tokenReserve - tokenAmount;
1667
- const numerator = tokenIn * tokenReserve;
1668
- const fraction = numerator / availableReserve;
1669
- return fraction - tokenIn;
1670
- }
1671
- Curves.calculateAddLiquidityCost = calculateAddLiquidityCost;
1672
- function calculateRemoveLiquidityReturn(tokenIn, tokenReserve, tokenRemoved) {
1673
- const denominator = tokenIn + tokenRemoved;
1674
- const fraction = tokenIn * tokenReserve / denominator;
1675
- return tokenReserve - fraction;
1676
- }
1677
- Curves.calculateRemoveLiquidityReturn = calculateRemoveLiquidityReturn;
1678
- function calculateTokenAmountReceived(tokenIn, tokenReserve, tokenOutReserve) {
1679
- const denominator = tokenIn + tokenOutReserve;
1680
- const fraction = tokenIn * tokenReserve / denominator;
1681
- return tokenReserve - fraction;
1682
- }
1683
- Curves.calculateTokenAmountReceived = calculateTokenAmountReceived;
1684
- })(MoonbagsPackage.Curves || (MoonbagsPackage.Curves = {}));
1685
- (function(Moonbags) {
1686
- async function getDynamicVirtualTokenReserves(suiClient, poolId) {
1687
- const result = await suiClient.getDynamicFieldObject({
1688
- parentId: poolId,
1689
- name: {
1690
- type: "vector<u8>",
1691
- value: "virtual_token_reserves"
1692
- }
1693
- });
1694
- if (!result.data) {
1695
- return undefined;
1696
- }
1697
- return BigInt(result.data.content.fields.value);
1698
- }
1699
- Moonbags.getDynamicVirtualTokenReserves = getDynamicVirtualTokenReserves;
1700
- function buyExactInReturnsWithLock(params) {
1701
- const { inputAmount, amountIn, pool, config, dynamicVirtualTokenReserves } = params;
1702
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1703
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1704
- const remainTokenReserves = BigInt(pool.remain_token_reserves.fields.balance);
1705
- const expectedOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualSuiReserves, virtualTokenReserves, amountIn);
1706
- const availableOut = virtualTokenReserves - (dynamicVirtualTokenReserves || remainTokenReserves);
1707
- let finalOut = expectedOut;
1708
- let usedSui = amountIn;
1709
- if (expectedOut > availableOut) {
1710
- finalOut = availableOut;
1711
- usedSui = MoonbagsPackage.Curves.calculateAddLiquidityCost(virtualSuiReserves, virtualTokenReserves, availableOut) + BigInt(1);
1712
- }
1713
- const feeAmount = usedSui * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1714
- tiny_invariant_default()(inputAmount >= usedSui + feeAmount, "Input amount is less than used SUI + fee");
1715
- return {
1716
- receivedCurve: finalOut,
1717
- receivedSui: inputAmount - usedSui - feeAmount
1718
- };
1719
- }
1720
- Moonbags.buyExactInReturnsWithLock = buyExactInReturnsWithLock;
1721
- function sellReturns(params) {
1722
- const { amountIn, pool, config } = params;
1723
- const virtualSuiReserves = BigInt(pool.virtual_sui_reserves);
1724
- const virtualTokenReserves = BigInt(pool.virtual_token_reserves);
1725
- const realSuiReserves = BigInt(pool.real_sui_reserves.fields.balance);
1726
- let rawSuiOut = MoonbagsPackage.Curves.calculateRemoveLiquidityReturn(virtualTokenReserves, virtualSuiReserves, amountIn);
1727
- if (rawSuiOut > realSuiReserves) {
1728
- rawSuiOut = realSuiReserves;
1729
- }
1730
- const feeAmount = rawSuiOut * BigInt(config.platform_fee) / constants_MoonbagsConstants.FEE_DENOMINATOR;
1731
- const finalSuiOut = rawSuiOut - feeAmount;
1732
- return {
1733
- receivedCurve: BigInt(0),
1734
- receivedSui: finalSuiOut
1735
- };
1736
- }
1737
- Moonbags.sellReturns = sellReturns;
1738
- })(MoonbagsPackage.Moonbags || (MoonbagsPackage.Moonbags = {}));
1739
- })(package_MoonbagsPackage || (package_MoonbagsPackage = {}));
1740
- var package_MoonbagsPackage;
1741
-
1742
- ;// CONCATENATED MODULE: ./src/bonding-curve/moonbags/calculation.ts
1743
-
1744
-
1745
-
1746
- (function(MoonbagsCalculation) {
1747
- async function getCurveAmountAfterBuy(params, suiClient) {
1748
- let { suiAmount, poolId, frontendFee } = params;
1749
- const [poolMoveStruct, configMoveStruct, dynamicVirtualTokenReserves] = await Promise.all([
1750
- getMoveObjectContent(suiClient, poolId),
1751
- getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1752
- package_MoonbagsPackage.Moonbags.getDynamicVirtualTokenReserves(suiClient, poolId)
1753
- ]);
1754
- const pool = poolMoveStruct;
1755
- const config = configMoveStruct;
1756
- if (frontendFee !== undefined) {
1757
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1758
- }
1759
- const usedSui = suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1760
- const { receivedCurve } = package_MoonbagsPackage.Moonbags.buyExactInReturnsWithLock({
1761
- inputAmount: suiAmount,
1762
- amountIn: usedSui,
1763
- pool,
1764
- config,
1765
- dynamicVirtualTokenReserves
1766
- });
1767
- return receivedCurve;
1768
- }
1769
- MoonbagsCalculation.getCurveAmountAfterBuy = getCurveAmountAfterBuy;
1770
- async function getSuiAmountAfterSell(params, suiClient) {
1771
- const { curveAmount, poolId, frontendFee } = params;
1772
- const [poolMoveStruct, configMoveStruct] = await Promise.all([
1773
- getMoveObjectContent(suiClient, poolId),
1774
- getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID)
1775
- ]);
1776
- const pool = poolMoveStruct;
1777
- const config = configMoveStruct;
1778
- const { receivedSui } = package_MoonbagsPackage.Moonbags.sellReturns({
1779
- amountIn: curveAmount,
1780
- pool,
1781
- config
1782
- });
1783
- if (frontendFee !== undefined) {
1784
- return getAmountAfterFee(receivedSui, frontendFee);
1785
- }
1786
- return receivedSui;
1787
- }
1788
- MoonbagsCalculation.getSuiAmountAfterSell = getSuiAmountAfterSell;
1789
- async function getUsedSuiForTx(params, suiClient) {
1790
- let { suiAmount, frontendFee } = params;
1791
- const configMoveStruct = await getMoveObjectContent(suiClient, constants_MoonbagsConstants.CONFIG_OBJECT_ID);
1792
- const config = configMoveStruct;
1793
- if (frontendFee !== undefined) {
1794
- suiAmount = getAmountAfterFee(suiAmount, frontendFee);
1795
- }
1796
- return suiAmount * constants_MoonbagsConstants.FEE_DENOMINATOR / (constants_MoonbagsConstants.FEE_DENOMINATOR + BigInt(config.platform_fee));
1797
- }
1798
- MoonbagsCalculation.getUsedSuiForTx = getUsedSuiForTx;
1799
- })(calculation_MoonbagsCalculation || (calculation_MoonbagsCalculation = {}));
1800
- var calculation_MoonbagsCalculation;
1801
-
1802
- ;// CONCATENATED MODULE: ./src/bonding-curve/moonbags/transaction.ts
1803
-
1804
-
1805
-
1806
-
1807
-
1808
-
1809
-
1810
-
1811
- (function(MoonbagsTransaction) {
1812
- async function buildBuyTx(params, suiClient) {
1813
- const { tx, coinOut } = await splitSuiCoinAfterFeeFromBuyTx(params, suiClient);
1814
- tiny_invariant_default()(coinOut, "Coin out is required");
1815
- const usedSui = await calculation_MoonbagsCalculation.getUsedSuiForTx({
1816
- suiAmount: BigInt(params.inputAmount),
1817
- frontendFee: params.frontendFee
1818
- }, suiClient);
1819
- const [suiCoin, curveCoin] = tx.moveCall({
1820
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::buy_exact_in_returns_with_lock`,
1821
- typeArguments: [
1822
- params.outCoinType
1823
- ],
1824
- arguments: [
1825
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1826
- tx.object(constants_MoonbagsConstants.LOCK_CONFIG_OBJECT_ID),
1827
- coinOut,
1828
- tx.pure.u64(usedSui),
1829
- tx.pure.u64(params.minAmountOut),
1830
- tx.object(constants_MoonbagsConstants.BURN_MANAGER_OBJECT_ID),
1831
- tx.object(constants_MoonbagsConstants.POOLS_OBJECT_ID),
1832
- tx.object(constants_MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID),
1833
- tx.object(SUI_METADATA_OBJECT_ID),
1834
- tx.object(CLOCK_OBJECT_ID)
1835
- ]
1836
- });
1837
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, SUI_FULL_TYPE, suiCoin, params.accountAddress);
1838
- return {
1839
- tx,
1840
- coinOut: curveCoin
1841
- };
1842
- }
1843
- MoonbagsTransaction.buildBuyTx = buildBuyTx;
1844
- async function buildSellTx(params, suiClient) {
1845
- tiny_invariant_default()(isSuiCoinType(params.outCoinType), "Output must be SUI");
1846
- const { tx, coinData } = await getSplitCoinForTx({
1847
- amount: params.inputAmount,
1848
- coinType: params.inCoinType,
1849
- inheritTx: params.extendTx?.tx,
1850
- account: params.accountAddress,
1851
- splits: [
1852
- params.inputAmount
1853
- ]
1854
- }, suiClient);
1855
- const [inputCoin] = coinData;
1856
- const [suiCoin, curveCoin] = tx.moveCall({
1857
- target: `${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::sell_returns`,
1858
- typeArguments: [
1859
- params.inCoinType
1860
- ],
1861
- arguments: [
1862
- tx.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),
1863
- inputCoin,
1864
- tx.pure.u64(params.minAmountOut),
1865
- tx.object(CLOCK_OBJECT_ID)
1866
- ]
1867
- });
1868
- bluefin_BluefinTx.transferOrDestroyZeroCoin(tx, params.inCoinType, curveCoin, params.accountAddress);
1869
- return await splitSuiCoinAfterFeeFromSellTx(tx, params, suiCoin);
1870
- }
1871
- MoonbagsTransaction.buildSellTx = buildSellTx;
1872
- async function getBuyTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1873
- tiny_invariant_default()(isSuiCoinType(coinInType), "coinInType must be SUI for buy transaction");
1874
- tiny_invariant_default()(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1875
- tiny_invariant_default()(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1876
- tiny_invariant_default()(coinInAmount > 0, "coinInAmount must be greater than 0");
1877
- const inputAmount = coinInAmount;
1878
- const outputAmount = await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({
1879
- poolId: poolId,
1880
- suiAmount: inputAmount,
1881
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined
1882
- }, suiClient);
1883
- const minAmountOut = BigInt(new (external_bignumber_js_default())(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1884
- let { tx, coinOut } = await buildBuyTx({
1885
- accountAddress: walletAddress,
1886
- inCoinType: coinInType,
1887
- outCoinType: coinOutType,
1888
- inputAmount: inputAmount.toString(),
1889
- minAmountOut: minAmountOut.toString(),
1890
- poolId: poolId,
1891
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined,
1892
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : undefined,
1893
- extendTx: undefined,
1894
- isSponsored: false
1895
- }, suiClient);
1896
- tiny_invariant_default()(coinOut, "Coin out is required");
1897
- tx.transferObjects([
1898
- coinOut
1899
- ], tx.pure.address(walletAddress));
1900
- tx.setSender(walletAddress);
1901
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1902
- tx = await addGasFee({
1903
- inheritTx: tx,
1904
- sender: walletAddress,
1905
- feeAmount,
1906
- suiInputAmount: inputAmount
1907
- }, suiClient);
1908
- return tx.build({
1909
- client: suiClient
1910
- });
1911
- }
1912
- MoonbagsTransaction.getBuyTransaction = getBuyTransaction;
1913
- async function getSellTransaction({ coinInAmount, coinInType, coinOutType, poolId, slippage, walletAddress, tradeFee }, suiClient) {
1914
- tiny_invariant_default()(isSuiCoinType(coinOutType), "coinOutType must be SUI for sell transaction");
1915
- tiny_invariant_default()(coinOutType !== coinInType, "coinOutType must be different from coinInType");
1916
- tiny_invariant_default()(slippage >= 0 && slippage < 1, "slippage must be between 0 (inclusive) and 1 (exclusive)");
1917
- tiny_invariant_default()(coinInAmount > 0, "coinInAmount must be greater than 0");
1918
- const inputAmount = coinInAmount;
1919
- const outputAmount = await calculation_MoonbagsCalculation.getSuiAmountAfterSell({
1920
- poolId: poolId,
1921
- curveAmount: inputAmount,
1922
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined
1923
- }, suiClient);
1924
- const minAmountOut = BigInt(new (external_bignumber_js_default())(outputAmount.toString()).multipliedBy(1 - slippage).toFixed(0, 3));
1925
- let { tx, coinOut } = await buildSellTx({
1926
- accountAddress: walletAddress,
1927
- inCoinType: coinInType,
1928
- outCoinType: coinOutType,
1929
- inputAmount: inputAmount.toString(),
1930
- minAmountOut: minAmountOut.toString(),
1931
- poolId: poolId,
1932
- frontendFee: tradeFee ? tradeFee.tradeFeePercent : undefined,
1933
- frontendFeeRecipient: tradeFee ? tradeFee.tradeFeeRecipientAddress : undefined,
1934
- extendTx: undefined,
1935
- isSponsored: false
1936
- }, suiClient);
1937
- tiny_invariant_default()(coinOut, "Coin out is required");
1938
- tx.transferObjects([
1939
- coinOut
1940
- ], tx.pure.address(walletAddress));
1941
- tx.setSender(walletAddress);
1942
- const feeAmount = await getNeededGasFee(suiClient, tx, walletAddress, 0);
1943
- tx = await addGasFee({
1944
- inheritTx: tx,
1945
- sender: walletAddress,
1946
- feeAmount
1947
- }, suiClient);
1948
- return tx.build({
1949
- client: suiClient
1950
- });
1951
- }
1952
- MoonbagsTransaction.getSellTransaction = getSellTransaction;
1953
- })(transaction_MoonbagsTransaction || (transaction_MoonbagsTransaction = {}));
1954
- var transaction_MoonbagsTransaction;
1955
-
1956
- ;// CONCATENATED MODULE: ./src/bonding-curve/moonbags/index.ts
1957
-
1958
-
1959
-
1960
-
1961
-
1962
- ;// CONCATENATED MODULE: ./src/bonding-curve/index.ts
1963
-
1964
-
1965
-
1966
-
1967
- ;// CONCATENATED MODULE: ./src/constant/index.ts
1968
-
1969
-
1970
-
1971
- ;// CONCATENATED MODULE: ./src/fee/index.ts
1972
-
1973
-
1974
- ;// CONCATENATED MODULE: ./src/libs/math/index.ts
1975
-
1976
-
1977
- ;// CONCATENATED MODULE: ./src/libs/sui-client-adapter.ts
1978
- /**
1979
- * Adapter to make SuiClient v1.38 compatible with libraries expecting v1.34
1980
- * This works around TypeScript type incompatibilities between versions
1981
- */ function adaptSuiClient(client) {
1982
- // Return the client with type assertion to bypass strict type checking
1983
- // The underlying implementation is compatible, just the types differ
1984
- return client;
1985
- }
1986
- /**
1987
- * Adapter to make Transaction v1.38 compatible with libraries expecting v1.34
1988
- * This works around TypeScript type incompatibilities between versions
1989
- */ function adaptTransaction(transaction) {
1990
- // Return the transaction with type assertion to bypass strict type checking
1991
- // The underlying implementation is compatible, just the types differ
1992
- return transaction;
1993
- }
1994
- /**
1995
- * Alternative: Create a proxy that ensures compatibility
1996
- */ function createCompatibleSuiClient(client) {
1997
- // You can add any necessary adaptations here if needed
1998
- return new Proxy(client, {
1999
- get (target, prop) {
2000
- const value = target[prop];
2001
- if (typeof value === "function") {
2002
- return value.bind(target);
2003
- }
2004
- return value;
2005
- }
2006
- });
2007
- }
2008
-
2009
- ;// CONCATENATED MODULE: ./src/libs/index.ts
2010
-
2011
-
2012
-
2013
-
2014
-
2015
-
2016
-
2017
-
2018
- ;// CONCATENATED MODULE: ./src/modules/aggregator-module.ts
2019
-
2020
-
2021
- /**
2022
- * Main aggregator module that provides unified access to multiple DEX aggregators
2023
- * Supports routing trades through Cetus, FlowX, Astros, Aftermath, and 7K Protocol
2024
- */ class AggregatorModule {
2025
- /** Reference to the main Noodles SDK instance */ sdk;
2026
- /** Astros/Navi Protocol aggregator instance */ _astrosAggregator;
2027
- /** Aftermath Finance aggregator instance */ _aftermathAggregator;
2028
- /** 7K Protocol aggregator instance */ _sevenkAggregator;
2029
- /** Cetus Protocol aggregator instance */ _cetusAggregator;
2030
- /** FlowX Finance aggregator instance */ _flowXAggregator;
2031
- /**
2032
- * Creates a new AggregatorModule instance with all supported aggregators
2033
- * @param sdk - The main Noodles SDK instance containing configuration
2034
- */ constructor(sdk){
2035
- this.sdk = sdk;
2036
- this._astrosAggregator = new astros_AstrosAggregator({
2037
- defaultTradeFee: sdk.options.tradeFee,
2038
- astrosApiKey: sdk.options.astrosApiKey
2039
- }, sdk.suiClient);
2040
- this._aftermathAggregator = new aftermath_AftermathAggregator({
2041
- defaultTradeFee: sdk.options.tradeFee,
2042
- aftermathApiKey: sdk.options.aftermathApiKey,
2043
- aftermathApiEndpoint: sdk.options.aftermathApiEndpoint
2044
- }, sdk.suiClient);
2045
- this._sevenkAggregator = new _7k_SevenKAggregator({
2046
- defaultTradeFee: sdk.options.tradeFee,
2047
- sevenKApiKey: sdk.options.sevenKApiKey
2048
- }, sdk.suiClient);
2049
- this._cetusAggregator = new cetus_CetusAggregator({
2050
- defaultTradeFee: sdk.options.tradeFee,
2051
- cetusApiKey: sdk.options.cetusApiKey,
2052
- cetusApiEndpoint: sdk.options.cetusApiEndpoint,
2053
- cetusPartnerId: sdk.options.cetusPartnerId
2054
- }, sdk.suiClient);
2055
- this._flowXAggregator = new flowx_FlowXAggregator({
2056
- defaultTradeFee: sdk.options.tradeFee,
2057
- flowxApiKey: sdk.options.flowxApiKey
2058
- }, sdk.suiClient);
2059
- }
2060
- /** Gets the Astros/Navi Protocol aggregator instance */ get astrosAggregator() {
2061
- return this._astrosAggregator;
2062
- }
2063
- /** Gets the Aftermath Finance aggregator instance */ get aftermathAggregator() {
2064
- return this._aftermathAggregator;
2065
- }
2066
- /** Gets the 7K Protocol aggregator instance */ get sevenkAggregator() {
2067
- return this._sevenkAggregator;
2068
- }
2069
- /** Gets the Cetus Protocol aggregator instance */ get cetusAggregator() {
2070
- return this._cetusAggregator;
2071
- }
2072
- /** Gets the FlowX Finance aggregator instance */ get flowXAggregator() {
2073
- return this._flowXAggregator;
2074
- }
2075
- /**
2076
- * Finds the optimal trade route using the specified aggregator
2077
- * @param aggregator - The aggregator to use for route finding
2078
- * @param params - Trade route parameters including token types and amounts
2079
- * @returns Promise resolving to route response with both standardized and raw data, or null if no route found
2080
- */ async getTradeRoute(aggregator, params) {
2081
- let finalResponse;
2082
- switch(aggregator){
2083
- case common_SupportedAggregator.ASTROS:
2084
- {
2085
- const tradeRouteResponse = await this._astrosAggregator.getTradeRoute(params);
2086
- if (!tradeRouteResponse) {
2087
- return null;
2088
- }
2089
- const finalRoutes = astros_AstrosAggregator.toCommonTradeRoutes(tradeRouteResponse, params.coinInType, params.coinOutType);
2090
- if (!finalRoutes) {
2091
- return null;
2092
- }
2093
- let tradeFeePercent;
2094
- if (params.tradeFee) {
2095
- tradeFeePercent = params.tradeFee.tradeFeePercent;
2096
- } else {
2097
- tradeFeePercent = this.sdk.options.tradeFee.tradeFeePercent;
2098
- }
2099
- /**
2100
- * Astros route amount_out does not consider the trade fee,
2101
- * so we need to deduct the trade fee from the final amount_out
2102
- */ const finalAmountOut = BigInt(new (external_bignumber_js_default())(tradeRouteResponse.amount_out).multipliedBy(1 - tradeFeePercent).toFixed(0, 3));
2103
- finalRoutes.amountOut = finalAmountOut;
2104
- finalResponse = {
2105
- route: finalRoutes,
2106
- aggregatorRoute: tradeRouteResponse
2107
- };
2108
- break;
2109
- }
2110
- case common_SupportedAggregator.AFTERMATH:
2111
- {
2112
- const tradeRouteResponse = await this._aftermathAggregator.getTradeRoute(params);
2113
- if (!tradeRouteResponse) {
2114
- return null;
2115
- }
2116
- const finalRoutes = aftermath_AftermathAggregator.toCommonTradeRoutes(tradeRouteResponse);
2117
- if (!finalRoutes) {
2118
- return null;
2119
- }
2120
- finalResponse = {
2121
- route: finalRoutes,
2122
- aggregatorRoute: tradeRouteResponse
2123
- };
2124
- break;
2125
- }
2126
- case common_SupportedAggregator.SEVENK:
2127
- {
2128
- const tradeRouteResponse = await this._sevenkAggregator.getTradeRoute(params);
2129
- if (!tradeRouteResponse) {
2130
- return null;
2131
- }
2132
- const finalRoutes = _7k_SevenKAggregator.toCommonTradeRoutes(tradeRouteResponse);
2133
- if (!finalRoutes) {
2134
- return null;
2135
- }
2136
- finalResponse = {
2137
- route: finalRoutes,
2138
- aggregatorRoute: tradeRouteResponse
2139
- };
2140
- break;
2141
- }
2142
- case common_SupportedAggregator.CETUS:
2143
- {
2144
- const tradeRouteResponse = await this._cetusAggregator.getTradeRoute(params);
2145
- if (!tradeRouteResponse) {
2146
- return null;
2147
- }
2148
- const finalRoutes = cetus_CetusAggregator.toCommonTradeRoutes(tradeRouteResponse, params.coinInType, params.coinOutType);
2149
- if (!finalRoutes) {
2150
- return null;
2151
- }
2152
- finalResponse = {
2153
- route: finalRoutes,
2154
- aggregatorRoute: tradeRouteResponse
2155
- };
2156
- break;
2157
- }
2158
- case common_SupportedAggregator.FLOWX:
2159
- {
2160
- const tradeRouteResponse = await this._flowXAggregator.getTradeRoute(params);
2161
- if (!tradeRouteResponse) {
2162
- return null;
2163
- }
2164
- const finalRoutes = flowx_FlowXAggregator.toCommonTradeRoutes(tradeRouteResponse);
2165
- if (!finalRoutes) {
2166
- return null;
2167
- }
2168
- finalResponse = {
2169
- route: finalRoutes,
2170
- aggregatorRoute: tradeRouteResponse
2171
- };
2172
- break;
2173
- }
2174
- }
2175
- return finalResponse;
2176
- }
2177
- /**
2178
- * Builds a transaction from an existing trade route
2179
- * @param aggregator - The aggregator that generated the route
2180
- * @param params - Transaction parameters including wallet address, route, and slippage
2181
- * @returns Promise resolving to built transaction bytes ready for signing and execution
2182
- */ async getTransactionByRoute(aggregator, params) {
2183
- switch(aggregator){
2184
- case common_SupportedAggregator.ASTROS:
2185
- {
2186
- return this._astrosAggregator.getTransaction({
2187
- walletAddress: params.walletAddress,
2188
- completeRoute: params.completeRoute,
2189
- slippage: params.slippage,
2190
- tradeFee: params.tradeFee
2191
- });
2192
- }
2193
- case common_SupportedAggregator.AFTERMATH:
2194
- {
2195
- return this._aftermathAggregator.getTransaction({
2196
- walletAddress: params.walletAddress,
2197
- completeRoute: params.completeRoute,
2198
- slippage: params.slippage
2199
- });
2200
- }
2201
- case common_SupportedAggregator.SEVENK:
2202
- {
2203
- return this._sevenkAggregator.getTransaction({
2204
- walletAddress: params.walletAddress,
2205
- completeRoute: params.completeRoute,
2206
- slippage: params.slippage,
2207
- tradeFee: params.tradeFee
2208
- });
2209
- }
2210
- case common_SupportedAggregator.CETUS:
2211
- {
2212
- return this._cetusAggregator.getTransaction({
2213
- walletAddress: params.walletAddress,
2214
- completeRoute: params.completeRoute,
2215
- slippage: params.slippage,
2216
- tradeFee: params.tradeFee
2217
- });
2218
- }
2219
- case common_SupportedAggregator.FLOWX:
2220
- {
2221
- return this._flowXAggregator.getTransaction({
2222
- walletAddress: params.walletAddress,
2223
- completeRoute: params.completeRoute,
2224
- slippage: params.slippage,
2225
- tradeFee: params.tradeFee
2226
- });
2227
- }
2228
- }
2229
- }
2230
- /**
2231
- * Combines route finding and transaction building into a single operation
2232
- * This is a convenience method that calls getTradeRoute followed by getTransactionByRoute
2233
- * @param aggregator - The aggregator to use for both route finding and transaction building
2234
- * @param params - Combined parameters including trade details, wallet address, and slippage
2235
- * @returns Promise resolving to complete response with route info and built transaction, or null if no route found
2236
- */ async getTradeTransaction(aggregator, params) {
2237
- const routeResponse = await this.getTradeRoute(aggregator, {
2238
- coinInAmount: params.coinInAmount,
2239
- coinInType: params.coinInType,
2240
- coinOutType: params.coinOutType,
2241
- tradeFee: params.tradeFee
2242
- });
2243
- if (!routeResponse) {
2244
- return null;
2245
- }
2246
- const transaction = await this.getTransactionByRoute(aggregator, {
2247
- walletAddress: params.walletAddress,
2248
- completeRoute: routeResponse.aggregatorRoute,
2249
- slippage: params.slippage,
2250
- tradeFee: params.tradeFee
2251
- });
2252
- return {
2253
- route: routeResponse.route,
2254
- aggregatorRoute: routeResponse.aggregatorRoute,
2255
- transaction
2256
- };
2257
- }
2258
- /**
2259
- * Finds the best rate across all aggregators and returns the optimal trade transaction
2260
- * This method queries all available aggregators and selects the one with the best output amount
2261
- * @param params - Combined parameters including trade details, wallet address, and slippage
2262
- * @returns Promise resolving to complete response with route info and built transaction from the best aggregator, or null if no routes found
2263
- */ async getTradeTransactionWithBestRate(params) {
2264
- const aggregators = Object.keys(common_SupportedAggregator);
2265
- const tradeRouteResponses = await Promise.all(aggregators.map(async (aggregator)=>{
2266
- try {
2267
- return await this.getTradeRoute(aggregator, params);
2268
- } catch {
2269
- return null;
2270
- }
2271
- }));
2272
- let bestResponse = null;
2273
- let chosenAggregator = null;
2274
- for(let i = 0; i < tradeRouteResponses.length; i++){
2275
- const tradeRouteResponse = tradeRouteResponses[i];
2276
- const aggregator = aggregators[i];
2277
- if (!tradeRouteResponse) {
2278
- continue;
2279
- }
2280
- if (!bestResponse) {
2281
- bestResponse = tradeRouteResponse;
2282
- chosenAggregator = aggregator;
2283
- continue;
2284
- }
2285
- if (tradeRouteResponse.route.amountOut > bestResponse.route.amountOut) {
2286
- bestResponse = tradeRouteResponse;
2287
- chosenAggregator = aggregator;
2288
- continue;
2289
- }
2290
- }
2291
- if (!bestResponse || !chosenAggregator) {
2292
- return null;
2293
- }
2294
- const transaction = await this.getTransactionByRoute(chosenAggregator, {
2295
- walletAddress: params.walletAddress,
2296
- completeRoute: bestResponse.aggregatorRoute,
2297
- slippage: params.slippage,
2298
- tradeFee: params.tradeFee
2299
- });
2300
- return {
2301
- route: bestResponse.route,
2302
- aggregatorRoute: bestResponse.aggregatorRoute,
2303
- transaction
2304
- };
2305
- }
2306
- /**
2307
- * Gets the expected output amount for a trade using the specified aggregator
2308
- * This is a lightweight method that only fetches the route and returns the output amount
2309
- * without building a transaction
2310
- *
2311
- * @param aggregator - The aggregator to use for calculating output amount
2312
- * @param params - Trade route parameters including token types and input amount
2313
- * @returns Promise resolving to the expected output amount in smallest unit, or null if no route found
2314
- */ async getAmountOut(aggregator, params) {
2315
- const tradeRouteResult = await this.getTradeRoute(aggregator, params);
2316
- if (!tradeRouteResult) {
2317
- return null;
2318
- }
2319
- return tradeRouteResult.route.amountOut;
2320
- }
2321
- /**
2322
- * Finds the best output amount across all aggregators without building a transaction
2323
- * This method queries all available aggregators in parallel and returns the aggregator
2324
- * that provides the highest output amount along with that amount
2325
- *
2326
- * @param params - Trade route parameters including token types and input amount
2327
- * @returns Promise resolving to an object containing the best output amount and the aggregator that provided it, or null if no routes found
2328
- */ async getBestAmountOut(params) {
2329
- const aggregators = Object.keys(common_SupportedAggregator);
2330
- let bestAmountOut = null;
2331
- let bestAggregator = null;
2332
- for (const aggregator of aggregators){
2333
- const amountOut = await this.getAmountOut(aggregator, params);
2334
- if (amountOut === null) {
2335
- continue;
2336
- }
2337
- if (bestAmountOut === null || amountOut > bestAmountOut) {
2338
- bestAmountOut = amountOut;
2339
- bestAggregator = aggregator;
2340
- }
2341
- }
2342
- if (bestAmountOut === null || bestAggregator === null) {
2343
- return null;
2344
- }
2345
- return {
2346
- amountOut: bestAmountOut,
2347
- aggregator: bestAggregator
2348
- };
2349
- }
2350
- }
2351
-
2352
- ;// CONCATENATED MODULE: ./src/modules/boosting-module.ts
2353
-
2354
-
2355
-
2356
-
2357
- /** Sui package ID for the boosting protocol */ const BOOSTING_PACKAGE_ID = "0x25fa0eb553dd69fa6a8028f73a38f1df7f289fa88a58ed3d7dc5a5360155bb19";
2358
- /** Configuration object ID for boosting settings */ const CONFIG_ID = "0x8b1a8ac6e34688cd8f8f8e5fefa9d5fb9e1ff74d2f132f8e208ae5ac9cc530bb";
2359
- /** Admin capability object ID for privileged operations */ const ADMIN_CAP_ID = "0x13d101f44a0710a5475bec5f492a87b80e03d92d1cf540f26096f65850b23d26";
2360
- /**
2361
- * Module for managing boosting functionality in the Noodles SDK.
2362
- *
2363
- * This module provides methods for:
2364
- * - Paying boosting fees for different tiers
2365
- * - Managing boosting tiers (admin functions)
2366
- * - Retrieving boosting configuration
2367
- * - Updating fee receiver settings
2368
- */ class BoostingModule {
2369
- /** Reference to the main SDK instance */ sdk;
2370
- /**
2371
- * Creates a new BoostingModule instance.
2372
- *
2373
- * @param sdk - The main Noodles Pay SDK instance
2374
- */ constructor(sdk){
2375
- this.sdk = sdk;
2376
- }
2377
- /**
2378
- * Retrieves the current boosting configuration from the blockchain.
2379
- *
2380
- * @returns Promise resolving to the current boosting configuration
2381
- * @throws Error if config object is not found or invalid
2382
- */ async getConfig() {
2383
- const configObject = await this.sdk.suiClient.getObject({
2384
- id: CONFIG_ID,
2385
- options: {
2386
- showContent: true
2387
- }
2388
- });
2389
- tiny_invariant_default()(configObject.data?.content, "Config object not found or has no content");
2390
- tiny_invariant_default()(configObject.data?.content.dataType === "moveObject", "Config object is not a Move object");
2391
- const objectFields = configObject.data.content.fields;
2392
- const id = objectFields.id.id;
2393
- const feeReceiver = objectFields.fee_receiver;
2394
- const tiers = objectFields.tiers.fields.contents;
2395
- // Parse tier information from blockchain data
2396
- const tierMap = {};
2397
- for (const tier of tiers){
2398
- const key = tier.fields.key;
2399
- const duration = tier.fields.value.fields.duration;
2400
- const amount = tier.fields.value.fields.amount;
2401
- const point = tier.fields.value.fields.point;
2402
- const originalAmount = tier.fields.value.fields.original_amount;
2403
- tierMap[key] = {
2404
- duration: BigInt(duration),
2405
- amount: BigInt(amount),
2406
- point: BigInt(point),
2407
- originalAmount: BigInt(originalAmount)
2408
- };
2409
- }
2410
- return {
2411
- id,
2412
- receiverAddress: feeReceiver,
2413
- tiers: tierMap
2414
- };
2415
- }
2416
- /**
2417
- * Builds a transaction for paying boosting fees for a specific tier.
2418
- * The payment amount is determined by the tier configuration.
2419
- *
2420
- * @param request - Payment request parameters
2421
- * @returns Promise resolving to a transaction ready for execution
2422
- * @throws Error if tier ID is invalid
2423
- */ async buildPayBoostingTx({ walletAddress, tierId, boostingCoinType, currentTx }) {
2424
- const configObj = await this.getConfig();
2425
- tiny_invariant_default()(tierId in configObj.tiers, "Invalid tier ID");
2426
- const tier = configObj.tiers[tierId];
2427
- const paymentAmount = tier.amount;
2428
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2429
- const paymentCoin = tx.splitCoins(tx.gas, [
2430
- tx.pure.u64(paymentAmount)
2431
- ]);
2432
- tx.moveCall({
2433
- target: `${BOOSTING_PACKAGE_ID}::boosting::pay`,
2434
- typeArguments: [
2435
- (0,utils_namespaceObject.normalizeStructTag)(boostingCoinType)
2436
- ],
2437
- arguments: [
2438
- tx.object(CONFIG_ID),
2439
- tx.pure.u64(tierId),
2440
- paymentCoin
2441
- ]
2442
- });
2443
- tx.setSender(walletAddress);
2444
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, walletAddress, 0);
2445
- return addGasFee({
2446
- inheritTx: tx,
2447
- sender: walletAddress,
2448
- feeAmount: gasAmount
2449
- }, this.sdk.suiClient);
2450
- }
2451
- /**
2452
- * Builds a transaction for adding a new boosting tier.
2453
- *
2454
- * **Requires admin capability.**
2455
- *
2456
- * @param request - Add tier request parameters
2457
- * @returns Promise resolving to a transaction ready for execution
2458
- */ async buildAddTierTx({ adminAddress, tierId, duration, point, originalAmount, amount, currentTx }) {
2459
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2460
- tx.moveCall({
2461
- target: `${BOOSTING_PACKAGE_ID}::config::add_tier`,
2462
- typeArguments: [],
2463
- arguments: [
2464
- tx.object(CONFIG_ID),
2465
- tx.object(ADMIN_CAP_ID),
2466
- tx.pure.u64(tierId),
2467
- tx.pure.u64(point),
2468
- tx.pure.u64(duration),
2469
- tx.pure.u64(originalAmount),
2470
- tx.pure.u64(amount)
2471
- ]
2472
- });
2473
- tx.setSender(adminAddress);
2474
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2475
- return addGasFee({
2476
- inheritTx: tx,
2477
- sender: adminAddress,
2478
- feeAmount: gasAmount
2479
- }, this.sdk.suiClient);
2480
- }
2481
- /**
2482
- * Builds a transaction for updating an existing boosting tier.
2483
- *
2484
- * **Requires admin capability.**
2485
- *
2486
- * @param request - Update tier request parameters
2487
- * @returns Promise resolving to a transaction ready for execution
2488
- */ async buildUpdateTierTx({ adminAddress, tierId, duration, amount, originalAmount, point, currentTx }) {
2489
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2490
- tx.moveCall({
2491
- target: `${BOOSTING_PACKAGE_ID}::config::update_tier`,
2492
- typeArguments: [],
2493
- arguments: [
2494
- tx.object(CONFIG_ID),
2495
- tx.object(ADMIN_CAP_ID),
2496
- tx.pure.u64(tierId),
2497
- tx.pure.u64(duration),
2498
- tx.pure.u64(amount),
2499
- tx.pure.u64(point),
2500
- tx.pure.u64(originalAmount)
2501
- ]
2502
- });
2503
- tx.setSender(adminAddress);
2504
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2505
- return addGasFee({
2506
- inheritTx: tx,
2507
- sender: adminAddress,
2508
- feeAmount: gasAmount
2509
- }, this.sdk.suiClient);
2510
- }
2511
- /**
2512
- * Builds a transaction for removing a boosting tier.
2513
- *
2514
- * **Requires admin capability.**
2515
- *
2516
- * @param request - Remove tier request parameters
2517
- * @returns Promise resolving to a transaction ready for execution
2518
- */ async buildRemoveTierTx({ adminAddress, tierId, currentTx }) {
2519
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2520
- tx.moveCall({
2521
- target: `${BOOSTING_PACKAGE_ID}::config::remove_tier`,
2522
- typeArguments: [],
2523
- arguments: [
2524
- tx.object(CONFIG_ID),
2525
- tx.object(ADMIN_CAP_ID),
2526
- tx.pure.u64(tierId)
2527
- ]
2528
- });
2529
- tx.setSender(adminAddress);
2530
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2531
- return addGasFee({
2532
- inheritTx: tx,
2533
- sender: adminAddress,
2534
- feeAmount: gasAmount
2535
- }, this.sdk.suiClient);
2536
- }
2537
- /**
2538
- * Builds a transaction for updating the fee receiver address.
2539
- *
2540
- * **Requires admin capability.**
2541
- *
2542
- * @param request - Update fee receiver request parameters
2543
- * @returns Promise resolving to a transaction ready for execution
2544
- */ async buildUpdateFeeReceiver({ adminAddress, newReceiverAddress, currentTx }) {
2545
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2546
- tx.moveCall({
2547
- target: `${BOOSTING_PACKAGE_ID}::config::update_fee_receiver`,
2548
- typeArguments: [],
2549
- arguments: [
2550
- tx.object(CONFIG_ID),
2551
- tx.object(ADMIN_CAP_ID),
2552
- tx.pure.address(newReceiverAddress)
2553
- ]
2554
- });
2555
- tx.setSender(adminAddress);
2556
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2557
- return addGasFee({
2558
- inheritTx: tx,
2559
- sender: adminAddress,
2560
- feeAmount: gasAmount
2561
- }, this.sdk.suiClient);
2562
- }
2563
- /**
2564
- * Builds a transaction for paying boosting fees with admin privileges.
2565
- * Allows specifying a custom payment amount instead of using the tier's default amount.
2566
- *
2567
- * **Requires admin capability.**
2568
- *
2569
- * @param request - Admin payment request parameters
2570
- * @returns Promise resolving to a transaction ready for execution
2571
- */ async buildPayBoostingWithAdminTx({ walletAddress, tierId, customAmount, boostingCoinType, currentTx }) {
2572
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2573
- const paymentCoin = tx.splitCoins(tx.gas, [
2574
- tx.pure.u64(customAmount)
2575
- ]);
2576
- tx.moveCall({
2577
- target: `${BOOSTING_PACKAGE_ID}::boosting::pay_with_admin`,
2578
- typeArguments: [
2579
- (0,utils_namespaceObject.normalizeStructTag)(boostingCoinType)
2580
- ],
2581
- arguments: [
2582
- tx.object(ADMIN_CAP_ID),
2583
- tx.object(CONFIG_ID),
2584
- tx.pure.u64(tierId),
2585
- tx.pure.u64(customAmount),
2586
- paymentCoin
2587
- ]
2588
- });
2589
- tx.setSender(walletAddress);
2590
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, walletAddress, 0);
2591
- return addGasFee({
2592
- inheritTx: tx,
2593
- sender: walletAddress,
2594
- feeAmount: gasAmount
2595
- }, this.sdk.suiClient);
2596
- }
2597
- }
2598
-
2599
- ;// CONCATENATED MODULE: ./src/modules/curve-module.ts
2600
-
2601
-
2602
-
2603
- class CurveModule {
2604
- sdk;
2605
- constructor(sdk){
2606
- this.sdk = sdk;
2607
- }
2608
- async getEstimatedAmountOut(platform, params) {
2609
- const { coinInType, coinOutType } = params;
2610
- tiny_invariant_default()(coinInType !== coinOutType, "coinInType and coinOutType must be different");
2611
- tiny_invariant_default()(isSuiCoinType(coinInType) || isSuiCoinType(coinOutType), "One of coinInType or coinOutType must be SUI");
2612
- const isBuy = isSuiCoinType(coinInType);
2613
- switch(platform){
2614
- case types_SupportedBondingCurve.MOONBAGS:
2615
- {
2616
- if (isBuy) {
2617
- return await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({
2618
- poolId: params.poolId,
2619
- suiAmount: params.coinInAmount,
2620
- frontendFee: params.tradeFee ? params.tradeFee.tradeFeePercent : undefined
2621
- }, this.sdk.suiClient);
2622
- } else {
2623
- return await calculation_MoonbagsCalculation.getSuiAmountAfterSell({
2624
- poolId: params.poolId,
2625
- curveAmount: params.coinInAmount,
2626
- frontendFee: params.tradeFee ? params.tradeFee.tradeFeePercent : undefined
2627
- }, this.sdk.suiClient);
2628
- }
2629
- }
2630
- case types_SupportedBondingCurve.BLAST_FUN:
2631
- {
2632
- if (isBuy) {
2633
- return await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({
2634
- poolId: params.poolId,
2635
- suiAmount: params.coinInAmount,
2636
- frontendFee: params.tradeFee ? params.tradeFee.tradeFeePercent : undefined
2637
- });
2638
- } else {
2639
- return await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({
2640
- poolId: params.poolId,
2641
- curveAmount: params.coinInAmount,
2642
- frontendFee: params.tradeFee ? params.tradeFee.tradeFeePercent : undefined
2643
- });
2644
- }
2645
- }
2646
- default:
2647
- throw new Error(`Unsupported bonding curve platform: ${platform}`);
2648
- }
2649
- }
2650
- async getTradeTransaction(platform, params) {
2651
- const { coinInType, coinOutType } = params;
2652
- tiny_invariant_default()(coinInType !== coinOutType, "coinInType and coinOutType must be different");
2653
- tiny_invariant_default()(isSuiCoinType(coinInType) || isSuiCoinType(coinOutType), "One of coinInType or coinOutType must be SUI");
2654
- const isBuy = isSuiCoinType(coinInType);
2655
- let tx;
2656
- switch(platform){
2657
- case types_SupportedBondingCurve.MOONBAGS:
2658
- {
2659
- if (isBuy) {
2660
- tx = await transaction_MoonbagsTransaction.getBuyTransaction(params, this.sdk.suiClient);
2661
- } else {
2662
- tx = await transaction_MoonbagsTransaction.getSellTransaction(params, this.sdk.suiClient);
2663
- }
2664
- break;
2665
- }
2666
- case types_SupportedBondingCurve.BLAST_FUN:
2667
- {
2668
- if (isBuy) {
2669
- tx = await sdk_transaction_BlastFunSDKTransaction.getBuyTransaction(params, this.sdk.suiClient);
2670
- } else {
2671
- tx = await sdk_transaction_BlastFunSDKTransaction.getSellTransaction(params, this.sdk.suiClient);
2672
- }
2673
- break;
2674
- }
2675
- default:
2676
- throw new Error(`Unsupported bonding curve platform: ${platform}`);
2677
- }
2678
- return tx;
2679
- }
2680
- }
2681
-
2682
- ;// CONCATENATED MODULE: ./src/modules/subscription-module.ts
2683
-
2684
-
2685
-
2686
- /** Sui package ID for the subscription protocol */ const SUBSCRIPTION_PACKAGE_ID = "0x5dd4286ec234c117bb9577d4eaed1885b70d73ab1d3dab2794d0ab9a2c06c4a1";
2687
- /** Configuration object ID for subscription settings */ const SUBSCRIPTION_CONFIG_ID = "0x095b941beff22213fe8ccb223e4d1c5b4ede4dcd7f82ca4bb18c9a45fd3d6e20";
2688
- /** Admin capability object ID for privileged operations */ const SUBSCRIPTION_ADMIN_CAP_ID = "0xdc27fe8187131b7fc095fccd213b79f72312793152a2483d1f67199c390e256d";
2689
- /** Payment coin type on SUI */ const PAYMENT_COIN_TYPE = "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";
2690
- /**
2691
- * Module for managing subscription functionality in the Noodles SDK.
2692
- *
2693
- * This module provides methods for:
2694
- * - Subscribing to plans
2695
- * - Upgrading plans (immediate or next billing cycle)
2696
- * - Managing subscription plans (admin functions)
2697
- * - Retrieving subscription configuration
2698
- * - Updating fee receiver wallet and pause settings
2699
- */ class SubscriptionModule {
2700
- /** Reference to the main SDK instance */ sdk;
2701
- /**
2702
- * Creates a new SubscriptionModule instance.
2703
- *
2704
- * @param sdk - The main Noodles Pay SDK instance
2705
- */ constructor(sdk){
2706
- this.sdk = sdk;
2707
- }
2708
- /**
2709
- * Retrieves the current subscription configuration from the blockchain.
2710
- *
2711
- * @returns Promise resolving to the current subscription configuration
2712
- * @throws Error if config object is not found or invalid
2713
- */ async getConfig() {
2714
- const configObject = await this.sdk.suiClient.getObject({
2715
- id: SUBSCRIPTION_CONFIG_ID,
2716
- options: {
2717
- showContent: true
2718
- }
2719
- });
2720
- tiny_invariant_default()(configObject.data, "Config object not found");
2721
- tiny_invariant_default()(configObject.data.content, "Config object has no content");
2722
- tiny_invariant_default()(configObject.data?.content.dataType === "moveObject", "Config object is not a Move object");
2723
- const objectFields = configObject.data.content.fields;
2724
- const id = objectFields.id.id;
2725
- const feeReceiverWallet = objectFields.fee_receiver;
2726
- const paused = objectFields.paused;
2727
- const acceptedPaymentType = objectFields.accepted_payment_type;
2728
- const plans = objectFields.plans.fields.contents;
2729
- // Parse plan information from blockchain data
2730
- const planMap = {};
2731
- for (const plan of plans){
2732
- const key = plan.fields.key;
2733
- const planId = plan.fields.value.fields.id;
2734
- const price = plan.fields.value.fields.price;
2735
- const monthInterval = plan.fields.value.fields.month_interval;
2736
- const planType = plan.fields.value.fields.ptype;
2737
- planMap[key] = {
2738
- id: BigInt(planId),
2739
- price: BigInt(price),
2740
- monthInterval: monthInterval,
2741
- planType: planType
2742
- };
2743
- }
2744
- return {
2745
- id,
2746
- plans: planMap,
2747
- feeReceiverWallet: feeReceiverWallet,
2748
- paused,
2749
- acceptedPaymentType
2750
- };
2751
- }
2752
- /**
2753
- * Builds a transaction for subscribing to a plan.
2754
- * The payment amount is determined by the plan configuration.
2755
- *
2756
- * @param request - Subscription request parameters
2757
- * @reference order_id generated from your backend to identify the purchase
2758
- * @returns Promise resolving to a transaction ready for execution
2759
- * @throws Error if plan ID is invalid or contract is paused
2760
- */ async buildSubscribeCyclePlanTx({ walletAddress, planId, reference, paymentCoinType = PAYMENT_COIN_TYPE, currentTx }) {
2761
- const configObj = await this.getConfig();
2762
- tiny_invariant_default()(!configObj.paused, "Contract is paused");
2763
- tiny_invariant_default()(planId in configObj.plans, "Invalid plan ID");
2764
- const plan = configObj.plans[planId];
2765
- const paymentAmount = plan.price;
2766
- // Get USDC coins from user's wallet
2767
- const { tx: txWithCoin, coinData } = await getSplitCoinForTx({
2768
- account: walletAddress,
2769
- amount: paymentAmount.toString(),
2770
- splits: [
2771
- paymentAmount.toString()
2772
- ],
2773
- coinType: paymentCoinType,
2774
- inheritTx: currentTx
2775
- }, this.sdk.suiClient);
2776
- txWithCoin.moveCall({
2777
- target: `${SUBSCRIPTION_PACKAGE_ID}::subscription::subscribe_cycle_plan`,
2778
- typeArguments: [
2779
- paymentCoinType
2780
- ],
2781
- arguments: [
2782
- txWithCoin.object(SUBSCRIPTION_CONFIG_ID),
2783
- txWithCoin.pure.u64(planId),
2784
- txWithCoin.pure.string(reference),
2785
- coinData
2786
- ]
2787
- });
2788
- txWithCoin.setSender(walletAddress);
2789
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, txWithCoin, walletAddress, 0);
2790
- return addGasFee({
2791
- inheritTx: txWithCoin,
2792
- sender: walletAddress,
2793
- feeAmount: gasAmount
2794
- }, this.sdk.suiClient);
2795
- }
2796
- /**
2797
- * Builds a transaction for buying additional compute units (CU) for CUAddOn plans.
2798
- *
2799
- * @param request - Buy more CU request parameters
2800
- * @reference order_id generated from your backend to identify the purchase
2801
- * @returns Promise resolving to a transaction ready for execution
2802
- * @throws Error if plan ID is invalid or contract is paused
2803
- */ async buildBuyMoreCUPlanTx({ walletAddress, planId, reference, paidAmount, paymentCoinType = PAYMENT_COIN_TYPE, currentTx }) {
2804
- const configObj = await this.getConfig();
2805
- tiny_invariant_default()(!configObj.paused, "Contract is paused");
2806
- tiny_invariant_default()(planId in configObj.plans, "Invalid plan ID");
2807
- // Get USDC coins from user's wallet
2808
- const { tx: txWithCoin, coinData } = await getSplitCoinForTx({
2809
- account: walletAddress,
2810
- amount: paidAmount.toString(),
2811
- splits: [
2812
- paidAmount.toString()
2813
- ],
2814
- coinType: paymentCoinType,
2815
- inheritTx: currentTx
2816
- }, this.sdk.suiClient);
2817
- txWithCoin.moveCall({
2818
- target: `${SUBSCRIPTION_PACKAGE_ID}::subscription::buy_more_cu`,
2819
- typeArguments: [
2820
- paymentCoinType
2821
- ],
2822
- arguments: [
2823
- txWithCoin.object(SUBSCRIPTION_CONFIG_ID),
2824
- txWithCoin.pure.u64(planId),
2825
- txWithCoin.pure.string(reference),
2826
- txWithCoin.pure.u64(paidAmount),
2827
- coinData
2828
- ]
2829
- });
2830
- txWithCoin.setSender(walletAddress);
2831
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, txWithCoin, walletAddress, 0);
2832
- return addGasFee({
2833
- inheritTx: txWithCoin,
2834
- sender: walletAddress,
2835
- feeAmount: gasAmount
2836
- }, this.sdk.suiClient);
2837
- }
2838
- /**
2839
- * Builds a transaction for subscribing with admin privileges.
2840
- * Allows specifying a custom payment amount instead of using the plan's default price.
2841
- * Useful for promotions, discounts, or special cases.
2842
- *
2843
- * **Requires admin capability.**
2844
- *
2845
- * @param request - Admin subscription request parameters
2846
- * @returns Promise resolving to a transaction ready for execution
2847
- * @throws Error if contract is paused
2848
- */ async buildSubscribePlanWithAdminTx({ walletAddress, planId, reference, customAmount, paymentCoinType = PAYMENT_COIN_TYPE, currentTx }) {
2849
- const configObj = await this.getConfig();
2850
- tiny_invariant_default()(!configObj.paused, "Contract is paused");
2851
- // Get USDC coins from user's wallet
2852
- const { tx: txWithCoin, coinData } = await getSplitCoinForTx({
2853
- account: walletAddress,
2854
- amount: customAmount.toString(),
2855
- splits: [
2856
- customAmount.toString()
2857
- ],
2858
- coinType: paymentCoinType,
2859
- inheritTx: currentTx
2860
- }, this.sdk.suiClient);
2861
- txWithCoin.moveCall({
2862
- target: `${SUBSCRIPTION_PACKAGE_ID}::subscription::subscribe_plan_with_admin`,
2863
- typeArguments: [
2864
- paymentCoinType
2865
- ],
2866
- arguments: [
2867
- txWithCoin.object(SUBSCRIPTION_ADMIN_CAP_ID),
2868
- txWithCoin.object(SUBSCRIPTION_CONFIG_ID),
2869
- txWithCoin.pure.u64(planId),
2870
- txWithCoin.pure.string(reference),
2871
- txWithCoin.pure.u64(customAmount),
2872
- coinData
2873
- ]
2874
- });
2875
- txWithCoin.setSender(walletAddress);
2876
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, txWithCoin, walletAddress, 0);
2877
- return addGasFee({
2878
- inheritTx: txWithCoin,
2879
- sender: walletAddress,
2880
- feeAmount: gasAmount
2881
- }, this.sdk.suiClient);
2882
- }
2883
- /**
2884
- * Builds a transaction for adding a new subscription plan.
2885
- *
2886
- * **Requires admin capability.**
2887
- *
2888
- * @param request - Add plan request parameters
2889
- * @returns Promise resolving to a transaction ready for execution
2890
- */ async buildAddPlanTx({ adminAddress, planId, planType, monthInterval, price, currentTx }) {
2891
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2892
- tx.moveCall({
2893
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::add_plan`,
2894
- typeArguments: [],
2895
- arguments: [
2896
- tx.object(SUBSCRIPTION_CONFIG_ID),
2897
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID),
2898
- tx.pure.u64(planId),
2899
- tx.pure.u8(planType),
2900
- tx.pure.u8(monthInterval),
2901
- tx.pure.u64(price)
2902
- ]
2903
- });
2904
- tx.setSender(adminAddress);
2905
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2906
- return addGasFee({
2907
- inheritTx: tx,
2908
- sender: adminAddress,
2909
- feeAmount: gasAmount
2910
- }, this.sdk.suiClient);
2911
- }
2912
- /**
2913
- * Builds a transaction for updating an existing subscription plan.
2914
- *
2915
- * **Requires admin capability.**
2916
- *
2917
- * @param request - Update plan request parameters
2918
- * @returns Promise resolving to a transaction ready for execution
2919
- */ async buildUpdatePlanTx({ adminAddress, planId, planType, monthInterval, price, currentTx }) {
2920
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2921
- tx.moveCall({
2922
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::update_plan`,
2923
- typeArguments: [],
2924
- arguments: [
2925
- tx.object(SUBSCRIPTION_CONFIG_ID),
2926
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID),
2927
- tx.pure.u64(BigInt(planId)),
2928
- tx.pure.u8(planType),
2929
- tx.pure.u8(monthInterval),
2930
- tx.pure.u64(price)
2931
- ]
2932
- });
2933
- tx.setSender(adminAddress);
2934
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2935
- return addGasFee({
2936
- inheritTx: tx,
2937
- sender: adminAddress,
2938
- feeAmount: gasAmount
2939
- }, this.sdk.suiClient);
2940
- }
2941
- /**
2942
- * Builds a transaction for removing a subscription plan.
2943
- *
2944
- * **Requires admin capability.**
2945
- *
2946
- * @param request - Remove plan request parameters
2947
- * @returns Promise resolving to a transaction ready for execution
2948
- */ async buildRemovePlanTx({ adminAddress, planId, currentTx }) {
2949
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2950
- tx.moveCall({
2951
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::remove_plan`,
2952
- typeArguments: [],
2953
- arguments: [
2954
- tx.object(SUBSCRIPTION_CONFIG_ID),
2955
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID),
2956
- tx.pure.u64(BigInt(planId))
2957
- ]
2958
- });
2959
- tx.setSender(adminAddress);
2960
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2961
- return addGasFee({
2962
- inheritTx: tx,
2963
- sender: adminAddress,
2964
- feeAmount: gasAmount
2965
- }, this.sdk.suiClient);
2966
- }
2967
- /**
2968
- * Builds a transaction for updating the admin wallet address.
2969
- *
2970
- * **Requires admin capability.**
2971
- *
2972
- * @param request - Update admin wallet request parameters
2973
- * @returns Promise resolving to a transaction ready for execution
2974
- */ async buildUpdateFeeReceiverWalletTx({ adminAddress, newFeeReceiverWallet, currentTx }) {
2975
- const tx = currentTx || new transactions_namespaceObject.Transaction();
2976
- tx.moveCall({
2977
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::update_fee_receiver`,
2978
- typeArguments: [],
2979
- arguments: [
2980
- tx.object(SUBSCRIPTION_CONFIG_ID),
2981
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID),
2982
- tx.pure.address(newFeeReceiverWallet)
2983
- ]
2984
- });
2985
- tx.setSender(adminAddress);
2986
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
2987
- return addGasFee({
2988
- inheritTx: tx,
2989
- sender: adminAddress,
2990
- feeAmount: gasAmount
2991
- }, this.sdk.suiClient);
2992
- }
2993
- /**
2994
- * Builds a transaction for pausing or unpausing the contract.
2995
- *
2996
- * **Requires admin capability.**
2997
- *
2998
- * @param request - Set paused request parameters
2999
- * @returns Promise resolving to a transaction ready for execution
3000
- */ async buildSetPausedTx({ adminAddress, paused, currentTx }) {
3001
- const tx = currentTx || new transactions_namespaceObject.Transaction();
3002
- tx.moveCall({
3003
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::set_paused`,
3004
- typeArguments: [],
3005
- arguments: [
3006
- tx.object(SUBSCRIPTION_CONFIG_ID),
3007
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID),
3008
- tx.pure.bool(paused)
3009
- ]
3010
- });
3011
- tx.setSender(adminAddress);
3012
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
3013
- return addGasFee({
3014
- inheritTx: tx,
3015
- sender: adminAddress,
3016
- feeAmount: gasAmount
3017
- }, this.sdk.suiClient);
3018
- }
3019
- /**
3020
- * Builds a transaction to set the accepted payment coin type.
3021
- * Note: Only one payment type can be accepted at a time. Setting a new type replaces the previous one.
3022
- *
3023
- * **Requires admin capability.**
3024
- *
3025
- * @param request - Set accepted payment type request parameters
3026
- * @returns Promise resolving to a transaction ready for execution
3027
- */ async buildSetAcceptedPaymentTypeTx({ adminAddress, paymentCoinType, currentTx }) {
3028
- const tx = currentTx || new transactions_namespaceObject.Transaction();
3029
- tx.moveCall({
3030
- target: `${SUBSCRIPTION_PACKAGE_ID}::config::set_accepted_payment_type`,
3031
- typeArguments: [
3032
- paymentCoinType
3033
- ],
3034
- arguments: [
3035
- tx.object(SUBSCRIPTION_CONFIG_ID),
3036
- tx.object(SUBSCRIPTION_ADMIN_CAP_ID)
3037
- ]
3038
- });
3039
- tx.setSender(adminAddress);
3040
- const gasAmount = await getNeededGasFee(this.sdk.suiClient, tx, adminAddress, 0);
3041
- return addGasFee({
3042
- inheritTx: tx,
3043
- sender: adminAddress,
3044
- feeAmount: gasAmount
3045
- }, this.sdk.suiClient);
3046
- }
3047
- }
3048
-
3049
- ;// CONCATENATED MODULE: ./src/modules/index.ts
3050
-
3051
-
3052
-
3053
-
3054
-
3055
-
3056
- ;// CONCATENATED MODULE: ./src/pay-sdk.ts
3057
-
3058
-
3059
- class NoodlesPaySdk {
3060
- _suiClient;
3061
- boostingModule;
3062
- subscriptionModule;
3063
- constructor(){
3064
- this._suiClient = new client_namespaceObject.SuiClient({
3065
- url: (0,client_namespaceObject.getFullnodeUrl)("mainnet")
3066
- });
3067
- this.subscriptionModule = new SubscriptionModule(this);
3068
- this.boostingModule = new BoostingModule(this);
3069
- }
3070
- get suiClient() {
3071
- return this._suiClient;
3072
- }
3073
- }
3074
-
3075
- ;// CONCATENATED MODULE: ./src/sdk.ts
3076
-
3077
-
3078
- const DEFAULT_TRADE_FEE = {
3079
- tradeFeePercent: 0.01,
3080
- tradeFeeRecipientAddress: "0xdaf1c8ed29d89cd8f217f609bad0a668fa6f158c12000bfa5f93e670c99e24ff"
3081
- };
3082
- class NoodlesSdk {
3083
- options;
3084
- _suiClient;
3085
- aggregatorModule;
3086
- curveModule;
3087
- constructor(options){
3088
- this.options = options;
3089
- this._suiClient = new client_namespaceObject.SuiClient({
3090
- url: (0,client_namespaceObject.getFullnodeUrl)("mainnet")
3091
- });
3092
- this.aggregatorModule = new AggregatorModule(this);
3093
- this.curveModule = new CurveModule(this);
3094
- }
3095
- get suiClient() {
3096
- return this._suiClient;
3097
- }
3098
- }
3099
-
3100
- ;// CONCATENATED MODULE: external "@mysten/sui/keypairs/ed25519"
3101
- const ed25519_namespaceObject = require("@mysten/sui/keypairs/ed25519");
3102
- ;// CONCATENATED MODULE: ./src/transaction/draft-transfer.ts
3103
-
3104
-
3105
-
3106
-
3107
-
3108
- // Constants
3109
- const CONSTANTS = {
3110
- GAS_FEE_BUFFER_PERCENTAGE: 0.1
3111
- };
3112
- class DraftTransferTx {
3113
- suiClient;
3114
- constructor(suiClient){
3115
- this.suiClient = suiClient;
3116
- }
3117
- /**
3118
- * Validates private key against expected sender address
3119
- * @private
3120
- */ validatePrivateKey(privateKey, expectedSender) {
3121
- tiny_invariant_default()(privateKey?.trim(), "Private key is required");
3122
- const keypair = ed25519_namespaceObject.Ed25519Keypair.fromSecretKey(privateKey);
3123
- const derivedAddress = keypair.getPublicKey().toSuiAddress();
3124
- if (derivedAddress !== expectedSender) {
3125
- throw new Error(`Private key mismatch. Expected: ${expectedSender}, Got: ${derivedAddress}`);
3126
- }
3127
- return keypair;
3128
- }
3129
- /**
3130
- * Creates a draft transaction for SUI transfer
3131
- * @param params - Transfer parameters
3132
- * @returns Draft transaction object with encoded transaction data
3133
- * @throws {Error} If validation fails or transaction building fails
3134
- */ async createDraft(sender, recipient, amountMIST) {
3135
- tiny_invariant_default()(sender?.trim(), "Sender address is required");
3136
- tiny_invariant_default()(recipient?.trim(), "Recipient address is required");
3137
- tiny_invariant_default()(sender !== recipient, "Sender and recipient cannot be the same");
3138
- tiny_invariant_default()(amountMIST > 0n, "Transfer amount must be at least 1 MIST");
3139
- try {
3140
- // Build the transaction
3141
- let transaction = new transactions_namespaceObject.Transaction();
3142
- const [coin] = transaction.splitCoins(transaction.gas, [
3143
- amountMIST
3144
- ]);
3145
- transaction.transferObjects([
3146
- coin
3147
- ], recipient);
3148
- transaction.setSender(sender);
3149
- // Set gas configuration
3150
- const referenceGasPrice = await this.suiClient.getReferenceGasPrice();
3151
- transaction.setGasPrice(referenceGasPrice);
3152
- // Calculate and set gas budget
3153
- const feeAmount = await getNeededGasFee(this.suiClient, transaction, sender, CONSTANTS.GAS_FEE_BUFFER_PERCENTAGE);
3154
- transaction = await addGasFee({
3155
- inheritTx: transaction,
3156
- sender,
3157
- feeAmount,
3158
- suiInputAmount: amountMIST
3159
- }, this.suiClient);
3160
- // Build and encode transaction
3161
- const txBytes = await transaction.build({
3162
- client: this.suiClient
3163
- });
3164
- const txDraftBase64 = Buffer.from(txBytes).toString("base64");
3165
- const txDigest = await transaction.getDigest();
3166
- return {
3167
- sender,
3168
- recipient,
3169
- amountMIST,
3170
- txDraftBase64,
3171
- txDigest
3172
- };
3173
- } catch (error) {
3174
- throw new Error(`Failed to create draft transaction: ${error instanceof Error ? error.message : "Unknown error"}`);
3175
- }
3176
- }
3177
- /**
3178
- * Executes a draft transaction on the Sui network
3179
- * @param draftTx - Draft transaction to execute
3180
- * @param privateKey - Sender's private key
3181
- * @returns Execution result with success status and transaction details
3182
- */ async execute(draftTx, privateKey) {
3183
- try {
3184
- tiny_invariant_default()(draftTx, "Draft transaction is required");
3185
- tiny_invariant_default()(draftTx.txDraftBase64?.trim(), "Transaction data is required");
3186
- // Validate private key and get keypair
3187
- const keypair = this.validatePrivateKey(privateKey, draftTx.sender);
3188
- // Decode and sign transaction
3189
- const txBytes = (0,utils_namespaceObject.fromBase64)(draftTx.txDraftBase64);
3190
- const { signature } = await keypair.signTransaction(txBytes);
3191
- // Execute on network
3192
- const result = await this.suiClient.executeTransactionBlock({
3193
- transactionBlock: txBytes,
3194
- signature
3195
- });
3196
- return {
3197
- success: true,
3198
- txDigest: result.digest,
3199
- effects: result.effects
3200
- };
3201
- } catch (error) {
3202
- const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
3203
- return {
3204
- success: false,
3205
- error: errorMessage
3206
- };
3207
- }
3208
- }
3209
- /**
3210
- * Verifies the status of a transaction on the Sui network
3211
- * @param txDigest - Transaction digest to check
3212
- * @returns Transaction status: 'success', 'failure', or 'pending'
3213
- */ async getTransactionStatus(txDigest) {
3214
- tiny_invariant_default()(txDigest?.trim(), "Transaction digest is required");
3215
- try {
3216
- const txResponse = await this.suiClient.getTransactionBlock({
3217
- digest: txDigest,
3218
- options: {
3219
- showEffects: true
3220
- }
3221
- });
3222
- if (!txResponse?.effects?.status) {
3223
- return "pending";
3224
- }
3225
- return txResponse.effects.status.status === "success" ? "success" : "failure";
3226
- } catch (error) {
3227
- if (error instanceof Error) {
3228
- // Transaction not found indicates it's still pending
3229
- if (error.message.includes("not found") || error.message.includes("Could not find")) {
3230
- return "pending";
3231
- }
3232
- }
3233
- return "failure";
3234
- }
3235
- }
3236
- }
3237
-
3238
- ;// CONCATENATED MODULE: ./src/transaction/index.ts
3239
-
3240
-
3241
- ;// CONCATENATED MODULE: ./src/exports/index.ts
3242
-
3243
-
3244
-
3245
-
3246
-
3247
-
3248
-
3249
-
3250
-
3251
-
3252
- exports.ADMIN_CAP_ID = __webpack_exports__.ADMIN_CAP_ID;
3253
- exports.AftermathAggregator = __webpack_exports__.AftermathAggregator;
3254
- exports.AggregatorModule = __webpack_exports__.AggregatorModule;
3255
- exports.AstrosAggregator = __webpack_exports__.AstrosAggregator;
3256
- exports.BASE_BPS = __webpack_exports__.BASE_BPS;
3257
- exports.BLUEFIN_PACKAGE_ID = __webpack_exports__.BLUEFIN_PACKAGE_ID;
3258
- exports.BOOSTING_PACKAGE_ID = __webpack_exports__.BOOSTING_PACKAGE_ID;
3259
- exports.BlastFunConstants = __webpack_exports__.BlastFunConstants;
3260
- exports.BlastFunCustomCalculation = __webpack_exports__.BlastFunCustomCalculation;
3261
- exports.BlastFunCustomTransaction = __webpack_exports__.BlastFunCustomTransaction;
3262
- exports.BlastFunPackage = __webpack_exports__.BlastFunPackage;
3263
- exports.BlastFunSDKCalculation = __webpack_exports__.BlastFunSDKCalculation;
3264
- exports.BlastFunSDKTransaction = __webpack_exports__.BlastFunSDKTransaction;
3265
- exports.BluefinTx = __webpack_exports__.BluefinTx;
3266
- exports.BoostingModule = __webpack_exports__.BoostingModule;
3267
- exports.Bps = __webpack_exports__.Bps;
3268
- exports.CLOCK_OBJECT_ID = __webpack_exports__.CLOCK_OBJECT_ID;
3269
- exports.CONFIG_ID = __webpack_exports__.CONFIG_ID;
3270
- exports.CetusAggregator = __webpack_exports__.CetusAggregator;
3271
- exports.CurveModule = __webpack_exports__.CurveModule;
3272
- exports.DEFAULT_TRADE_FEE = __webpack_exports__.DEFAULT_TRADE_FEE;
3273
- exports.DraftTransferTx = __webpack_exports__.DraftTransferTx;
3274
- exports.FlowXAggregator = __webpack_exports__.FlowXAggregator;
3275
- exports.MathUtils = __webpack_exports__.MathUtils;
3276
- exports.MoonbagsCalculation = __webpack_exports__.MoonbagsCalculation;
3277
- exports.MoonbagsConstants = __webpack_exports__.MoonbagsConstants;
3278
- exports.MoonbagsPackage = __webpack_exports__.MoonbagsPackage;
3279
- exports.MoonbagsTransaction = __webpack_exports__.MoonbagsTransaction;
3280
- exports.NATIVE_USDC_TOKEN_TYPE = __webpack_exports__.NATIVE_USDC_TOKEN_TYPE;
3281
- exports.NoodlesPaySdk = __webpack_exports__.NoodlesPaySdk;
3282
- exports.NoodlesSdk = __webpack_exports__.NoodlesSdk;
3283
- exports.PAYMENT_COIN_TYPE = __webpack_exports__.PAYMENT_COIN_TYPE;
3284
- exports.SUBSCRIPTION_ADMIN_CAP_ID = __webpack_exports__.SUBSCRIPTION_ADMIN_CAP_ID;
3285
- exports.SUBSCRIPTION_CONFIG_ID = __webpack_exports__.SUBSCRIPTION_CONFIG_ID;
3286
- exports.SUBSCRIPTION_PACKAGE_ID = __webpack_exports__.SUBSCRIPTION_PACKAGE_ID;
3287
- exports.SUI_FULL_TYPE = __webpack_exports__.SUI_FULL_TYPE;
3288
- exports.SUI_METADATA_OBJECT_ID = __webpack_exports__.SUI_METADATA_OBJECT_ID;
3289
- exports.SUI_TYPE = __webpack_exports__.SUI_TYPE;
3290
- exports.SevenKAggregator = __webpack_exports__.SevenKAggregator;
3291
- exports.SubscriptionModule = __webpack_exports__.SubscriptionModule;
3292
- exports.SupportedAggregator = __webpack_exports__.SupportedAggregator;
3293
- exports.SupportedBondingCurve = __webpack_exports__.SupportedBondingCurve;
3294
- exports.TradeFeeOptions = __webpack_exports__.TradeFeeOptions;
3295
- exports.USDC_TOKEN_TYPE = __webpack_exports__.USDC_TOKEN_TYPE;
3296
- exports.adaptSuiClient = __webpack_exports__.adaptSuiClient;
3297
- exports.adaptTransaction = __webpack_exports__.adaptTransaction;
3298
- exports.addGasFee = __webpack_exports__.addGasFee;
3299
- exports.createCompatibleSuiClient = __webpack_exports__.createCompatibleSuiClient;
3300
- exports.getAmountAfterFee = __webpack_exports__.getAmountAfterFee;
3301
- exports.getCoinObjectIdsByAmount = __webpack_exports__.getCoinObjectIdsByAmount;
3302
- exports.getMemezPumpSDK = __webpack_exports__.getMemezPumpSDK;
3303
- exports.getMoveObject = __webpack_exports__.getMoveObject;
3304
- exports.getMoveObjectContent = __webpack_exports__.getMoveObjectContent;
3305
- exports.getNeededGasFee = __webpack_exports__.getNeededGasFee;
3306
- exports.getSplitCoinForTx = __webpack_exports__.getSplitCoinForTx;
3307
- exports.getSplitCoinsAfterFee = __webpack_exports__.getSplitCoinsAfterFee;
3308
- exports.isSuiCoinType = __webpack_exports__.isSuiCoinType;
3309
- exports.splitSuiCoinAfterFeeFromBuyTx = __webpack_exports__.splitSuiCoinAfterFeeFromBuyTx;
3310
- exports.splitSuiCoinAfterFeeFromSellTx = __webpack_exports__.splitSuiCoinAfterFeeFromSellTx;
3311
- for(var __rspack_i in __webpack_exports__) {
3312
- if(["ADMIN_CAP_ID","AftermathAggregator","AggregatorModule","AstrosAggregator","BASE_BPS","BLUEFIN_PACKAGE_ID","BOOSTING_PACKAGE_ID","BlastFunConstants","BlastFunCustomCalculation","BlastFunCustomTransaction","BlastFunPackage","BlastFunSDKCalculation","BlastFunSDKTransaction","BluefinTx","BoostingModule","Bps","CLOCK_OBJECT_ID","CONFIG_ID","CetusAggregator","CurveModule","DEFAULT_TRADE_FEE","DraftTransferTx","FlowXAggregator","MathUtils","MoonbagsCalculation","MoonbagsConstants","MoonbagsPackage","MoonbagsTransaction","NATIVE_USDC_TOKEN_TYPE","NoodlesPaySdk","NoodlesSdk","PAYMENT_COIN_TYPE","SUBSCRIPTION_ADMIN_CAP_ID","SUBSCRIPTION_CONFIG_ID","SUBSCRIPTION_PACKAGE_ID","SUI_FULL_TYPE","SUI_METADATA_OBJECT_ID","SUI_TYPE","SevenKAggregator","SubscriptionModule","SupportedAggregator","SupportedBondingCurve","TradeFeeOptions","USDC_TOKEN_TYPE","adaptSuiClient","adaptTransaction","addGasFee","createCompatibleSuiClient","getAmountAfterFee","getCoinObjectIdsByAmount","getMemezPumpSDK","getMoveObject","getMoveObjectContent","getNeededGasFee","getSplitCoinForTx","getSplitCoinsAfterFee","isSuiCoinType","splitSuiCoinAfterFeeFromBuyTx","splitSuiCoinAfterFeeFromSellTx"].indexOf(__rspack_i) === -1) {
3313
- exports[__rspack_i] = __webpack_exports__[__rspack_i];
3314
- }
3315
- }
3316
- Object.defineProperty(exports, '__esModule', { value: true });
1
+ "use strict";const __rslib_import_meta_url__="u"<typeof document?new(require("url".replace("",""))).URL("file:"+__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href;var types_TradeFeeOptions,constants_BlastFunConstants,package_MathUtils,package_Bps,package_BlastFunPackage,custom_calculation_BlastFunCustomCalculation,bluefin_BluefinTx,custom_transaction_BlastFunCustomTransaction,sdk_calculation_BlastFunSDKCalculation,sdk_transaction_BlastFunSDKTransaction,constants_MoonbagsConstants,package_MoonbagsPackage,calculation_MoonbagsCalculation,transaction_MoonbagsTransaction,__webpack_require__={};__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{addGasFee:()=>addGasFee,TradeFeeOptions:()=>types_TradeFeeOptions,SUBSCRIPTION_CONFIG_ID:()=>SUBSCRIPTION_CONFIG_ID,getMemezPumpSDK:()=>getMemezPumpSDK,DraftTransferTx:()=>DraftTransferTx,BlastFunSDKCalculation:()=>sdk_calculation_BlastFunSDKCalculation,MoonbagsConstants:()=>constants_MoonbagsConstants,NoodlesPaySdk:()=>NoodlesPaySdk,Bps:()=>package_Bps,ADMIN_CAP_ID:()=>ADMIN_CAP_ID,splitSuiCoinAfterFeeFromBuyTx:()=>splitSuiCoinAfterFeeFromBuyTx,getMoveObject:()=>getMoveObject,SUBSCRIPTION_PACKAGE_ID:()=>SUBSCRIPTION_PACKAGE_ID,MoonbagsCalculation:()=>calculation_MoonbagsCalculation,SUBSCRIPTION_ADMIN_CAP_ID:()=>SUBSCRIPTION_ADMIN_CAP_ID,getSplitCoinsAfterFee:()=>getSplitCoinsAfterFee,AstrosAggregator:()=>astros_AstrosAggregator,BlastFunSDKTransaction:()=>sdk_transaction_BlastFunSDKTransaction,CONFIG_ID:()=>CONFIG_ID,AftermathAggregator:()=>aftermath_AftermathAggregator,FlowXAggregator:()=>flowx_FlowXAggregator,adaptSuiClient:()=>adaptSuiClient,getNeededGasFee:()=>getNeededGasFee,AggregatorModule:()=>AggregatorModule,adaptTransaction:()=>adaptTransaction,createCompatibleSuiClient:()=>createCompatibleSuiClient,splitSuiCoinAfterFeeFromSellTx:()=>splitSuiCoinAfterFeeFromSellTx,SupportedAggregator:()=>common_SupportedAggregator,NATIVE_USDC_TOKEN_TYPE:()=>NATIVE_USDC_TOKEN_TYPE,BOOSTING_PACKAGE_ID:()=>BOOSTING_PACKAGE_ID,SUI_TYPE:()=>SUI_TYPE,USDC_TOKEN_TYPE:()=>USDC_TOKEN_TYPE,isSuiCoinType:()=>isSuiCoinType,MoonbagsPackage:()=>package_MoonbagsPackage,getCoinObjectIdsByAmount:()=>getCoinObjectIdsByAmount,SUI_FULL_TYPE:()=>SUI_FULL_TYPE,getAmountAfterFee:()=>getAmountAfterFee,BLUEFIN_PACKAGE_ID:()=>BLUEFIN_PACKAGE_ID,SubscriptionModule:()=>SubscriptionModule,MathUtils:()=>package_MathUtils,CLOCK_OBJECT_ID:()=>CLOCK_OBJECT_ID,CurveModule:()=>CurveModule,MoonbagsTransaction:()=>transaction_MoonbagsTransaction,BlastFunPackage:()=>package_BlastFunPackage,CetusAggregator:()=>cetus_CetusAggregator,DEFAULT_TRADE_FEE:()=>DEFAULT_TRADE_FEE,BlastFunCustomTransaction:()=>custom_transaction_BlastFunCustomTransaction,NoodlesSdk:()=>NoodlesSdk,BoostingModule:()=>BoostingModule,getMoveObjectContent:()=>getMoveObjectContent,getSplitCoinForTx:()=>getSplitCoinForTx,BlastFunCustomCalculation:()=>custom_calculation_BlastFunCustomCalculation,SupportedBondingCurve:()=>types_SupportedBondingCurve,PAYMENT_COIN_TYPE:()=>PAYMENT_COIN_TYPE,BASE_BPS:()=>1e4,BluefinTx:()=>bluefin_BluefinTx,SUI_METADATA_OBJECT_ID:()=>SUI_METADATA_OBJECT_ID,SevenKAggregator:()=>_7k_SevenKAggregator,BlastFunConstants:()=>constants_BlastFunConstants});const sdk_ts_namespaceObject=require("@7kprotocol/sdk-ts"),transactions_namespaceObject=require("@mysten/sui/transactions"),external_bignumber_js_namespaceObject=require("bignumber.js");var external_bignumber_js_default=__webpack_require__.n(external_bignumber_js_namespaceObject);class _7k_SevenKAggregator{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:a}){try{this._config.sevenKApiKey&&sdk_ts_namespaceObject.Config.setApiKey(this._config.sevenKApiKey);let i=a?a.tradeFeePercent:this._config.defaultTradeFee.tradeFeePercent;return await (0,sdk_ts_namespaceObject.getQuote)({tokenIn:t,tokenOut:n,amountIn:e.toString(),commissionBps:1e4*i})}catch(e){return null}}async getTransaction({walletAddress:e,completeRoute:t,slippage:n,tradeFee:a}){let i,o;a?(i=a.tradeFeePercent,o=a.tradeFeeRecipientAddress):(i=this._config.defaultTradeFee.tradeFeePercent,o=this._config.defaultTradeFee.tradeFeeRecipientAddress);let r=await (0,sdk_ts_namespaceObject.buildTx)({quoteResponse:t,slippage:n,accountAddress:e,commission:{partner:o,commissionBps:1e4*i}});return r.tx instanceof sdk_ts_namespaceObject.BluefinXTx?transactions_namespaceObject.Transaction.from(r.tx.txBytes).build({client:this._suiClient}):(r.tx.setSender(e),r.tx.build({client:this._suiClient}))}}(_7k_SevenKAggregator||(_7k_SevenKAggregator={})).toCommonTradeRoutes=function(e){let t=[];if(!e.routes||0===e.routes.length)return null;for(let n of e.routes){let e=[],a={};for(let t of n.hops){for(let e of t.pool.allTokens)a[e.address]=e.decimal;let n=a[t.tokenIn]??0,i=a[t.tokenOut]??0,o=BigInt(new(external_bignumber_js_default())(t.tokenInAmount).multipliedBy(10**n).toFixed(0,3)),r=BigInt(new(external_bignumber_js_default())(t.tokenOutAmount).multipliedBy(10**i).toFixed(0,3));e.push({poolAddress:t.poolId,coinIn:t.tokenIn,coinOut:t.tokenOut,amountIn:o,amountOut:r})}if(0===e.length)continue;let i=a[n.tokenIn]??0,o=a[n.tokenOut]??0,r=BigInt(new(external_bignumber_js_default())(n.tokenInAmount).multipliedBy(10**i).toFixed(0,3)),s=BigInt(new(external_bignumber_js_default())(n.tokenOutAmount).multipliedBy(10**o).toFixed(0,3));t.push({paths:e,coinIn:n.tokenIn,coinOut:n.tokenOut,amountIn:r,amountOut:s})}return 0===t.length?null:{coinIn:e.tokenIn,coinOut:e.tokenOut,amountIn:BigInt(e.swapAmountWithDecimal),amountOut:BigInt(e.returnAmountWithDecimal),routes:t}};const external_aftermath_ts_sdk_namespaceObject=require("aftermath-ts-sdk");class aftermath_AftermathAggregator{_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 external_aftermath_ts_sdk_namespaceObject.Aftermath(this._config.aftermathApiEndpoint):this._aftermathClient=new external_aftermath_ts_sdk_namespaceObject.Aftermath("MAINNET"),await this._aftermathClient.init(),this._config.aftermathApiKey){let e=external_aftermath_ts_sdk_namespaceObject.Helpers.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:a}){try{let i;i=a?{recipient:a.tradeFeeRecipientAddress,feePercentage:a.tradeFeePercent}:{recipient:this._config.defaultTradeFee.tradeFeeRecipientAddress,feePercentage:this._config.defaultTradeFee.tradeFeePercent};let o=await this.aftermathClient();return await o.Router().getCompleteTradeRouteGivenAmountIn({coinInAmount:e,coinInType:t,coinOutType:n,externalFee:i})}catch(e){return null}}async getTransaction({completeRoute:e,walletAddress:t,slippage:n}){let a=await this.aftermathClient(),i=await a.Router().getTransactionForCompleteTradeRoute({completeRoute:e,walletAddress:t,slippage:n,isSponsoredTx:!1});return i.setSender(t),i.build({client:this._suiClient})}}(aftermath_AftermathAggregator||(aftermath_AftermathAggregator={})).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}};const astros_aggregator_sdk_namespaceObject=require("@naviprotocol/astros-aggregator-sdk");function isSuiCoin(e){return"0x2::sui::SUI"===e||"0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI"===e}class astros_AstrosAggregator{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:a}){try{let i;return i=a?{fee:a.tradeFeePercent,receiverAddress:a.tradeFeeRecipientAddress}:{fee:this._config.defaultTradeFee.tradeFeePercent,receiverAddress:this._config.defaultTradeFee.tradeFeeRecipientAddress},await (0,astros_aggregator_sdk_namespaceObject.getQuote)(t,n,e,this._config.astrosApiKey,{byAmountIn:!0,serviceFee:i})}catch(e){return null}}returnMergedCoins(e,t,n){if(t.length<2)return e.object(t[0].coinObjectId);let a=0,i=[];t.sort((e,t)=>Number(t.balance)-Number(e.balance)).slice(1).forEach(e=>{a>=n||(a+=Number(e.balance),i.push(e.coinObjectId))});let o=t[0].coinObjectId;return e.mergeCoins(o,i),e.object(o)}async getTransaction({completeRoute:e,walletAddress:t,slippage:n,tradeFee:a}){let i,o;i=a?{fee:a.tradeFeePercent,receiverAddress:a.tradeFeeRecipientAddress}:{fee:this._config.defaultTradeFee.tradeFeePercent,receiverAddress:this._config.defaultTradeFee.tradeFeeRecipientAddress};let r=new(external_bignumber_js_default())(e.amount_out).multipliedBy(1-n-i.fee).toNumber(),s=new transactions_namespaceObject.Transaction;if(isSuiCoin(e.from))o=s.splitCoins(s.gas,[s.pure.u64(e.amount_in)]);else{let n=await (0,astros_aggregator_sdk_namespaceObject.getCoins)(this._suiClient,t,e.from),a=this.returnMergedCoins(s,n.data,Number.parseFloat(e.amount_in));o=s.splitCoins(a,[s.pure.u64(e.amount_in)])}let u=await (0,astros_aggregator_sdk_namespaceObject.buildSwapPTBFromQuote)(t,s,r,o,e,void 0,!1,this._config.astrosApiKey,{serviceFee:i});return s.transferObjects([u],t),s.setSender(t),s.build({client:this._suiClient})}}(astros_AstrosAggregator||(astros_AstrosAggregator={})).toCommonTradeRoutes=function(e,t,n){if(0===e.routes.length)return null;let a=[];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&&a.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===a.length?null:{coinIn:t,coinOut:n,amountIn:BigInt(e.amount_in),amountOut:BigInt(e.amount_out),routes:a}};const aggregator_sdk_namespaceObject=require("@cetusprotocol/aggregator-sdk"),external_bn_js_namespaceObject=require("bn.js");var external_bn_js_default=__webpack_require__.n(external_bn_js_namespaceObject);(types_TradeFeeOptions||(types_TradeFeeOptions={})).equals=function(e,t){return e.tradeFeePercent===t.tradeFeePercent&&e.tradeFeeRecipientAddress===t.tradeFeeRecipientAddress};class cetus_CetusAggregator{_config;_suiClient;_cetusClient;constructor(e,t){this._config=e,this._suiClient=t}cetusClient(e,t){return t&&!types_TradeFeeOptions.equals(t,this._config.defaultTradeFee)?new aggregator_sdk_namespaceObject.AggregatorClient({client:this._suiClient,overlayFeeReceiver:t.tradeFeeRecipientAddress,overlayFeeRate:t.tradeFeePercent,env:aggregator_sdk_namespaceObject.Env.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 aggregator_sdk_namespaceObject.AggregatorClient({client:this._suiClient,overlayFeeReceiver:this._config.defaultTradeFee.tradeFeeRecipientAddress,overlayFeeRate:this._config.defaultTradeFee.tradeFeePercent,env:aggregator_sdk_namespaceObject.Env.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:a}){try{let i=this.cetusClient(void 0,a);return await i.findRouters({from:t,target:n,amount:new(external_bn_js_default())(e.toString()),byAmountIn:!0})}catch(e){return null}}async getTransaction({completeRoute:e,walletAddress:t,slippage:n,tradeFee:a}){let i=this.cetusClient(t,a),o=new transactions_namespaceObject.Transaction;return o.setSender(t),await i.fastRouterSwap({router:e,txb:o,slippage:n}),o.build({client:this._suiClient})}}(cetus_CetusAggregator||(cetus_CetusAggregator={})).toCommonTradeRoutes=function(e,t,n){if(0===e.paths.length)return null;let a=[],i=[],o=[];for(let t=0;t<e.paths.length;t++){let n=e.paths[t],a={poolAddress:n.id,amountIn:BigInt(n.amountIn),amountOut:BigInt(n.amountOut),coinIn:n.from,coinOut:n.target};if(o.push(a),t===e.paths.length-1)i.push([...o]);else{let a=e.paths[t+1];n.target!==a.from&&(i.push([...o]),o=[])}}for(let e of i)0!==e.length&&a.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===a.length?null:{coinIn:t,coinOut:n,amountIn:BigInt(e.amountIn.toString(10)),amountOut:BigInt(e.amountOut.toString(10)),routes:a}};var common_SupportedAggregator=function(e){return e.ASTROS="ASTROS",e.AFTERMATH="AFTERMATH",e.SEVENK="7K",e.CETUS="CETUS",e.FLOWX="FLOWX",e}({});const sdk_namespaceObject=require("@flowx-finance/sdk");function getInputPercent(e){return 1e6*e}class flowx_FlowXAggregator{_config;_suiClient;constructor(e,t){this._config=e,this._suiClient=t}getCommission(e,t){let n,a;return t?(n=t.tradeFeePercent,a=t.tradeFeeRecipientAddress):(n=this._config.defaultTradeFee.tradeFeePercent,a=this._config.defaultTradeFee.tradeFeeRecipientAddress),new sdk_namespaceObject.Commission(a,new sdk_namespaceObject.Coin(e),sdk_namespaceObject.CommissionType.PERCENTAGE,getInputPercent(n),!0)}async getTradeRoute({coinInAmount:e,coinInType:t,coinOutType:n,tradeFee:a}){let i=new sdk_namespaceObject.AggregatorQuoter("mainnet",this._config.flowxApiKey);try{return await i.getRoutes({tokenIn:t,tokenOut:n,amountIn:e.toString(),commission:this.getCommission(t,a)})}catch(e){return null}}async getTransaction({walletAddress:e,completeRoute:t,slippage:n,tradeFee:a}){return new sdk_namespaceObject.TradeBuilder("mainnet",t.routes).sender(e).slippage(getInputPercent(n)).commission(this.getCommission(t.coinIn.coinType,a)).build().buildTransaction({client:this._suiClient}).then(t=>(t.setSender(e),t.build({client:this._suiClient})))}}(flowx_FlowXAggregator||(flowx_FlowXAggregator={})).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}},function(e){e.PACKAGE_ID_V4="0x7e6aa6e179466ab2814425a780b122575296d011119fa69d27f289f5a28814bd",e.MEMEZ_AV_OBJECT_ID="0x2319e3e76dfad73d8f4684bdbf42be4f32d8ce4521dd61becc8261dc918d82c0"}(constants_BlastFunConstants||(constants_BlastFunConstants={}));const tiny_invariant_namespaceObject=require("@minswap/tiny-invariant");var tiny_invariant_default=__webpack_require__.n(tiny_invariant_namespaceObject);async function getMoveObjectContent(e,t){return(await getMoveObject(e,t)).fields}async function getMoveObject(e,t){let n=await e.getObject({id:t,options:{showContent:!0}}),a=n.data?.content;return tiny_invariant_default()(a,"Pool object not found or has no content"),tiny_invariant_default()("moveObject"===a.dataType,"Object is not a Move object"),a}const BASE_BPS=1e4;function getSplitCoinsAfterFee(e,t){let n=BigInt(e),a=BigInt(1e4*Number(t));if(a===BigInt(0))return[n.toString()];let i=n*a/BigInt(1e4);return[(n-i).toString(),i.toString()]}function getAmountAfterFee(e,t){if(!t||0>=Number(t))return BigInt(e);let n=BigInt(e),a=BigInt(1e4*Number(t));if(a===BigInt(0))return n;let i=n*a/BigInt(1e4);return n-i}async function getNeededGasFee(e,t,n,a){let{effects:{gasUsed:i,status:o}}=await e.devInspectTransactionBlock({sender:n,transactionBlock:t});if("success"!==o.status)throw Error(`Transaction failed during dev inspect: ${o.error??""}`);let r=BigInt(i.computationCost)+BigInt(i.storageCost)-BigInt(i.storageRebate),s=BigInt(1e4*Number(a));return r*(BigInt(1e4)+s)/BigInt(1e4)}!function(e){(e.U64||(e.U64={})).mulDivUp=function(e,t,n){let a=BigInt(0);return e*t%n>BigInt(0)&&(a=BigInt(1)),e*t/n+a}}(package_MathUtils||(package_MathUtils={})),function(e){function t(e){return tiny_invariant_default()(BigInt(e)<=BigInt(1e4),"Bps overflow"),BigInt(e)}e.calcUp=function(e,t){let n,a=BigInt(e.pos0),i=BigInt(1e4);return n=a*t%i!==BigInt(0)?BigInt(1):BigInt(0),a*t/i+n},e.sub=function(e,t){return tiny_invariant_default()(BigInt(e.pos0)>=BigInt(t.pos0),"Bps underflow"),{pos0:(BigInt(e.pos0)-BigInt(t.pos0)).toString()}},e.value=function(e){return BigInt(e.pos0)},e.new_=function(e){return{pos0:t(e).toString()}},e.assertOverflow=t}(package_Bps||(package_Bps={})),function(e){var t,n;(e.MemezFun||(e.MemezFun={})).isSniperProtectedMemezFun=async function(e,t){return(await getMoveObjectContent(e,t)).public_key.length>0},(t=e.MemezFees||(e.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 a=e.fields.pos0.fields;if(BigInt(a.pos0)===BigInt(0))return BigInt(0);let i=package_Bps.calcUp(package_Bps.sub(a,n),t);if(t>=i)return i;throw Error(`Insufficient amount to cover fee. Required: ${i}, provided: ${t}`)}throw Error("Unknown fee variant")},t.calculateWithDiscount=function(e,t,n){if("Value"===e.variant)return BigInt(e.fields.pos0);if("Percentage"===e.variant){let a=e.fields.pos0.fields;return package_Bps.calcUp(package_Bps.sub(a,t),n)}throw Error("Unknown fee variant")},(e.MemezBurner||(e.MemezBurner={})).calculate=function(e,t){if(package_Bps.value(e.fee.fields)===BigInt(0)||t===BigInt(0)||t>=BigInt(e.target_liquidity))return package_Bps.new_(0);let n=BigInt(1e4);return package_Bps.new_(package_MathUtils.U64.mulDivUp(package_Bps.value(e.fee.fields),package_MathUtils.U64.mulDivUp(t,n,BigInt(e.target_liquidity)),n))},(n=e.MemezPump||(e.MemezPump={})).getPumpState=async function(e,t){return await getMoveObjectContent(e,t.inner_state)},n.pump=function(t,n){let a=t.constant_product.fields,i=e.MemezFees.takeWithDiscount(a.quote_swap_fee,n,a.quote_referrer_fee.fields),o=n-i,r=BigInt(a.meme_balance),s=BigInt(a.quote_balance),u=r*o/(BigInt(a.virtual_liquidity)+s+o),c=e.MemezFees.takeWithDiscount(a.meme_swap_fee,u,a.meme_referrer_fee.fields);return u-c},n.dump=function(t,n){let a=t.constant_product.fields,i=e.MemezFees.takeWithDiscount(a.meme_swap_fee,n,a.meme_referrer_fee.fields),o=n-i,r=BigInt(a.meme_balance),s=BigInt(a.quote_balance),u=BigInt(a.virtual_liquidity),c=e.MemezBurner.calculate(a.burner.fields,s),_=package_Bps.calcUp(c,o),l=o-(package_Bps.value(c)!==BigInt(0)?_:BigInt(0)),d=(u+s)*l/(r+l);d>s&&(d=s);let g=e.MemezFees.takeWithDiscount(a.quote_swap_fee,d,a.quote_referrer_fee.fields);return d-g}}(package_BlastFunPackage||(package_BlastFunPackage={})),function(e){e.getCurveAmountAfterBuy=async function(e,t){let{suiAmount:n,poolId:a,frontendFee:i}=e,o=await getMoveObjectContent(t,a),r=await package_BlastFunPackage.MemezPump.getPumpState(t,o);return n=getAmountAfterFee(n,i),package_BlastFunPackage.MemezPump.pump(r,n)},e.getSuiAmountAfterSell=async function(e,t){let{curveAmount:n,poolId:a,frontendFee:i}=e,o=await getMoveObjectContent(t,a),r=await package_BlastFunPackage.MemezPump.getPumpState(t,o);return getAmountAfterFee(package_BlastFunPackage.MemezPump.dump(r,n),i)}}(custom_calculation_BlastFunCustomCalculation||(custom_calculation_BlastFunCustomCalculation={}));const SUI_TYPE="0x2::sui::SUI",SUI_FULL_TYPE="0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI",USDC_TOKEN_TYPE="0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN",NATIVE_USDC_TOKEN_TYPE="0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC",SUI_METADATA_OBJECT_ID="0x9258181f5ceac8dbffb7030890243caed69a9599d2886d957a9cb7656af3bdb3",CLOCK_OBJECT_ID="0x0000000000000000000000000000000000000000000000000000000000000006";function isSuiCoinType(e){return e===SUI_TYPE||e===SUI_FULL_TYPE}const utils_namespaceObject=require("@mysten/sui/utils"),orderByKey=(e,t,n)=>{let a;if(e?.length){do{a=!1;for(let i=0;i<e.length-1;i++){let o=BigInt(e[i][t]),r=BigInt(e[i+1][t]);if("desc"===n?o<r:o>r){let t=e[i];e[i]=e[i+1],e[i+1]=t,a=!0}}}while(a);return e}},getCoinObjectIdsByAmount=async(e,t,n,a)=>{let i,o=[],r=!0;for(;r;)try{let n=await e.getCoins({owner:t,coinType:a,cursor:i});o=[...o,...n.data],r=n.hasNextPage,i=n.nextCursor}catch(e){console.error("Error fetching data:",e),r=!1}let s=orderByKey(o.map(e=>({...e,balance:e.balance})),"balance","desc")??[],u="0",c=[],_=[];for(let e of s)if(u=(BigInt(e.balance)+BigInt(u)).toString(10),c.push(e.coinObjectId),_.push(e),BigInt(u)>=BigInt(n))break;return{objectIds:c,balance:u,objectCoins:_}};async function getSplitCoinForTx(e,t){let{account:n,amount:a,splits:i,coinType:o,inheritTx:r,inspecTransaction:s,isSponsored:u=!1}=e,c=r??new transactions_namespaceObject.Transaction,{objectIds:_}=await getCoinObjectIdsByAmount(t,n,a,o),l=_[0];if((0,utils_namespaceObject.normalizeStructTag)(o)===(0,utils_namespaceObject.normalizeStructTag)(SUI_FULL_TYPE)&&!u){let e;return s?(_.length>1&&c.mergeCoins(c.object(l),_.slice(1).map(e=>c.object(e))),e=c.splitCoins(c.object(l),i)):e=c.splitCoins(c.gas,i),{tx:c,coinData:e}}_.length>1&&c.mergeCoins(c.object(l),_.slice(1).map(e=>c.object(e)));let d=c.splitCoins(c.object(l),i);return{tx:c,coinData:d}}const BLUEFIN_PACKAGE_ID="0x62412b7268c35f3808336aee57a52836501f40b8ba5d936f8ad275e672befd04";async function splitSuiCoinAfterFeeFromBuyTx(e,t){let n,a,{inputAmount:i,accountAddress:o,frontendFee:r,frontendFeeRecipient:s,extendTx:u,isSponsored:c}=e;tiny_invariant_default()(e.inCoinType===SUI_FULL_TYPE||e.inCoinType===SUI_TYPE,"Input must be SUI");let{tx:_,coinIn:l}=u||{},d=getSplitCoinsAfterFee(i,r||"0"),g=_||new transactions_namespaceObject.Transaction;if(l)n=g.splitCoins(l,d),bluefin_BluefinTx.transferOrDestroyZeroCoin(g,SUI_FULL_TYPE,l,o);else{let{coinData:e}=await getSplitCoinForTx({account:o,amount:i,splits:d,coinType:SUI_FULL_TYPE,inheritTx:g,isSponsored:c||!1},t);n=e}if(r&&s){let[e,t]=n;a=e,g.transferObjects([t],g.pure.address(s||o))}else[a]=n;return{tx:g,coinOut:a}}async function splitSuiCoinAfterFeeFromSellTx(e,t,n){if(tiny_invariant_default()(t.outCoinType===SUI_FULL_TYPE||t.outCoinType===SUI_TYPE,"Output must be SUI"),0>=Number(t.frontendFee||0))return{tx:e,coinOut:n};let a=e.moveCall({target:"0x2::coin::value",typeArguments:[t.outCoinType],arguments:[n]}),i=e.moveCall({target:`${BLUEFIN_PACKAGE_ID}::math::mul_div_u64`,typeArguments:[],arguments:[a,e.pure.u64(BigInt(1e4*Number(t.frontendFee||"0"))),e.pure.u64(BigInt(1e4))]}),o=e.moveCall({target:"0x2::coin::split",typeArguments:[t.outCoinType],arguments:[n,i]});return e.transferObjects([o],e.pure.address(t.frontendFeeRecipient||t.accountAddress)),{tx:e,coinOut:n}}(bluefin_BluefinTx||(bluefin_BluefinTx={})).transferOrDestroyZeroCoin=function(e,t,n,a){e.moveCall({target:`${BLUEFIN_PACKAGE_ID}::utils::transfer_or_destroy`,typeArguments:[t],arguments:[n,e.pure.address(a)]})},function(e){async function t(e){let t=e||new transactions_namespaceObject.Transaction;return t.moveCall({target:`${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_allowed_versions::get_allowed_versions`,arguments:[t.object(constants_BlastFunConstants.MEMEZ_AV_OBJECT_ID)],typeArguments:[]})}e.getAllowedVersions=t,e.buildBuyTx=async function(e,n){tiny_invariant_default()(!await package_BlastFunPackage.MemezFun.isSniperProtectedMemezFun(n,e.poolId),"This coin is a sniper protected coin, please use the Blast Fun website to trade it.");let{tx:a,coinOut:i}=await splitSuiCoinAfterFeeFromBuyTx(e,n);tiny_invariant_default()(i,"Coin out is required");let o=a.moveCall({target:`${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::pump`,typeArguments:[e.outCoinType,SUI_FULL_TYPE],arguments:[a.object(e.poolId),i,a.pure.vector("address",[]),a.pure.vector("vector<u8>",[]),a.pure.u64(e.minAmountOut),await t(a)]});return{tx:a,coinOut:o}},e.buildSellTx=async function(e,n){tiny_invariant_default()(e.outCoinType===SUI_FULL_TYPE||e.outCoinType===SUI_TYPE,"Output must be SUI");let a=await getMoveObjectContent(n,e.poolId),{tx:i,coinData:o}=await getSplitCoinForTx({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},n),[r]=o,[s]=i.moveCall({target:`${constants_BlastFunConstants.PACKAGE_ID_V4}::memez_pump::dump`,typeArguments:[e.inCoinType,e.outCoinType],arguments:[i.object(e.poolId),i.object(a.ipx_meme_coin_treasury),r,i.pure.vector("address",[]),i.pure.u64(e.minAmountOut),await t(i)]});return await splitSuiCoinAfterFeeFromSellTx(i,e,s)}}(custom_transaction_BlastFunCustomTransaction||(custom_transaction_BlastFunCustomTransaction={}));const memez_fun_sdk_namespaceObject=require("@interest-protocol/memez-fun-sdk"),sui_core_sdk_namespaceObject=require("@interest-protocol/sui-core-sdk"),client_namespaceObject=require("@mysten/sui/client"),payload={network:sui_core_sdk_namespaceObject.Network.MAINNET,fullNodeUrl:(0,client_namespaceObject.getFullnodeUrl)("mainnet")},memezPump=new memez_fun_sdk_namespaceObject.MemezPumpSDK(payload);function getMemezPumpSDK(){return memezPump}async function addGasFee(e,t){let{inheritTx:n,sender:a,feeAmount:i,suiInputAmount:o}=e,r=n||new transactions_namespaceObject.Transaction;r.setGasBudget(i);let{objectCoins:s}=await getCoinObjectIdsByAmount(t,a,(BigInt(o||"0")+i).toString(),SUI_FULL_TYPE);return r.setGasPayment(s.map(e=>({objectId:e.coinObjectId,version:e.version,digest:e.digest}))),r}!function(e){e.getCurveAmountAfterBuy=async function(e){let{suiAmount:t,poolId:n,frontendFee:a}=e;t=getAmountAfterFee(t,a);let{memeAmountOut:i}=await getMemezPumpSDK().quotePump({pool:n,amount:t});return i},e.getSuiAmountAfterSell=async function(e){let{curveAmount:t,poolId:n,frontendFee:a}=e,{quoteAmountOut:i}=await getMemezPumpSDK().quoteDump({pool:n,amount:t});return getAmountAfterFee(i,a)}}(sdk_calculation_BlastFunSDKCalculation||(sdk_calculation_BlastFunSDKCalculation={})),function(e){async function t(e,t){let{tx:n,coinOut:a}=await splitSuiCoinAfterFeeFromBuyTx(e,t);tiny_invariant_default()(a,"Coin out is required");let{memeCoin:i,tx:o}=await getMemezPumpSDK().pump({pool:e.poolId,quoteCoin:a,minAmountOut:e.minAmountOut,tx:n});return{tx:o,coinOut:i}}async function n(e,t){tiny_invariant_default()(isSuiCoinType(e.outCoinType),"Output must be SUI");let{tx:n,coinData:a}=await getSplitCoinForTx({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},t),[i]=a,{quoteCoin:o,tx:r}=await getMemezPumpSDK().dump({pool:e.poolId,memeCoin:i,tx:n,minAmountOut:e.minAmountOut});return await splitSuiCoinAfterFeeFromSellTx(r,e,o)}e.buildBuyTx=t,e.buildSellTx=n,e.getBuyTransaction=async function({coinInAmount:e,coinInType:n,coinOutType:a,poolId:i,slippage:o,walletAddress:r,tradeFee:s},u){tiny_invariant_default()(isSuiCoinType(n),"coinInType must be SUI for buy transaction"),tiny_invariant_default()(a!==n,"coinOutType must be different from coinInType"),tiny_invariant_default()(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),tiny_invariant_default()(e>0,"coinInAmount must be greater than 0");let c=await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({poolId:i,suiAmount:e,frontendFee:s?s.tradeFeePercent:void 0}),_=BigInt(new(external_bignumber_js_default())(c.toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await t({accountAddress:r,inCoinType:n,outCoinType:a,inputAmount:e.toString(),minAmountOut:_.toString(),poolId:i,frontendFee:s?s.tradeFeePercent:void 0,frontendFeeRecipient:s?s.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},u);tiny_invariant_default()(d,"Coin out is required"),l.transferObjects([d],l.pure.address(r)),l.setSender(r);let g=await getNeededGasFee(u,l,r,0);return(l=await addGasFee({inheritTx:l,sender:r,feeAmount:g,suiInputAmount:e},u)).build({client:u})},e.getSellTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:a,poolId:i,slippage:o,walletAddress:r,tradeFee:s},u){tiny_invariant_default()(isSuiCoinType(a),"coinOutType must be SUI for sell transaction"),tiny_invariant_default()(a!==t,"coinOutType must be different from coinInType"),tiny_invariant_default()(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),tiny_invariant_default()(e>0,"coinInAmount must be greater than 0");let c=await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({poolId:i,curveAmount:e,frontendFee:s?s.tradeFeePercent:void 0}),_=BigInt(new(external_bignumber_js_default())(c.toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await n({accountAddress:r,inCoinType:t,outCoinType:a,inputAmount:e.toString(),minAmountOut:_.toString(),poolId:i,frontendFee:s?s.tradeFeePercent:void 0,frontendFeeRecipient:s?s.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},u);tiny_invariant_default()(d,"Coin out is required"),l.transferObjects([d],l.pure.address(r)),l.setSender(r);let g=await getNeededGasFee(u,l,r,0);return(l=await addGasFee({inheritTx:l,sender:r,feeAmount:g},u)).build({client:u})}}(sdk_transaction_BlastFunSDKTransaction||(sdk_transaction_BlastFunSDKTransaction={}));var types_SupportedBondingCurve=function(e){return e.BLAST_FUN="BLAST_FUN",e.MOONBAGS="MOONBAGS",e}({});function adaptSuiClient(e){return e}function adaptTransaction(e){return e}function createCompatibleSuiClient(e){return new Proxy(e,{get(e,t){let n=e[t];return"function"==typeof n?n.bind(e):n}})}!function(e){e.PACKAGE_ID="0xb8df325010942634a4afb3db3901ee215546af43a4ec4af781e7213b0bba7290",e.CONFIG_OBJECT_ID="0x74aecf86067c6913960ba4925333aefd2b1f929cafca7e21fd55a8f244b70499",e.LOCK_CONFIG_OBJECT_ID="0xfb09822d9808980abd04c51321adb850701f5f55535c6206658ef4d910c3e9be",e.BURN_MANAGER_OBJECT_ID="0x1d94aa32518d0cb00f9de6ed60d450c9a2090761f326752ffad06b2e9404f845",e.POOLS_OBJECT_ID="0xf699e7f2276f5c9a75944b37a0c5b5d9ddfd2471bf6242483b03ab2887d198d0",e.GLOBAL_CONFIG_OBJECT_ID="0xdaa46292632c3c4d8f31f23ea0f9b36a28ff3677e9684980e4438403a67a3d8f",e.FEE_DENOMINATOR=BigInt(1e4)}(constants_MoonbagsConstants||(constants_MoonbagsConstants={})),function(e){var t,n;(t=e.Curves||(e.Curves={})).calculateAddLiquidityCost=function(e,t,n){return e*t/(t-n)-e},t.calculateRemoveLiquidityReturn=function(e,t,n){return t-e*t/(e+n)},t.calculateTokenAmountReceived=function(e,t,n){return t-e*t/(e+n)},(n=e.Moonbags||(e.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)},n.buyExactInReturnsWithLock=function(t){let{inputAmount:n,amountIn:a,pool:i,config:o,dynamicVirtualTokenReserves:r}=t,s=BigInt(i.virtual_sui_reserves),u=BigInt(i.virtual_token_reserves),c=BigInt(i.remain_token_reserves.fields.balance),_=e.Curves.calculateRemoveLiquidityReturn(s,u,a),l=u-(r||c),d=_,g=a;_>l&&(d=l,g=e.Curves.calculateAddLiquidityCost(s,u,l)+BigInt(1));let p=g*BigInt(o.platform_fee)/constants_MoonbagsConstants.FEE_DENOMINATOR;return tiny_invariant_default()(n>=g+p,"Input amount is less than used SUI + fee"),{receivedCurve:d,receivedSui:n-g-p}},n.sellReturns=function(t){let{amountIn:n,pool:a,config:i}=t,o=BigInt(a.virtual_sui_reserves),r=BigInt(a.virtual_token_reserves),s=BigInt(a.real_sui_reserves.fields.balance),u=e.Curves.calculateRemoveLiquidityReturn(r,o,n);u>s&&(u=s);let c=u*BigInt(i.platform_fee)/constants_MoonbagsConstants.FEE_DENOMINATOR,_=u-c;return{receivedCurve:BigInt(0),receivedSui:_}}}(package_MoonbagsPackage||(package_MoonbagsPackage={})),function(e){e.getCurveAmountAfterBuy=async function(e,t){let{suiAmount:n,poolId:a,frontendFee:i}=e,[o,r,s]=await Promise.all([getMoveObjectContent(t,a),getMoveObjectContent(t,constants_MoonbagsConstants.CONFIG_OBJECT_ID),package_MoonbagsPackage.Moonbags.getDynamicVirtualTokenReserves(t,a)]);void 0!==i&&(n=getAmountAfterFee(n,i));let u=n*constants_MoonbagsConstants.FEE_DENOMINATOR/(constants_MoonbagsConstants.FEE_DENOMINATOR+BigInt(r.platform_fee)),{receivedCurve:c}=package_MoonbagsPackage.Moonbags.buyExactInReturnsWithLock({inputAmount:n,amountIn:u,pool:o,config:r,dynamicVirtualTokenReserves:s});return c},e.getSuiAmountAfterSell=async function(e,t){let{curveAmount:n,poolId:a,frontendFee:i}=e,[o,r]=await Promise.all([getMoveObjectContent(t,a),getMoveObjectContent(t,constants_MoonbagsConstants.CONFIG_OBJECT_ID)]),{receivedSui:s}=package_MoonbagsPackage.Moonbags.sellReturns({amountIn:n,pool:o,config:r});return void 0!==i?getAmountAfterFee(s,i):s},e.getUsedSuiForTx=async function(e,t){let{suiAmount:n,frontendFee:a}=e,i=await getMoveObjectContent(t,constants_MoonbagsConstants.CONFIG_OBJECT_ID);return void 0!==a&&(n=getAmountAfterFee(n,a)),n*constants_MoonbagsConstants.FEE_DENOMINATOR/(constants_MoonbagsConstants.FEE_DENOMINATOR+BigInt(i.platform_fee))}}(calculation_MoonbagsCalculation||(calculation_MoonbagsCalculation={})),function(e){async function t(e,t){let{tx:n,coinOut:a}=await splitSuiCoinAfterFeeFromBuyTx(e,t);tiny_invariant_default()(a,"Coin out is required");let i=await calculation_MoonbagsCalculation.getUsedSuiForTx({suiAmount:BigInt(e.inputAmount),frontendFee:e.frontendFee},t),[o,r]=n.moveCall({target:`${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::buy_exact_in_returns_with_lock`,typeArguments:[e.outCoinType],arguments:[n.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),n.object(constants_MoonbagsConstants.LOCK_CONFIG_OBJECT_ID),a,n.pure.u64(i),n.pure.u64(e.minAmountOut),n.object(constants_MoonbagsConstants.BURN_MANAGER_OBJECT_ID),n.object(constants_MoonbagsConstants.POOLS_OBJECT_ID),n.object(constants_MoonbagsConstants.GLOBAL_CONFIG_OBJECT_ID),n.object(SUI_METADATA_OBJECT_ID),n.object(CLOCK_OBJECT_ID)]});return bluefin_BluefinTx.transferOrDestroyZeroCoin(n,SUI_FULL_TYPE,o,e.accountAddress),{tx:n,coinOut:r}}async function n(e,t){tiny_invariant_default()(isSuiCoinType(e.outCoinType),"Output must be SUI");let{tx:n,coinData:a}=await getSplitCoinForTx({amount:e.inputAmount,coinType:e.inCoinType,inheritTx:e.extendTx?.tx,account:e.accountAddress,splits:[e.inputAmount]},t),[i]=a,[o,r]=n.moveCall({target:`${constants_MoonbagsConstants.PACKAGE_ID}::moonbags::sell_returns`,typeArguments:[e.inCoinType],arguments:[n.object(constants_MoonbagsConstants.CONFIG_OBJECT_ID),i,n.pure.u64(e.minAmountOut),n.object(CLOCK_OBJECT_ID)]});return bluefin_BluefinTx.transferOrDestroyZeroCoin(n,e.inCoinType,r,e.accountAddress),await splitSuiCoinAfterFeeFromSellTx(n,e,o)}e.buildBuyTx=t,e.buildSellTx=n,e.getBuyTransaction=async function({coinInAmount:e,coinInType:n,coinOutType:a,poolId:i,slippage:o,walletAddress:r,tradeFee:s},u){tiny_invariant_default()(isSuiCoinType(n),"coinInType must be SUI for buy transaction"),tiny_invariant_default()(a!==n,"coinOutType must be different from coinInType"),tiny_invariant_default()(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),tiny_invariant_default()(e>0,"coinInAmount must be greater than 0");let c=await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({poolId:i,suiAmount:e,frontendFee:s?s.tradeFeePercent:void 0},u),_=BigInt(new(external_bignumber_js_default())(c.toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await t({accountAddress:r,inCoinType:n,outCoinType:a,inputAmount:e.toString(),minAmountOut:_.toString(),poolId:i,frontendFee:s?s.tradeFeePercent:void 0,frontendFeeRecipient:s?s.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},u);tiny_invariant_default()(d,"Coin out is required"),l.transferObjects([d],l.pure.address(r)),l.setSender(r);let g=await getNeededGasFee(u,l,r,0);return(l=await addGasFee({inheritTx:l,sender:r,feeAmount:g,suiInputAmount:e},u)).build({client:u})},e.getSellTransaction=async function({coinInAmount:e,coinInType:t,coinOutType:a,poolId:i,slippage:o,walletAddress:r,tradeFee:s},u){tiny_invariant_default()(isSuiCoinType(a),"coinOutType must be SUI for sell transaction"),tiny_invariant_default()(a!==t,"coinOutType must be different from coinInType"),tiny_invariant_default()(o>=0&&o<1,"slippage must be between 0 (inclusive) and 1 (exclusive)"),tiny_invariant_default()(e>0,"coinInAmount must be greater than 0");let c=await calculation_MoonbagsCalculation.getSuiAmountAfterSell({poolId:i,curveAmount:e,frontendFee:s?s.tradeFeePercent:void 0},u),_=BigInt(new(external_bignumber_js_default())(c.toString()).multipliedBy(1-o).toFixed(0,3)),{tx:l,coinOut:d}=await n({accountAddress:r,inCoinType:t,outCoinType:a,inputAmount:e.toString(),minAmountOut:_.toString(),poolId:i,frontendFee:s?s.tradeFeePercent:void 0,frontendFeeRecipient:s?s.tradeFeeRecipientAddress:void 0,extendTx:void 0,isSponsored:!1},u);tiny_invariant_default()(d,"Coin out is required"),l.transferObjects([d],l.pure.address(r)),l.setSender(r);let g=await getNeededGasFee(u,l,r,0);return(l=await addGasFee({inheritTx:l,sender:r,feeAmount:g},u)).build({client:u})}}(transaction_MoonbagsTransaction||(transaction_MoonbagsTransaction={}));class AggregatorModule{sdk;_astrosAggregator;_aftermathAggregator;_sevenkAggregator;_cetusAggregator;_flowXAggregator;constructor(e){this.sdk=e,this._astrosAggregator=new astros_AstrosAggregator({defaultTradeFee:e.options.tradeFee,astrosApiKey:e.options.astrosApiKey},e.suiClient),this._aftermathAggregator=new aftermath_AftermathAggregator({defaultTradeFee:e.options.tradeFee,aftermathApiKey:e.options.aftermathApiKey,aftermathApiEndpoint:e.options.aftermathApiEndpoint},e.suiClient),this._sevenkAggregator=new _7k_SevenKAggregator({defaultTradeFee:e.options.tradeFee,sevenKApiKey:e.options.sevenKApiKey},e.suiClient),this._cetusAggregator=new cetus_CetusAggregator({defaultTradeFee:e.options.tradeFee,cetusApiKey:e.options.cetusApiKey,cetusApiEndpoint:e.options.cetusApiEndpoint,cetusPartnerId:e.options.cetusPartnerId},e.suiClient),this._flowXAggregator=new flowx_FlowXAggregator({defaultTradeFee:e.options.tradeFee,flowxApiKey:e.options.flowxApiKey},e.suiClient)}get astrosAggregator(){return this._astrosAggregator}get aftermathAggregator(){return this._aftermathAggregator}get sevenkAggregator(){return this._sevenkAggregator}get cetusAggregator(){return this._cetusAggregator}get flowXAggregator(){return this._flowXAggregator}async getTradeRoute(e,t){let n;switch(e){case common_SupportedAggregator.ASTROS:{let e,a=await this._astrosAggregator.getTradeRoute(t);if(!a)return null;let i=astros_AstrosAggregator.toCommonTradeRoutes(a,t.coinInType,t.coinOutType);if(!i)return null;e=t.tradeFee?t.tradeFee.tradeFeePercent:this.sdk.options.tradeFee.tradeFeePercent,i.amountOut=BigInt(new(external_bignumber_js_default())(a.amount_out).multipliedBy(1-e).toFixed(0,3)),n={route:i,aggregatorRoute:a};break}case common_SupportedAggregator.AFTERMATH:{let e=await this._aftermathAggregator.getTradeRoute(t);if(!e)return null;let a=aftermath_AftermathAggregator.toCommonTradeRoutes(e);if(!a)return null;n={route:a,aggregatorRoute:e};break}case common_SupportedAggregator.SEVENK:{let e=await this._sevenkAggregator.getTradeRoute(t);if(!e)return null;let a=_7k_SevenKAggregator.toCommonTradeRoutes(e);if(!a)return null;n={route:a,aggregatorRoute:e};break}case common_SupportedAggregator.CETUS:{let e=await this._cetusAggregator.getTradeRoute(t);if(!e)return null;let a=cetus_CetusAggregator.toCommonTradeRoutes(e,t.coinInType,t.coinOutType);if(!a)return null;n={route:a,aggregatorRoute:e};break}case common_SupportedAggregator.FLOWX:{let e=await this._flowXAggregator.getTradeRoute(t);if(!e)return null;let a=flowx_FlowXAggregator.toCommonTradeRoutes(e);if(!a)return null;n={route:a,aggregatorRoute:e}}}return n}async getTransactionByRoute(e,t){switch(e){case common_SupportedAggregator.ASTROS:return this._astrosAggregator.getTransaction({walletAddress:t.walletAddress,completeRoute:t.completeRoute,slippage:t.slippage,tradeFee:t.tradeFee});case common_SupportedAggregator.AFTERMATH:return this._aftermathAggregator.getTransaction({walletAddress:t.walletAddress,completeRoute:t.completeRoute,slippage:t.slippage});case common_SupportedAggregator.SEVENK:return this._sevenkAggregator.getTransaction({walletAddress:t.walletAddress,completeRoute:t.completeRoute,slippage:t.slippage,tradeFee:t.tradeFee});case common_SupportedAggregator.CETUS:return this._cetusAggregator.getTransaction({walletAddress:t.walletAddress,completeRoute:t.completeRoute,slippage:t.slippage,tradeFee:t.tradeFee});case common_SupportedAggregator.FLOWX:return this._flowXAggregator.getTransaction({walletAddress:t.walletAddress,completeRoute:t.completeRoute,slippage:t.slippage,tradeFee:t.tradeFee})}}async getTradeTransaction(e,t){let n=await this.getTradeRoute(e,{coinInAmount:t.coinInAmount,coinInType:t.coinInType,coinOutType:t.coinOutType,tradeFee:t.tradeFee});if(!n)return null;let a=await this.getTransactionByRoute(e,{walletAddress:t.walletAddress,completeRoute:n.aggregatorRoute,slippage:t.slippage,tradeFee:t.tradeFee});return{route:n.route,aggregatorRoute:n.aggregatorRoute,transaction:a}}async getTradeTransactionWithBestRate(e){let t=Object.keys(common_SupportedAggregator),n=await Promise.all(t.map(async t=>{try{return await this.getTradeRoute(t,e)}catch{return null}})),a=null,i=null;for(let e=0;e<n.length;e++){let o=n[e],r=t[e];if(o&&(!a||o.route.amountOut>a.route.amountOut)){a=o,i=r;continue}}if(!a||!i)return null;let o=await this.getTransactionByRoute(i,{walletAddress:e.walletAddress,completeRoute:a.aggregatorRoute,slippage:e.slippage,tradeFee:e.tradeFee});return{route:a.route,aggregatorRoute:a.aggregatorRoute,transaction:o}}async getAmountOut(e,t){let n=await this.getTradeRoute(e,t);return n?n.route.amountOut:null}async getBestAmountOut(e){let t=Object.keys(common_SupportedAggregator),n=null,a=null;for(let i of t){let t=await this.getAmountOut(i,e);null!==t&&(null===n||t>n)&&(n=t,a=i)}return null===n||null===a?null:{amountOut:n,aggregator:a}}}const BOOSTING_PACKAGE_ID="0x25fa0eb553dd69fa6a8028f73a38f1df7f289fa88a58ed3d7dc5a5360155bb19",CONFIG_ID="0x8b1a8ac6e34688cd8f8f8e5fefa9d5fb9e1ff74d2f132f8e208ae5ac9cc530bb",ADMIN_CAP_ID="0x13d101f44a0710a5475bec5f492a87b80e03d92d1cf540f26096f65850b23d26";class BoostingModule{sdk;constructor(e){this.sdk=e}async getConfig(){let e=await this.sdk.suiClient.getObject({id:CONFIG_ID,options:{showContent:!0}});tiny_invariant_default()(e.data?.content,"Config object not found or has no content"),tiny_invariant_default()(e.data?.content.dataType==="moveObject","Config object is not a Move object");let t=e.data.content.fields,n=t.id.id,a=t.fee_receiver,i=t.tiers.fields.contents,o={};for(let e of i){let t=e.fields.key,n=e.fields.value.fields.duration,a=e.fields.value.fields.amount,i=e.fields.value.fields.point,r=e.fields.value.fields.original_amount;o[t]={duration:BigInt(n),amount:BigInt(a),point:BigInt(i),originalAmount:BigInt(r)}}return{id:n,receiverAddress:a,tiers:o}}async buildPayBoostingTx({walletAddress:e,tierId:t,boostingCoinType:n,currentTx:a}){let i=await this.getConfig();tiny_invariant_default()(t in i.tiers,"Invalid tier ID");let o=i.tiers[t].amount,r=a||new transactions_namespaceObject.Transaction,s=r.splitCoins(r.gas,[r.pure.u64(o)]);r.moveCall({target:`${BOOSTING_PACKAGE_ID}::boosting::pay`,typeArguments:[(0,utils_namespaceObject.normalizeStructTag)(n)],arguments:[r.object(CONFIG_ID),r.pure.u64(t),s]}),r.setSender(e);let u=await getNeededGasFee(this.sdk.suiClient,r,e,0);return addGasFee({inheritTx:r,sender:e,feeAmount:u},this.sdk.suiClient)}async buildAddTierTx({adminAddress:e,tierId:t,duration:n,point:a,originalAmount:i,amount:o,currentTx:r}){let s=r||new transactions_namespaceObject.Transaction;s.moveCall({target:`${BOOSTING_PACKAGE_ID}::config::add_tier`,typeArguments:[],arguments:[s.object(CONFIG_ID),s.object(ADMIN_CAP_ID),s.pure.u64(t),s.pure.u64(a),s.pure.u64(n),s.pure.u64(i),s.pure.u64(o)]}),s.setSender(e);let u=await getNeededGasFee(this.sdk.suiClient,s,e,0);return addGasFee({inheritTx:s,sender:e,feeAmount:u},this.sdk.suiClient)}async buildUpdateTierTx({adminAddress:e,tierId:t,duration:n,amount:a,originalAmount:i,point:o,currentTx:r}){let s=r||new transactions_namespaceObject.Transaction;s.moveCall({target:`${BOOSTING_PACKAGE_ID}::config::update_tier`,typeArguments:[],arguments:[s.object(CONFIG_ID),s.object(ADMIN_CAP_ID),s.pure.u64(t),s.pure.u64(n),s.pure.u64(a),s.pure.u64(o),s.pure.u64(i)]}),s.setSender(e);let u=await getNeededGasFee(this.sdk.suiClient,s,e,0);return addGasFee({inheritTx:s,sender:e,feeAmount:u},this.sdk.suiClient)}async buildRemoveTierTx({adminAddress:e,tierId:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${BOOSTING_PACKAGE_ID}::config::remove_tier`,typeArguments:[],arguments:[a.object(CONFIG_ID),a.object(ADMIN_CAP_ID),a.pure.u64(t)]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}async buildUpdateFeeReceiver({adminAddress:e,newReceiverAddress:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${BOOSTING_PACKAGE_ID}::config::update_fee_receiver`,typeArguments:[],arguments:[a.object(CONFIG_ID),a.object(ADMIN_CAP_ID),a.pure.address(t)]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}async buildPayBoostingWithAdminTx({walletAddress:e,tierId:t,customAmount:n,boostingCoinType:a,currentTx:i}){let o=i||new transactions_namespaceObject.Transaction,r=o.splitCoins(o.gas,[o.pure.u64(n)]);o.moveCall({target:`${BOOSTING_PACKAGE_ID}::boosting::pay_with_admin`,typeArguments:[(0,utils_namespaceObject.normalizeStructTag)(a)],arguments:[o.object(ADMIN_CAP_ID),o.object(CONFIG_ID),o.pure.u64(t),o.pure.u64(n),r]}),o.setSender(e);let s=await getNeededGasFee(this.sdk.suiClient,o,e,0);return addGasFee({inheritTx:o,sender:e,feeAmount:s},this.sdk.suiClient)}}class CurveModule{sdk;constructor(e){this.sdk=e}async getEstimatedAmountOut(e,t){let{coinInType:n,coinOutType:a}=t;tiny_invariant_default()(n!==a,"coinInType and coinOutType must be different"),tiny_invariant_default()(isSuiCoinType(n)||isSuiCoinType(a),"One of coinInType or coinOutType must be SUI");let i=isSuiCoinType(n);switch(e){case types_SupportedBondingCurve.MOONBAGS:if(i)return await calculation_MoonbagsCalculation.getCurveAmountAfterBuy({poolId:t.poolId,suiAmount:t.coinInAmount,frontendFee:t.tradeFee?t.tradeFee.tradeFeePercent:void 0},this.sdk.suiClient);return await calculation_MoonbagsCalculation.getSuiAmountAfterSell({poolId:t.poolId,curveAmount:t.coinInAmount,frontendFee:t.tradeFee?t.tradeFee.tradeFeePercent:void 0},this.sdk.suiClient);case types_SupportedBondingCurve.BLAST_FUN:if(i)return await sdk_calculation_BlastFunSDKCalculation.getCurveAmountAfterBuy({poolId:t.poolId,suiAmount:t.coinInAmount,frontendFee:t.tradeFee?t.tradeFee.tradeFeePercent:void 0});return await sdk_calculation_BlastFunSDKCalculation.getSuiAmountAfterSell({poolId:t.poolId,curveAmount:t.coinInAmount,frontendFee:t.tradeFee?t.tradeFee.tradeFeePercent:void 0});default:throw Error(`Unsupported bonding curve platform: ${e}`)}}async getTradeTransaction(e,t){let n,{coinInType:a,coinOutType:i}=t;tiny_invariant_default()(a!==i,"coinInType and coinOutType must be different"),tiny_invariant_default()(isSuiCoinType(a)||isSuiCoinType(i),"One of coinInType or coinOutType must be SUI");let o=isSuiCoinType(a);switch(e){case types_SupportedBondingCurve.MOONBAGS:n=o?await transaction_MoonbagsTransaction.getBuyTransaction(t,this.sdk.suiClient):await transaction_MoonbagsTransaction.getSellTransaction(t,this.sdk.suiClient);break;case types_SupportedBondingCurve.BLAST_FUN:n=o?await sdk_transaction_BlastFunSDKTransaction.getBuyTransaction(t,this.sdk.suiClient):await sdk_transaction_BlastFunSDKTransaction.getSellTransaction(t,this.sdk.suiClient);break;default:throw Error(`Unsupported bonding curve platform: ${e}`)}return n}}const SUBSCRIPTION_PACKAGE_ID="0x5dd4286ec234c117bb9577d4eaed1885b70d73ab1d3dab2794d0ab9a2c06c4a1",SUBSCRIPTION_CONFIG_ID="0x095b941beff22213fe8ccb223e4d1c5b4ede4dcd7f82ca4bb18c9a45fd3d6e20",SUBSCRIPTION_ADMIN_CAP_ID="0xdc27fe8187131b7fc095fccd213b79f72312793152a2483d1f67199c390e256d",PAYMENT_COIN_TYPE="0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC";class SubscriptionModule{sdk;constructor(e){this.sdk=e}async getConfig(){let e=await this.sdk.suiClient.getObject({id:SUBSCRIPTION_CONFIG_ID,options:{showContent:!0}});tiny_invariant_default()(e.data,"Config object not found"),tiny_invariant_default()(e.data.content,"Config object has no content"),tiny_invariant_default()(e.data?.content.dataType==="moveObject","Config object is not a Move object");let t=e.data.content.fields,n=t.id.id,a=t.fee_receiver,i=t.paused,o=t.accepted_payment_type,r=t.plans.fields.contents,s={};for(let e of r){let t=e.fields.key,n=e.fields.value.fields.id,a=e.fields.value.fields.price,i=e.fields.value.fields.month_interval,o=e.fields.value.fields.ptype;s[t]={id:BigInt(n),price:BigInt(a),monthInterval:i,planType:o}}return{id:n,plans:s,feeReceiverWallet:a,paused:i,acceptedPaymentType:o}}async buildSubscribeCyclePlanTx({walletAddress:e,planId:t,reference:n,paymentCoinType:a=PAYMENT_COIN_TYPE,currentTx:i}){let o=await this.getConfig();tiny_invariant_default()(!o.paused,"Contract is paused"),tiny_invariant_default()(t in o.plans,"Invalid plan ID");let r=o.plans[t],s=r.price*BigInt(r.monthInterval),{tx:u,coinData:c}=await getSplitCoinForTx({account:e,amount:s.toString(),splits:[s.toString()],coinType:a,inheritTx:i},this.sdk.suiClient);u.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::subscription::subscribe_cycle_plan`,typeArguments:[a],arguments:[u.object(SUBSCRIPTION_CONFIG_ID),u.pure.u64(t),u.pure.string(n),c]}),u.setSender(e);let _=await getNeededGasFee(this.sdk.suiClient,u,e,0);return addGasFee({inheritTx:u,sender:e,feeAmount:_},this.sdk.suiClient)}async buildBuyMoreCUPlanTx({walletAddress:e,planId:t,reference:n,paidAmount:a,paymentCoinType:i=PAYMENT_COIN_TYPE,currentTx:o}){let r=await this.getConfig();tiny_invariant_default()(!r.paused,"Contract is paused"),tiny_invariant_default()(t in r.plans,"Invalid plan ID");let{tx:s,coinData:u}=await getSplitCoinForTx({account:e,amount:a.toString(),splits:[a.toString()],coinType:i,inheritTx:o},this.sdk.suiClient);s.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::subscription::buy_more_cu`,typeArguments:[i],arguments:[s.object(SUBSCRIPTION_CONFIG_ID),s.pure.u64(t),s.pure.string(n),s.pure.u64(a),u]}),s.setSender(e);let c=await getNeededGasFee(this.sdk.suiClient,s,e,0);return addGasFee({inheritTx:s,sender:e,feeAmount:c},this.sdk.suiClient)}async buildSubscribePlanWithAdminTx({walletAddress:e,planId:t,reference:n,customAmount:a,paymentCoinType:i=PAYMENT_COIN_TYPE,currentTx:o}){let r=await this.getConfig();tiny_invariant_default()(!r.paused,"Contract is paused");let{tx:s,coinData:u}=await getSplitCoinForTx({account:e,amount:a.toString(),splits:[a.toString()],coinType:i,inheritTx:o},this.sdk.suiClient);s.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::subscription::subscribe_plan_with_admin`,typeArguments:[i],arguments:[s.object(SUBSCRIPTION_ADMIN_CAP_ID),s.object(SUBSCRIPTION_CONFIG_ID),s.pure.u64(t),s.pure.string(n),s.pure.u64(a),u]}),s.setSender(e);let c=await getNeededGasFee(this.sdk.suiClient,s,e,0);return addGasFee({inheritTx:s,sender:e,feeAmount:c},this.sdk.suiClient)}async buildAddPlanTx({adminAddress:e,planId:t,planType:n,monthInterval:a,price:i,currentTx:o}){let r=o||new transactions_namespaceObject.Transaction;r.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::add_plan`,typeArguments:[],arguments:[r.object(SUBSCRIPTION_CONFIG_ID),r.object(SUBSCRIPTION_ADMIN_CAP_ID),r.pure.u64(t),r.pure.u8(n),r.pure.u8(a),r.pure.u64(i)]}),r.setSender(e);let s=await getNeededGasFee(this.sdk.suiClient,r,e,0);return addGasFee({inheritTx:r,sender:e,feeAmount:s},this.sdk.suiClient)}async buildUpdatePlanTx({adminAddress:e,planId:t,planType:n,monthInterval:a,price:i,currentTx:o}){let r=o||new transactions_namespaceObject.Transaction;r.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::update_plan`,typeArguments:[],arguments:[r.object(SUBSCRIPTION_CONFIG_ID),r.object(SUBSCRIPTION_ADMIN_CAP_ID),r.pure.u64(BigInt(t)),r.pure.u8(n),r.pure.u8(a),r.pure.u64(i)]}),r.setSender(e);let s=await getNeededGasFee(this.sdk.suiClient,r,e,0);return addGasFee({inheritTx:r,sender:e,feeAmount:s},this.sdk.suiClient)}async buildRemovePlanTx({adminAddress:e,planId:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::remove_plan`,typeArguments:[],arguments:[a.object(SUBSCRIPTION_CONFIG_ID),a.object(SUBSCRIPTION_ADMIN_CAP_ID),a.pure.u64(BigInt(t))]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}async buildUpdateFeeReceiverWalletTx({adminAddress:e,newFeeReceiverWallet:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::update_fee_receiver`,typeArguments:[],arguments:[a.object(SUBSCRIPTION_CONFIG_ID),a.object(SUBSCRIPTION_ADMIN_CAP_ID),a.pure.address(t)]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}async buildSetPausedTx({adminAddress:e,paused:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::set_paused`,typeArguments:[],arguments:[a.object(SUBSCRIPTION_CONFIG_ID),a.object(SUBSCRIPTION_ADMIN_CAP_ID),a.pure.bool(t)]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}async buildSetAcceptedPaymentTypeTx({adminAddress:e,paymentCoinType:t,currentTx:n}){let a=n||new transactions_namespaceObject.Transaction;a.moveCall({target:`${SUBSCRIPTION_PACKAGE_ID}::config::set_accepted_payment_type`,typeArguments:[t],arguments:[a.object(SUBSCRIPTION_CONFIG_ID),a.object(SUBSCRIPTION_ADMIN_CAP_ID)]}),a.setSender(e);let i=await getNeededGasFee(this.sdk.suiClient,a,e,0);return addGasFee({inheritTx:a,sender:e,feeAmount:i},this.sdk.suiClient)}}class NoodlesPaySdk{_suiClient;boostingModule;subscriptionModule;constructor(){this._suiClient=new client_namespaceObject.SuiClient({url:(0,client_namespaceObject.getFullnodeUrl)("mainnet")}),this.subscriptionModule=new SubscriptionModule(this),this.boostingModule=new BoostingModule(this)}get suiClient(){return this._suiClient}}const DEFAULT_TRADE_FEE={tradeFeePercent:.01,tradeFeeRecipientAddress:"0xdaf1c8ed29d89cd8f217f609bad0a668fa6f158c12000bfa5f93e670c99e24ff"};class NoodlesSdk{options;_suiClient;aggregatorModule;curveModule;constructor(e){this.options=e,this._suiClient=new client_namespaceObject.SuiClient({url:(0,client_namespaceObject.getFullnodeUrl)("mainnet")}),this.aggregatorModule=new AggregatorModule(this),this.curveModule=new CurveModule(this)}get suiClient(){return this._suiClient}}const ed25519_namespaceObject=require("@mysten/sui/keypairs/ed25519"),CONSTANTS={GAS_FEE_BUFFER_PERCENTAGE:.1};class DraftTransferTx{suiClient;constructor(e){this.suiClient=e}validatePrivateKey(e,t){tiny_invariant_default()(e?.trim(),"Private key is required");let n=ed25519_namespaceObject.Ed25519Keypair.fromSecretKey(e),a=n.getPublicKey().toSuiAddress();if(a!==t)throw Error(`Private key mismatch. Expected: ${t}, Got: ${a}`);return n}async createDraft(e,t,n){tiny_invariant_default()(e?.trim(),"Sender address is required"),tiny_invariant_default()(t?.trim(),"Recipient address is required"),tiny_invariant_default()(e!==t,"Sender and recipient cannot be the same"),tiny_invariant_default()(n>0n,"Transfer amount must be at least 1 MIST");try{let a=new transactions_namespaceObject.Transaction,[i]=a.splitCoins(a.gas,[n]);a.transferObjects([i],t),a.setSender(e);let o=await this.suiClient.getReferenceGasPrice();a.setGasPrice(o);let r=await getNeededGasFee(this.suiClient,a,e,CONSTANTS.GAS_FEE_BUFFER_PERCENTAGE);a=await addGasFee({inheritTx:a,sender:e,feeAmount:r,suiInputAmount:n},this.suiClient);let s=await a.build({client:this.suiClient}),u=Buffer.from(s).toString("base64"),c=await a.getDigest();return{sender:e,recipient:t,amountMIST:n,txDraftBase64:u,txDigest:c}}catch(e){throw Error(`Failed to create draft transaction: ${e instanceof Error?e.message:"Unknown error"}`)}}async execute(e,t){try{tiny_invariant_default()(e,"Draft transaction is required"),tiny_invariant_default()(e.txDraftBase64?.trim(),"Transaction data is required");let n=this.validatePrivateKey(t,e.sender),a=(0,utils_namespaceObject.fromBase64)(e.txDraftBase64),{signature:i}=await n.signTransaction(a),o=await this.suiClient.executeTransactionBlock({transactionBlock:a,signature:i});return{success:!0,txDigest:o.digest,effects:o.effects}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Unknown error occurred"}}}async getTransactionStatus(e){tiny_invariant_default()(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"}}}for(var __rspack_i in exports.ADMIN_CAP_ID=__webpack_exports__.ADMIN_CAP_ID,exports.AftermathAggregator=__webpack_exports__.AftermathAggregator,exports.AggregatorModule=__webpack_exports__.AggregatorModule,exports.AstrosAggregator=__webpack_exports__.AstrosAggregator,exports.BASE_BPS=__webpack_exports__.BASE_BPS,exports.BLUEFIN_PACKAGE_ID=__webpack_exports__.BLUEFIN_PACKAGE_ID,exports.BOOSTING_PACKAGE_ID=__webpack_exports__.BOOSTING_PACKAGE_ID,exports.BlastFunConstants=__webpack_exports__.BlastFunConstants,exports.BlastFunCustomCalculation=__webpack_exports__.BlastFunCustomCalculation,exports.BlastFunCustomTransaction=__webpack_exports__.BlastFunCustomTransaction,exports.BlastFunPackage=__webpack_exports__.BlastFunPackage,exports.BlastFunSDKCalculation=__webpack_exports__.BlastFunSDKCalculation,exports.BlastFunSDKTransaction=__webpack_exports__.BlastFunSDKTransaction,exports.BluefinTx=__webpack_exports__.BluefinTx,exports.BoostingModule=__webpack_exports__.BoostingModule,exports.Bps=__webpack_exports__.Bps,exports.CLOCK_OBJECT_ID=__webpack_exports__.CLOCK_OBJECT_ID,exports.CONFIG_ID=__webpack_exports__.CONFIG_ID,exports.CetusAggregator=__webpack_exports__.CetusAggregator,exports.CurveModule=__webpack_exports__.CurveModule,exports.DEFAULT_TRADE_FEE=__webpack_exports__.DEFAULT_TRADE_FEE,exports.DraftTransferTx=__webpack_exports__.DraftTransferTx,exports.FlowXAggregator=__webpack_exports__.FlowXAggregator,exports.MathUtils=__webpack_exports__.MathUtils,exports.MoonbagsCalculation=__webpack_exports__.MoonbagsCalculation,exports.MoonbagsConstants=__webpack_exports__.MoonbagsConstants,exports.MoonbagsPackage=__webpack_exports__.MoonbagsPackage,exports.MoonbagsTransaction=__webpack_exports__.MoonbagsTransaction,exports.NATIVE_USDC_TOKEN_TYPE=__webpack_exports__.NATIVE_USDC_TOKEN_TYPE,exports.NoodlesPaySdk=__webpack_exports__.NoodlesPaySdk,exports.NoodlesSdk=__webpack_exports__.NoodlesSdk,exports.PAYMENT_COIN_TYPE=__webpack_exports__.PAYMENT_COIN_TYPE,exports.SUBSCRIPTION_ADMIN_CAP_ID=__webpack_exports__.SUBSCRIPTION_ADMIN_CAP_ID,exports.SUBSCRIPTION_CONFIG_ID=__webpack_exports__.SUBSCRIPTION_CONFIG_ID,exports.SUBSCRIPTION_PACKAGE_ID=__webpack_exports__.SUBSCRIPTION_PACKAGE_ID,exports.SUI_FULL_TYPE=__webpack_exports__.SUI_FULL_TYPE,exports.SUI_METADATA_OBJECT_ID=__webpack_exports__.SUI_METADATA_OBJECT_ID,exports.SUI_TYPE=__webpack_exports__.SUI_TYPE,exports.SevenKAggregator=__webpack_exports__.SevenKAggregator,exports.SubscriptionModule=__webpack_exports__.SubscriptionModule,exports.SupportedAggregator=__webpack_exports__.SupportedAggregator,exports.SupportedBondingCurve=__webpack_exports__.SupportedBondingCurve,exports.TradeFeeOptions=__webpack_exports__.TradeFeeOptions,exports.USDC_TOKEN_TYPE=__webpack_exports__.USDC_TOKEN_TYPE,exports.adaptSuiClient=__webpack_exports__.adaptSuiClient,exports.adaptTransaction=__webpack_exports__.adaptTransaction,exports.addGasFee=__webpack_exports__.addGasFee,exports.createCompatibleSuiClient=__webpack_exports__.createCompatibleSuiClient,exports.getAmountAfterFee=__webpack_exports__.getAmountAfterFee,exports.getCoinObjectIdsByAmount=__webpack_exports__.getCoinObjectIdsByAmount,exports.getMemezPumpSDK=__webpack_exports__.getMemezPumpSDK,exports.getMoveObject=__webpack_exports__.getMoveObject,exports.getMoveObjectContent=__webpack_exports__.getMoveObjectContent,exports.getNeededGasFee=__webpack_exports__.getNeededGasFee,exports.getSplitCoinForTx=__webpack_exports__.getSplitCoinForTx,exports.getSplitCoinsAfterFee=__webpack_exports__.getSplitCoinsAfterFee,exports.isSuiCoinType=__webpack_exports__.isSuiCoinType,exports.splitSuiCoinAfterFeeFromBuyTx=__webpack_exports__.splitSuiCoinAfterFeeFromBuyTx,exports.splitSuiCoinAfterFeeFromSellTx=__webpack_exports__.splitSuiCoinAfterFeeFromSellTx,__webpack_exports__)-1===["ADMIN_CAP_ID","AftermathAggregator","AggregatorModule","AstrosAggregator","BASE_BPS","BLUEFIN_PACKAGE_ID","BOOSTING_PACKAGE_ID","BlastFunConstants","BlastFunCustomCalculation","BlastFunCustomTransaction","BlastFunPackage","BlastFunSDKCalculation","BlastFunSDKTransaction","BluefinTx","BoostingModule","Bps","CLOCK_OBJECT_ID","CONFIG_ID","CetusAggregator","CurveModule","DEFAULT_TRADE_FEE","DraftTransferTx","FlowXAggregator","MathUtils","MoonbagsCalculation","MoonbagsConstants","MoonbagsPackage","MoonbagsTransaction","NATIVE_USDC_TOKEN_TYPE","NoodlesPaySdk","NoodlesSdk","PAYMENT_COIN_TYPE","SUBSCRIPTION_ADMIN_CAP_ID","SUBSCRIPTION_CONFIG_ID","SUBSCRIPTION_PACKAGE_ID","SUI_FULL_TYPE","SUI_METADATA_OBJECT_ID","SUI_TYPE","SevenKAggregator","SubscriptionModule","SupportedAggregator","SupportedBondingCurve","TradeFeeOptions","USDC_TOKEN_TYPE","adaptSuiClient","adaptTransaction","addGasFee","createCompatibleSuiClient","getAmountAfterFee","getCoinObjectIdsByAmount","getMemezPumpSDK","getMoveObject","getMoveObjectContent","getNeededGasFee","getSplitCoinForTx","getSplitCoinsAfterFee","isSuiCoinType","splitSuiCoinAfterFeeFromBuyTx","splitSuiCoinAfterFeeFromSellTx"].indexOf(__rspack_i)&&(exports[__rspack_i]=__webpack_exports__[__rspack_i]);Object.defineProperty(exports,"__esModule",{value:!0});