@sun-protocol/sun-cli 1.2.3-beta.0 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +9 -4
  2. package/dist/commands/contract.d.ts.map +1 -1
  3. package/dist/commands/contract.js +3 -5
  4. package/dist/commands/contract.js.map +1 -1
  5. package/dist/commands/liquidity.d.ts.map +1 -1
  6. package/dist/commands/liquidity.js +332 -161
  7. package/dist/commands/liquidity.js.map +1 -1
  8. package/dist/commands/sunpump.d.ts.map +1 -1
  9. package/dist/commands/sunpump.js +50 -15
  10. package/dist/commands/sunpump.js.map +1 -1
  11. package/dist/commands/swap.d.ts.map +1 -1
  12. package/dist/commands/swap.js +26 -12
  13. package/dist/commands/swap.js.map +1 -1
  14. package/dist/commands/wallet.js +2 -2
  15. package/dist/commands/wallet.js.map +1 -1
  16. package/dist/lib/command.d.ts +15 -4
  17. package/dist/lib/command.d.ts.map +1 -1
  18. package/dist/lib/command.js +19 -2
  19. package/dist/lib/command.js.map +1 -1
  20. package/dist/lib/context.d.ts +2 -0
  21. package/dist/lib/context.d.ts.map +1 -1
  22. package/dist/lib/context.js +17 -0
  23. package/dist/lib/context.js.map +1 -1
  24. package/dist/lib/sdk/compat.d.ts.map +1 -1
  25. package/dist/lib/sdk/compat.js +42 -7
  26. package/dist/lib/sdk/compat.js.map +1 -1
  27. package/dist/lib/sdk/constants.d.ts +6 -0
  28. package/dist/lib/sdk/constants.d.ts.map +1 -1
  29. package/dist/lib/sdk/constants.js +10 -1
  30. package/dist/lib/sdk/constants.js.map +1 -1
  31. package/dist/lib/sdk/factory.d.ts +4 -1
  32. package/dist/lib/sdk/factory.d.ts.map +1 -1
  33. package/dist/lib/sdk/factory.js +41 -1
  34. package/dist/lib/sdk/factory.js.map +1 -1
  35. package/dist/lib/sdk/liquidity-v3.d.ts +16 -0
  36. package/dist/lib/sdk/liquidity-v3.d.ts.map +1 -0
  37. package/dist/lib/sdk/liquidity-v3.js +61 -0
  38. package/dist/lib/sdk/liquidity-v3.js.map +1 -0
  39. package/dist/lib/sdk/liquidity-v4.d.ts +22 -0
  40. package/dist/lib/sdk/liquidity-v4.d.ts.map +1 -0
  41. package/dist/lib/sdk/liquidity-v4.js +70 -0
  42. package/dist/lib/sdk/liquidity-v4.js.map +1 -0
  43. package/dist/lib/slippage.d.ts +14 -0
  44. package/dist/lib/slippage.d.ts.map +1 -0
  45. package/dist/lib/slippage.js +22 -0
  46. package/dist/lib/slippage.js.map +1 -0
  47. package/package.json +9 -7
@@ -11,6 +11,9 @@ const tronweb_1 = require("tronweb");
11
11
  const constants_1 = require("../lib/sdk/constants");
12
12
  const factory_1 = require("../lib/sdk/factory");
13
13
  const compat_1 = require("../lib/sdk/compat");
14
+ const liquidity_v3_1 = require("../lib/sdk/liquidity-v3");
15
+ const liquidity_v4_1 = require("../lib/sdk/liquidity-v4");
16
+ const slippage_1 = require("../lib/slippage");
14
17
  const SUNSWAP_V2_FACTORY_MIN_ABI = [
15
18
  {
16
19
  constant: true,
@@ -43,12 +46,6 @@ const SUNSWAP_V2_PAIR_MIN_ABI = [
43
46
  type: 'function',
44
47
  },
45
48
  ];
46
- const TICK_SPACING_BY_FEE = {
47
- 100: 1,
48
- 500: 10,
49
- 3000: 60,
50
- 10000: 200,
51
- };
52
49
  function assertSdkNetwork(network) {
53
50
  if (network === 'mainnet' || network === 'nile')
54
51
  return network;
@@ -67,11 +64,80 @@ function getV3PositionManager(network, override) {
67
64
  function getV2Factory(network) {
68
65
  return (0, sun_sdk_chains_1.getContractAddress)(assertSdkNetwork(network), 'sunswapV2Factory');
69
66
  }
70
- function percentFromDecimal(value) {
71
- return value === undefined ? undefined : `${parseFloat(value) * 100}%`;
67
+ function parseOptionalSlippage(value) {
68
+ return value === undefined ? undefined : (0, slippage_1.parseDecimalSlippage)(value);
72
69
  }
73
- function tickSpacingForFee(fee) {
74
- return TICK_SPACING_BY_FEE[fee] ?? 60;
70
+ function outputInvalidParams(message) {
71
+ const error = invalidParamsError(message);
72
+ (0, output_1.outputError)(message, error);
73
+ }
74
+ function invalidParamsError(message) {
75
+ return Object.assign(new Error(message), { code: 'INVALID_PARAMS' });
76
+ }
77
+ function resolveOptionalV4Pair(token0Input, token1Input, network) {
78
+ if ((token0Input === undefined) !== (token1Input === undefined)) {
79
+ throw invalidParamsError('--token0 and --token1 must be provided together or both omitted');
80
+ }
81
+ if (token0Input === undefined || token1Input === undefined)
82
+ return {};
83
+ return {
84
+ token0: (0, tokens_1.resolveTokenAddress)(token0Input, network),
85
+ token1: (0, tokens_1.resolveTokenAddress)(token1Input, network),
86
+ };
87
+ }
88
+ function parseOptionalV4Fee(value) {
89
+ if (value === undefined)
90
+ return undefined;
91
+ if (!/^\d+$/.test(value))
92
+ throw invalidParamsError('--fee must be a non-negative integer');
93
+ const fee = Number(value);
94
+ if (!Number.isSafeInteger(fee) || fee > 0xffffff) {
95
+ throw invalidParamsError('--fee must fit in an unsigned 24-bit integer');
96
+ }
97
+ return fee;
98
+ }
99
+ function prepareV4Position(snapshot, expectedPair, expectedFee) {
100
+ const poolKey = snapshot.poolKey;
101
+ if (!poolKey) {
102
+ throw Object.assign(new Error('V4 position does not include its pool information'), {
103
+ code: 'SDK_CONTRACT_ERROR',
104
+ });
105
+ }
106
+ if (expectedFee !== undefined && poolKey.fee !== expectedFee) {
107
+ throw invalidParamsError(`--fee ${expectedFee} does not match position pool fee ${poolKey.fee}`);
108
+ }
109
+ if (expectedPair.token0 === undefined || expectedPair.token1 === undefined) {
110
+ return { poolKey, reversed: false };
111
+ }
112
+ if (expectedPair.token0 === expectedPair.token1) {
113
+ throw invalidParamsError('--token0 and --token1 must be different currencies');
114
+ }
115
+ if (expectedPair.token0 === poolKey.currency0 && expectedPair.token1 === poolKey.currency1) {
116
+ return { poolKey, reversed: false };
117
+ }
118
+ if (expectedPair.token0 === poolKey.currency1 && expectedPair.token1 === poolKey.currency0) {
119
+ return { poolKey, reversed: true };
120
+ }
121
+ throw invalidParamsError('Provided --token0/--token1 do not match the tokenId position');
122
+ }
123
+ function v4PositionTokenSummary(poolKey, network) {
124
+ return {
125
+ Token0: `${(0, tokens_1.getSymbolOrAddress)(poolKey.currency0, network)} (${poolKey.currency0})`,
126
+ Token1: `${(0, tokens_1.getSymbolOrAddress)(poolKey.currency1, network)} (${poolKey.currency1})`,
127
+ Fee: poolKey.fee,
128
+ };
129
+ }
130
+ function orderV4PositionValues(reversed, value0, value1) {
131
+ return reversed ? [value1, value0] : [value0, value1];
132
+ }
133
+ function createV4PositionLoader(tokenId, expectedPair, expectedFee) {
134
+ let pending;
135
+ return (sdk) => {
136
+ pending ?? (pending = sdk.positions.v4
137
+ .read({ tokenId })
138
+ .then((snapshot) => prepareV4Position(snapshot, expectedPair, expectedFee)));
139
+ return pending;
140
+ };
75
141
  }
76
142
  function toV3PoolOrder(token0, token1, value0, value1) {
77
143
  const token0Hex = tronweb_1.TronWeb.address.toHex(token0).toLowerCase();
@@ -82,8 +148,18 @@ function withContracts(overrides) {
82
148
  const entries = Object.entries(overrides).filter((entry) => !!entry[1]);
83
149
  return entries.length ? Object.fromEntries(entries) : undefined;
84
150
  }
85
- function mapTx(result) {
86
- return (0, compat_1.toCliTxResult)(result);
151
+ function mapTx(result, reverseAmounts = false) {
152
+ const mapped = (0, compat_1.toCliTxResult)(result);
153
+ const amounts = mapped?.computedAmounts;
154
+ if (!reverseAmounts || !amounts)
155
+ return mapped;
156
+ return {
157
+ ...mapped,
158
+ computedAmounts: {
159
+ amount0Desired: amounts.amount1Desired,
160
+ amount1Desired: amounts.amount0Desired,
161
+ },
162
+ };
87
163
  }
88
164
  function toWTRXIfNative(tokenAddress, network) {
89
165
  if (tokenAddress === constants_1.TRX_ADDRESS) {
@@ -218,7 +294,7 @@ function registerLiquidityCommands(program) {
218
294
  confirmMsg: 'Add V2 liquidity?',
219
295
  spinnerLabel: 'Adding V2 liquidity...',
220
296
  errorLabel: 'V2 add liquidity failed',
221
- execute: (sdk) => sdk.liquidity.v2.add
297
+ execute: async (client) => (await (0, factory_1.withLiquidityAbi)(client, router, opts.abi)).liquidity.v2.add
222
298
  .execute({
223
299
  contracts: withContracts({ sunswapV2Router: router }),
224
300
  tokenA,
@@ -228,9 +304,10 @@ function registerLiquidityCommands(program) {
228
304
  amountAMin: opts.minA,
229
305
  amountBMin: opts.minB,
230
306
  recipient: opts.to,
307
+ ttlSeconds: 1800,
231
308
  deadline: opts.deadline,
232
309
  })
233
- .then(mapTx),
310
+ .then((result) => mapTx(result)),
234
311
  });
235
312
  });
236
313
  liq
@@ -272,7 +349,7 @@ function registerLiquidityCommands(program) {
272
349
  confirmMsg: 'Remove V2 liquidity?',
273
350
  spinnerLabel: 'Removing V2 liquidity...',
274
351
  errorLabel: 'V2 remove liquidity failed',
275
- execute: (sdk) => sdk.liquidity.v2.remove
352
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, router, opts.abi)).liquidity.v2.remove
276
353
  .execute({
277
354
  contracts: withContracts({ sunswapV2Router: router }),
278
355
  tokenA,
@@ -281,9 +358,10 @@ function registerLiquidityCommands(program) {
281
358
  amountAMin: opts.minA,
282
359
  amountBMin: opts.minB,
283
360
  recipient: opts.to,
361
+ ttlSeconds: 1800,
284
362
  deadline: opts.deadline,
285
363
  })
286
- .then(mapTx),
364
+ .then((result) => mapTx(result)),
287
365
  });
288
366
  });
289
367
  // ---------------------------------------------------------------------------
@@ -295,7 +373,7 @@ function registerLiquidityCommands(program) {
295
373
  .option('--pm <address>', 'V3 NonfungiblePositionManager address (auto-detected by network)')
296
374
  .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
297
375
  .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
298
- .option('--fee <n>', 'Pool fee tier (default: 3000)')
376
+ .option('--fee <n>', `Pool fee tier (default: ${constants_1.DEFAULT_V3_FEE})`)
299
377
  .option('--tick-lower <n>', 'Lower tick (auto-computed if omitted)')
300
378
  .option('--tick-upper <n>', 'Upper tick (auto-computed if omitted)')
301
379
  .option('--amount0 <raw>', 'Desired amount of token0')
@@ -338,32 +416,40 @@ function registerLiquidityCommands(program) {
338
416
  'Position Manager': pm,
339
417
  Token0: `${token0Display}${token0Note} (${token0})`,
340
418
  Token1: `${token1Display}${token1Note} (${token1})`,
341
- Fee: opts.fee || '3000 (default)',
419
+ Fee: opts.fee || `${constants_1.DEFAULT_V3_FEE} (default)`,
342
420
  'Tick Range': tickRange,
343
- Amount0: opts.amount0 || '(auto)',
344
- Amount1: opts.amount1 || '(auto)',
421
+ Amount0: opts.amount0 ?? '(not provided)',
422
+ Amount1: opts.amount1 ?? '(not provided)',
345
423
  Network: network,
346
424
  },
347
425
  confirmMsg: 'Mint V3 position?',
348
426
  spinnerLabel: 'Minting V3 position...',
349
427
  errorLabel: 'V3 mint failed',
350
- execute: (sdk) => sdk.liquidity.v3.add
428
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).liquidity.v3.add
351
429
  .execute({
352
430
  contracts: withContracts({ sunswapV3PositionManager: pm }),
353
431
  tokenA: token0,
354
432
  tokenB: token1,
355
- fee: opts.fee ? parseInt(opts.fee) : 3000,
433
+ fee: opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V3_FEE,
434
+ pool: await (0, liquidity_v3_1.resolveLegacyV3Pool)(sdk, {
435
+ token0,
436
+ token1,
437
+ fee: opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V3_FEE,
438
+ }),
356
439
  tickLower: opts.tickLower ? parseInt(opts.tickLower) : undefined,
357
440
  tickUpper: opts.tickUpper ? parseInt(opts.tickUpper) : undefined,
358
- tickRangeWidth: opts.tickLower === undefined && opts.tickUpper === undefined ? 100 : undefined,
441
+ tickRangeMode: 'legacy',
442
+ includeComputedMetadata: true,
443
+ tickRangeWidth: opts.tickLower === undefined || opts.tickUpper === undefined ? 100 : undefined,
359
444
  amount0,
360
445
  amount1,
361
446
  amount0Min,
362
447
  amount1Min,
363
448
  recipient: opts.recipient,
449
+ ttlSeconds: 1800,
364
450
  deadline: opts.deadline,
365
451
  })
366
- .then(mapTx),
452
+ .then((result) => mapTx(result, toV3PoolOrder(token0, token1, false, true)[0])),
367
453
  summarizeResult: (result) => {
368
454
  const out = {};
369
455
  if (result?.computedTicks) {
@@ -404,21 +490,32 @@ function registerLiquidityCommands(program) {
404
490
  summary: {
405
491
  'Position Manager': pm,
406
492
  'Token ID': opts.tokenId,
407
- Amount0: opts.amount0 || '(auto)',
408
- Amount1: opts.amount1 || '(auto)',
493
+ Amount0: opts.amount0 ?? '(not provided)',
494
+ Amount1: opts.amount1 ?? '(not provided)',
409
495
  Network: network,
410
496
  },
411
497
  confirmMsg: 'Increase V3 liquidity?',
412
498
  spinnerLabel: 'Increasing V3 liquidity...',
413
499
  errorLabel: 'V3 increase liquidity failed',
414
- execute: (sdk) => sdk.liquidity.v3.increase
500
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi, BigInt(opts.amount0 ?? '0') === 0n || BigInt(opts.amount1 ?? '0') === 0n
501
+ ? ['positions(uint256)']
502
+ : [])).liquidity.v3.increase
415
503
  .execute({
416
504
  contracts: withContracts({ sunswapV3PositionManager: pm }),
417
505
  tokenId: opts.tokenId,
418
506
  amount0: opts.amount0,
419
507
  amount1: opts.amount1,
508
+ includeComputedMetadata: true,
509
+ pool: BigInt(opts.amount0 ?? '0') === 0n || BigInt(opts.amount1 ?? '0') === 0n
510
+ ? await (0, liquidity_v3_1.resolveLegacyV3Pool)(sdk, {
511
+ tokenId: opts.tokenId,
512
+ positionManager: pm,
513
+ positionAbi: opts.abi,
514
+ })
515
+ : undefined,
420
516
  amount0Min: opts.min0,
421
517
  amount1Min: opts.min1,
518
+ ttlSeconds: 1800,
422
519
  deadline: opts.deadline,
423
520
  })
424
521
  .then(mapTx),
@@ -458,7 +555,7 @@ function registerLiquidityCommands(program) {
458
555
  confirmMsg: 'Decrease V3 liquidity?',
459
556
  spinnerLabel: 'Decreasing V3 liquidity...',
460
557
  errorLabel: 'V3 decrease liquidity failed',
461
- execute: (sdk) => sdk.positions.v3.remove
558
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).positions.v3.remove
462
559
  .execute({
463
560
  contracts: withContracts({ sunswapV3PositionManager: pm }),
464
561
  tokenId: opts.tokenId,
@@ -466,6 +563,7 @@ function registerLiquidityCommands(program) {
466
563
  amount0Min: opts.min0,
467
564
  amount1Min: opts.min1,
468
565
  collectFees: false,
566
+ ttlSeconds: 1800,
469
567
  deadline: opts.deadline,
470
568
  })
471
569
  .then(mapTx),
@@ -492,11 +590,12 @@ function registerLiquidityCommands(program) {
492
590
  confirmMsg: 'Collect V3 fees?',
493
591
  spinnerLabel: 'Collecting V3 fees...',
494
592
  errorLabel: 'V3 collect failed',
495
- execute: (sdk) => sdk.positions.v3.collect
593
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).positions.v3.collect
496
594
  .execute({
497
595
  contracts: withContracts({ sunswapV3PositionManager: pm }),
498
596
  tokenId: opts.tokenId,
499
597
  recipient: opts.recipient,
598
+ estimateFees: true,
500
599
  })
501
600
  .then(mapTx),
502
601
  summarizeResult: (result) => {
@@ -519,7 +618,7 @@ function registerLiquidityCommands(program) {
519
618
  .description('Mint a new SUNSWAP V4 concentrated liquidity position')
520
619
  .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
521
620
  .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
522
- .option('--fee <n>', 'Pool fee tier (e.g. 500)')
621
+ .option('--fee <n>', `Pool fee tier (default: ${constants_1.DEFAULT_V4_FEE})`)
523
622
  .option('--tick-lower <n>', 'Lower tick (auto-computed if omitted)')
524
623
  .option('--tick-upper <n>', 'Upper tick (auto-computed if omitted)')
525
624
  .option('--amount0 <raw>', 'Desired amount of token0')
@@ -541,56 +640,78 @@ function registerLiquidityCommands(program) {
541
640
  process.exitCode = 1;
542
641
  return;
543
642
  }
544
- const token0 = toWTRXIfNative(token0Input, network);
545
- const token1 = toWTRXIfNative(token1Input, network);
643
+ // V4 identifies native TRX with the zero address. WTRX is a different pool currency.
644
+ const token0 = token0Input;
645
+ const token1 = token1Input;
546
646
  const token0Display = (0, tokens_1.getSymbolOrAddress)(token0Input, network);
547
647
  const token1Display = (0, tokens_1.getSymbolOrAddress)(token1Input, network);
548
- const token0Note = token0 !== token0Input ? ` → WTRX` : '';
549
- const token1Note = token1 !== token1Input ? ` → WTRX` : '';
550
- const fee = opts.fee ? parseInt(opts.fee) : 3000;
551
- const tickSpacing = tickSpacingForFee(fee);
552
- const tickLower = opts.tickLower ? parseInt(opts.tickLower) : -2 * tickSpacing;
553
- const tickUpper = opts.tickUpper ? parseInt(opts.tickUpper) : 2 * tickSpacing;
648
+ const fee = opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V4_FEE;
649
+ const tickLower = opts.tickLower !== undefined ? parseInt(opts.tickLower) : undefined;
650
+ const tickUpper = opts.tickUpper !== undefined ? parseInt(opts.tickUpper) : undefined;
651
+ let slippage;
652
+ try {
653
+ slippage = parseOptionalSlippage(opts.slippage);
654
+ }
655
+ catch (err) {
656
+ (0, output_1.outputError)('Invalid --slippage', err);
657
+ return;
658
+ }
554
659
  if (!opts.amount0 && !opts.amount1) {
555
- console.error('Error: At least one of --amount0 or --amount1 is required');
556
- process.exitCode = 1;
660
+ outputInvalidParams('At least one of --amount0 or --amount1 is required');
557
661
  return;
558
662
  }
559
663
  await (0, command_1.writeAction)({
560
664
  title: 'V4 Mint Position',
561
665
  summary: {
562
- Token0: `${token0Display}${token0Note} (${token0})`,
563
- Token1: `${token1Display}${token1Note} (${token1})`,
564
- Fee: fee,
565
- 'Tick Range': `[${tickLower}, ${tickUpper}]`,
566
- Amount0: opts.amount0 || '(auto)',
567
- Amount1: opts.amount1 || '(auto)',
568
- Slippage: opts.slippage
569
- ? `${(parseFloat(opts.slippage) * 100).toFixed(2)}%`
570
- : '(default)',
666
+ Token0: `${token0Display} (${token0})`,
667
+ Token1: `${token1Display} (${token1})`,
668
+ Fee: opts.fee || `${constants_1.DEFAULT_V4_FEE} (default)`,
669
+ 'Tick Range': tickLower !== undefined && tickUpper !== undefined
670
+ ? `[${tickLower}, ${tickUpper}]`
671
+ : '(auto)',
672
+ Amount0: opts.amount0 ?? '(not provided)',
673
+ Amount1: opts.amount1 ?? '(not provided)',
674
+ Slippage: slippage?.display ?? '(default)',
571
675
  'Create Pool': opts.createPool ? 'Yes' : 'No',
572
676
  Network: network,
573
677
  },
574
678
  confirmMsg: 'Mint V4 position?',
575
679
  spinnerLabel: 'Minting V4 position...',
576
680
  errorLabel: 'V4 mint failed',
577
- execute: (sdk) => sdk.liquidity.v4.add
578
- .execute({
579
- token0,
580
- token1,
581
- fee,
582
- tickSpacing,
583
- tickLower,
584
- tickUpper,
585
- amount0: opts.amount0,
586
- amount1: opts.amount1,
587
- slippage: percentFromDecimal(opts.slippage),
588
- owner: opts.recipient,
589
- deadline: opts.deadline,
590
- sqrtPriceX96: opts.sqrtPrice,
591
- createPool: opts.createPool,
592
- })
593
- .then(mapTx),
681
+ execute: async (sdk) => {
682
+ const ticks = await (0, liquidity_v4_1.resolveV4MintTicks)(sdk, {
683
+ token0,
684
+ token1,
685
+ fee,
686
+ tickLower,
687
+ tickUpper,
688
+ sqrtPriceX96: opts.sqrtPrice,
689
+ createPool: opts.createPool,
690
+ });
691
+ return sdk.liquidity.v4.add
692
+ .execute({
693
+ token0,
694
+ token1,
695
+ fee,
696
+ ...ticks,
697
+ amount0: opts.amount0,
698
+ amount1: opts.amount1,
699
+ slippage: slippage?.sdk,
700
+ includeComputedMetadata: true,
701
+ transactionMode: 'multicall',
702
+ recipient: opts.recipient,
703
+ sweepRecipient: opts.recipient,
704
+ ttlSeconds: 1800,
705
+ deadline: opts.deadline,
706
+ sqrtPriceX96: opts.sqrtPrice,
707
+ })
708
+ .then((result) => {
709
+ const mapped = mapTx(result);
710
+ return tickLower === undefined || tickUpper === undefined
711
+ ? { ...mapped, computedTicks: ticks }
712
+ : mapped;
713
+ });
714
+ },
594
715
  summarizeResult: (result) => {
595
716
  const out = {};
596
717
  if (result?.poolCreated !== undefined)
@@ -613,56 +734,78 @@ function registerLiquidityCommands(program) {
613
734
  .command('v4:increase')
614
735
  .description('Increase liquidity of an existing V4 position')
615
736
  .requiredOption('--token-id <id>', 'Position NFT token ID')
616
- .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
617
- .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
618
- .option('--fee <n>', 'Pool fee tier')
737
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
738
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
739
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
619
740
  .option('--amount0 <raw>', 'Additional amount of token0')
620
741
  .option('--amount1 <raw>', 'Additional amount of token1')
621
742
  .option('--slippage <n>', 'Slippage tolerance as decimal')
622
743
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
623
744
  .action(async (opts) => {
624
745
  const network = (0, context_1.getNetwork)();
625
- let token0Input, token1Input;
746
+ let expectedPair, expectedFee;
626
747
  try {
627
- token0Input = (0, tokens_1.resolveTokenAddress)(opts.token0, network);
628
- token1Input = (0, tokens_1.resolveTokenAddress)(opts.token1, network);
748
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
749
+ expectedFee = parseOptionalV4Fee(opts.fee);
629
750
  }
630
751
  catch (err) {
631
- console.error(err.message);
632
- process.exitCode = 1;
752
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
753
+ return;
754
+ }
755
+ let slippage;
756
+ try {
757
+ slippage = parseOptionalSlippage(opts.slippage);
758
+ }
759
+ catch (err) {
760
+ (0, output_1.outputError)('Invalid --slippage', err);
633
761
  return;
634
762
  }
635
- const token0 = toWTRXIfNative(token0Input, network);
636
- const token1 = toWTRXIfNative(token1Input, network);
637
- const token0Display = (0, tokens_1.getSymbolOrAddress)(token0Input, network);
638
- const token1Display = (0, tokens_1.getSymbolOrAddress)(token1Input, network);
639
763
  if (!opts.amount0 && !opts.amount1) {
640
- console.error('Error: At least one of --amount0 or --amount1 is required');
641
- process.exitCode = 1;
764
+ outputInvalidParams('At least one of --amount0 or --amount1 is required');
642
765
  return;
643
766
  }
767
+ const summary = {
768
+ 'Token ID': opts.tokenId,
769
+ Token0: expectedPair.token0 ?? '(from tokenId)',
770
+ Token1: expectedPair.token1 ?? '(from tokenId)',
771
+ Fee: expectedFee ?? '(from tokenId)',
772
+ Amount0: opts.amount0 ?? '(not provided)',
773
+ Amount1: opts.amount1 ?? '(not provided)',
774
+ Slippage: slippage?.display ?? '(default)',
775
+ Network: network,
776
+ };
777
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
644
778
  await (0, command_1.writeAction)({
645
779
  title: 'V4 Increase Liquidity',
646
- summary: {
647
- 'Token ID': opts.tokenId,
648
- Token0: `${token0Display} (${token0})`,
649
- Token1: `${token1Display} (${token1})`,
650
- Amount0: opts.amount0 || '(auto)',
651
- Amount1: opts.amount1 || '(auto)',
652
- Network: network,
780
+ summary,
781
+ prepareLabel: 'Loading V4 position...',
782
+ prepare: async (sdk) => {
783
+ const prepared = await loadPosition(sdk);
784
+ const [amount0, amount1] = orderV4PositionValues(prepared.reversed, opts.amount0, opts.amount1);
785
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network), {
786
+ Amount0: amount0 ?? '(not provided)',
787
+ Amount1: amount1 ?? '(not provided)',
788
+ });
653
789
  },
654
790
  confirmMsg: 'Increase V4 liquidity?',
655
791
  spinnerLabel: 'Increasing V4 liquidity...',
656
792
  errorLabel: 'V4 increase liquidity failed',
657
- execute: (sdk) => sdk.liquidity.v4.increase
658
- .execute({
659
- tokenId: opts.tokenId,
660
- amount0: opts.amount0,
661
- amount1: opts.amount1,
662
- slippage: percentFromDecimal(opts.slippage),
663
- deadline: opts.deadline,
664
- })
665
- .then(mapTx),
793
+ execute: async (sdk) => {
794
+ const prepared = await loadPosition(sdk);
795
+ const [amount0, amount1] = orderV4PositionValues(prepared.reversed, opts.amount0, opts.amount1);
796
+ return sdk.liquidity.v4.increase
797
+ .execute({
798
+ tokenId: opts.tokenId,
799
+ amount0,
800
+ amount1,
801
+ slippage: slippage?.sdk,
802
+ includeComputedMetadata: true,
803
+ transactionMode: 'multicall',
804
+ ttlSeconds: 1800,
805
+ deadline: opts.deadline,
806
+ })
807
+ .then(mapTx);
808
+ },
666
809
  summarizeResult: (result) => {
667
810
  const out = {};
668
811
  if (result?.computedAmounts) {
@@ -680,51 +823,77 @@ function registerLiquidityCommands(program) {
680
823
  .description('Decrease liquidity of an existing V4 position')
681
824
  .requiredOption('--token-id <id>', 'Position NFT token ID')
682
825
  .requiredOption('--liquidity <raw>', 'Amount of liquidity to remove')
683
- .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
684
- .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
685
- .option('--fee <n>', 'Pool fee tier')
826
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
827
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
828
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
686
829
  .option('--min0 <raw>', 'Minimum amount of token0 to receive')
687
830
  .option('--min1 <raw>', 'Minimum amount of token1 to receive')
688
831
  .option('--slippage <n>', 'Slippage tolerance as decimal')
689
832
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
690
833
  .action(async (opts) => {
691
834
  const network = (0, context_1.getNetwork)();
692
- let token0Input, token1Input;
835
+ let expectedPair, expectedFee;
693
836
  try {
694
- token0Input = (0, tokens_1.resolveTokenAddress)(opts.token0, network);
695
- token1Input = (0, tokens_1.resolveTokenAddress)(opts.token1, network);
837
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
838
+ expectedFee = parseOptionalV4Fee(opts.fee);
696
839
  }
697
840
  catch (err) {
698
- console.error(err.message);
699
- process.exitCode = 1;
841
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
700
842
  return;
701
843
  }
702
- const token0 = toWTRXIfNative(token0Input, network);
703
- const token1 = toWTRXIfNative(token1Input, network);
704
- const token0Display = (0, tokens_1.getSymbolOrAddress)(token0Input, network);
705
- const token1Display = (0, tokens_1.getSymbolOrAddress)(token1Input, network);
844
+ let slippage;
845
+ try {
846
+ slippage = parseOptionalSlippage(opts.slippage);
847
+ }
848
+ catch (err) {
849
+ (0, output_1.outputError)('Invalid --slippage', err);
850
+ return;
851
+ }
852
+ const summary = {
853
+ 'Token ID': opts.tokenId,
854
+ Liquidity: opts.liquidity,
855
+ Token0: expectedPair.token0 ?? '(from tokenId)',
856
+ Token1: expectedPair.token1 ?? '(from tokenId)',
857
+ Fee: expectedFee ?? '(from tokenId)',
858
+ Min0: opts.min0 ?? '(SDK derived)',
859
+ Min1: opts.min1 ?? '(SDK derived)',
860
+ Slippage: slippage?.display ?? '(default)',
861
+ Network: network,
862
+ };
863
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
706
864
  await (0, command_1.writeAction)({
707
865
  title: 'V4 Decrease Liquidity',
708
- summary: {
709
- 'Token ID': opts.tokenId,
710
- Liquidity: opts.liquidity,
711
- Token0: `${token0Display} (${token0})`,
712
- Token1: `${token1Display} (${token1})`,
713
- Network: network,
866
+ summary,
867
+ prepareLabel: 'Loading V4 position...',
868
+ prepare: async (sdk) => {
869
+ const prepared = await loadPosition(sdk);
870
+ const [min0, min1] = orderV4PositionValues(prepared.reversed, opts.min0, opts.min1);
871
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network), {
872
+ Min0: min0 ?? '(SDK derived)',
873
+ Min1: min1 ?? '(SDK derived)',
874
+ });
714
875
  },
715
876
  confirmMsg: 'Decrease V4 liquidity?',
716
877
  spinnerLabel: 'Decreasing V4 liquidity...',
717
878
  errorLabel: 'V4 decrease liquidity failed',
718
- execute: (sdk) => sdk.positions.v4.remove
719
- .execute({
720
- tokenId: opts.tokenId,
721
- liquidity: opts.liquidity,
722
- amount0Min: opts.min0,
723
- amount1Min: opts.min1,
724
- slippage: percentFromDecimal(opts.slippage),
725
- deadline: opts.deadline,
726
- })
727
- .then(mapTx),
879
+ execute: async (sdk) => {
880
+ const prepared = await loadPosition(sdk);
881
+ const [amount0Min, amount1Min] = orderV4PositionValues(prepared.reversed, opts.min0, opts.min1);
882
+ return sdk.positions.v4.remove
883
+ .execute({
884
+ tokenId: opts.tokenId,
885
+ liquidity: opts.liquidity,
886
+ amount0Min,
887
+ amount1Min,
888
+ slippage: slippage?.sdk,
889
+ includeComputedMetadata: true,
890
+ transactionMode: 'multicall',
891
+ settlementMode: 'close-currency',
892
+ ttlSeconds: 1800,
893
+ deadline: opts.deadline,
894
+ })
895
+ .then(mapTx);
896
+ },
728
897
  summarizeResult: (result) => {
729
898
  const out = {};
730
899
  if (result?.computedAmountMin) {
@@ -741,52 +910,52 @@ function registerLiquidityCommands(program) {
741
910
  .command('v4:collect')
742
911
  .description('Collect accrued fees from an existing V4 position')
743
912
  .requiredOption('--token-id <id>', 'Position NFT token ID')
744
- .option('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
745
- .option('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
746
- .option('--fee <n>', 'Pool fee tier')
913
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
914
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
915
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
747
916
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
748
917
  .action(async (opts) => {
749
918
  const network = (0, context_1.getNetwork)();
750
- let token0, token1;
751
- if (opts.token0) {
752
- try {
753
- const resolved = (0, tokens_1.resolveTokenAddress)(opts.token0, network);
754
- token0 = toWTRXIfNative(resolved, network);
755
- }
756
- catch (err) {
757
- console.error(err.message);
758
- process.exitCode = 1;
759
- return;
760
- }
919
+ let expectedPair, expectedFee;
920
+ try {
921
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
922
+ expectedFee = parseOptionalV4Fee(opts.fee);
761
923
  }
762
- if (opts.token1) {
763
- try {
764
- const resolved = (0, tokens_1.resolveTokenAddress)(opts.token1, network);
765
- token1 = toWTRXIfNative(resolved, network);
766
- }
767
- catch (err) {
768
- console.error(err.message);
769
- process.exitCode = 1;
770
- return;
771
- }
924
+ catch (err) {
925
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
926
+ return;
772
927
  }
928
+ const summary = {
929
+ 'Token ID': opts.tokenId,
930
+ Token0: expectedPair.token0 ?? '(from tokenId)',
931
+ Token1: expectedPair.token1 ?? '(from tokenId)',
932
+ Fee: expectedFee ?? '(from tokenId)',
933
+ Network: network,
934
+ };
935
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
773
936
  await (0, command_1.writeAction)({
774
937
  title: 'V4 Collect Fees',
775
- summary: {
776
- 'Token ID': opts.tokenId,
777
- Token0: token0 || '(auto)',
778
- Token1: token1 || '(auto)',
779
- Network: network,
938
+ summary,
939
+ prepareLabel: 'Loading V4 position...',
940
+ prepare: async (sdk) => {
941
+ const prepared = await loadPosition(sdk);
942
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network));
780
943
  },
781
944
  confirmMsg: 'Collect V4 fees?',
782
945
  spinnerLabel: 'Collecting V4 fees...',
783
946
  errorLabel: 'V4 collect failed',
784
- execute: (sdk) => sdk.positions.v4.collect
785
- .execute({
786
- tokenId: opts.tokenId,
787
- deadline: opts.deadline,
788
- })
789
- .then(mapTx),
947
+ execute: async (sdk) => {
948
+ await loadPosition(sdk);
949
+ return sdk.positions.v4.collect
950
+ .execute({
951
+ tokenId: opts.tokenId,
952
+ transactionMode: 'multicall',
953
+ settlementMode: 'close-currency',
954
+ ttlSeconds: 1800,
955
+ deadline: opts.deadline,
956
+ })
957
+ .then(mapTx);
958
+ },
790
959
  });
791
960
  });
792
961
  liq
@@ -805,11 +974,13 @@ function registerLiquidityCommands(program) {
805
974
  transform: (result) => {
806
975
  if (!result)
807
976
  return { error: 'Position not found' };
977
+ const fee = result.poolKey?.fee;
808
978
  return {
809
979
  currency0: result.poolKey?.currency0,
810
980
  currency1: result.poolKey?.currency1,
811
- fee: result.poolKey?.fee,
812
- tickSpacing: result.poolKey?.tickSpacing,
981
+ fee: fee === undefined ? undefined : String(fee),
982
+ tickSpacing: result.poolKey?.tickSpacing ??
983
+ (Number.isFinite(Number(fee)) ? (0, liquidity_v4_1.v4TickSpacingForFee)(Number(fee)) : undefined),
813
984
  tickLower: result.tickLower,
814
985
  tickUpper: result.tickUpper,
815
986
  liquidity: result.liquidity,