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

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 +359 -168
  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 +36 -11
  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 +1 -1
  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,92 @@ 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 invalidParamsError(message) {
71
+ return Object.assign(new Error(message), { code: 'INVALID_PARAMS' });
72
+ }
73
+ function assertLiquidityAmounts(amount0, amount1) {
74
+ if (amount0 === undefined && amount1 === undefined) {
75
+ throw invalidParamsError('At least one of --amount0 or --amount1 is required');
76
+ }
77
+ for (const [name, value] of [
78
+ ['--amount0', amount0],
79
+ ['--amount1', amount1],
80
+ ]) {
81
+ if (value !== undefined && !/^\d+$/.test(value)) {
82
+ throw invalidParamsError(`${name} must be a non-negative integer in base units`);
83
+ }
84
+ }
85
+ if (BigInt(amount0 ?? '0') === 0n && BigInt(amount1 ?? '0') === 0n) {
86
+ throw invalidParamsError('At least one of --amount0 or --amount1 must be greater than zero');
87
+ }
88
+ }
89
+ function resolveOptionalV4Pair(token0Input, token1Input, network) {
90
+ if ((token0Input === undefined) !== (token1Input === undefined)) {
91
+ throw invalidParamsError('--token0 and --token1 must be provided together or both omitted');
92
+ }
93
+ if (token0Input === undefined || token1Input === undefined)
94
+ return {};
95
+ return {
96
+ token0: (0, tokens_1.resolveTokenAddress)(token0Input, network),
97
+ token1: (0, tokens_1.resolveTokenAddress)(token1Input, network),
98
+ };
99
+ }
100
+ function parseOptionalV4Fee(value) {
101
+ if (value === undefined)
102
+ return undefined;
103
+ if (!/^\d+$/.test(value))
104
+ throw invalidParamsError('--fee must be a non-negative integer');
105
+ const fee = Number(value);
106
+ if (!Number.isSafeInteger(fee) || fee > 0xffffff) {
107
+ throw invalidParamsError('--fee must fit in an unsigned 24-bit integer');
108
+ }
109
+ return fee;
110
+ }
111
+ function prepareV4Position(snapshot, expectedPair, expectedFee) {
112
+ const poolKey = snapshot.poolKey;
113
+ if (!poolKey) {
114
+ throw Object.assign(new Error('V4 position does not include its pool information'), {
115
+ code: 'SDK_CONTRACT_ERROR',
116
+ });
117
+ }
118
+ if (expectedFee !== undefined && poolKey.fee !== expectedFee) {
119
+ throw invalidParamsError(`--fee ${expectedFee} does not match position pool fee ${poolKey.fee}`);
120
+ }
121
+ if (expectedPair.token0 === undefined || expectedPair.token1 === undefined) {
122
+ return { poolKey, reversed: false };
123
+ }
124
+ if (expectedPair.token0 === expectedPair.token1) {
125
+ throw invalidParamsError('--token0 and --token1 must be different currencies');
126
+ }
127
+ if (expectedPair.token0 === poolKey.currency0 && expectedPair.token1 === poolKey.currency1) {
128
+ return { poolKey, reversed: false };
129
+ }
130
+ if (expectedPair.token0 === poolKey.currency1 && expectedPair.token1 === poolKey.currency0) {
131
+ return { poolKey, reversed: true };
132
+ }
133
+ throw invalidParamsError('Provided --token0/--token1 do not match the tokenId position');
134
+ }
135
+ function v4PositionTokenSummary(poolKey, network) {
136
+ return {
137
+ Token0: `${(0, tokens_1.getSymbolOrAddress)(poolKey.currency0, network)} (${poolKey.currency0})`,
138
+ Token1: `${(0, tokens_1.getSymbolOrAddress)(poolKey.currency1, network)} (${poolKey.currency1})`,
139
+ Fee: poolKey.fee,
140
+ };
141
+ }
142
+ function orderV4PositionValues(reversed, value0, value1) {
143
+ return reversed ? [value1, value0] : [value0, value1];
144
+ }
145
+ function createV4PositionLoader(tokenId, expectedPair, expectedFee) {
146
+ let pending;
147
+ return (sdk) => {
148
+ pending ?? (pending = sdk.positions.v4
149
+ .read({ tokenId })
150
+ .then((snapshot) => prepareV4Position(snapshot, expectedPair, expectedFee)));
151
+ return pending;
152
+ };
75
153
  }
76
154
  function toV3PoolOrder(token0, token1, value0, value1) {
77
155
  const token0Hex = tronweb_1.TronWeb.address.toHex(token0).toLowerCase();
@@ -82,8 +160,18 @@ function withContracts(overrides) {
82
160
  const entries = Object.entries(overrides).filter((entry) => !!entry[1]);
83
161
  return entries.length ? Object.fromEntries(entries) : undefined;
84
162
  }
85
- function mapTx(result) {
86
- return (0, compat_1.toCliTxResult)(result);
163
+ function mapTx(result, reverseAmounts = false) {
164
+ const mapped = (0, compat_1.toCliTxResult)(result);
165
+ const amounts = mapped?.computedAmounts;
166
+ if (!reverseAmounts || !amounts)
167
+ return mapped;
168
+ return {
169
+ ...mapped,
170
+ computedAmounts: {
171
+ amount0Desired: amounts.amount1Desired,
172
+ amount1Desired: amounts.amount0Desired,
173
+ },
174
+ };
87
175
  }
88
176
  function toWTRXIfNative(tokenAddress, network) {
89
177
  if (tokenAddress === constants_1.TRX_ADDRESS) {
@@ -218,7 +306,7 @@ function registerLiquidityCommands(program) {
218
306
  confirmMsg: 'Add V2 liquidity?',
219
307
  spinnerLabel: 'Adding V2 liquidity...',
220
308
  errorLabel: 'V2 add liquidity failed',
221
- execute: (sdk) => sdk.liquidity.v2.add
309
+ execute: async (client) => (await (0, factory_1.withLiquidityAbi)(client, router, opts.abi)).liquidity.v2.add
222
310
  .execute({
223
311
  contracts: withContracts({ sunswapV2Router: router }),
224
312
  tokenA,
@@ -228,9 +316,10 @@ function registerLiquidityCommands(program) {
228
316
  amountAMin: opts.minA,
229
317
  amountBMin: opts.minB,
230
318
  recipient: opts.to,
319
+ ttlSeconds: 1800,
231
320
  deadline: opts.deadline,
232
321
  })
233
- .then(mapTx),
322
+ .then((result) => mapTx(result)),
234
323
  });
235
324
  });
236
325
  liq
@@ -272,7 +361,7 @@ function registerLiquidityCommands(program) {
272
361
  confirmMsg: 'Remove V2 liquidity?',
273
362
  spinnerLabel: 'Removing V2 liquidity...',
274
363
  errorLabel: 'V2 remove liquidity failed',
275
- execute: (sdk) => sdk.liquidity.v2.remove
364
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, router, opts.abi)).liquidity.v2.remove
276
365
  .execute({
277
366
  contracts: withContracts({ sunswapV2Router: router }),
278
367
  tokenA,
@@ -281,9 +370,10 @@ function registerLiquidityCommands(program) {
281
370
  amountAMin: opts.minA,
282
371
  amountBMin: opts.minB,
283
372
  recipient: opts.to,
373
+ ttlSeconds: 1800,
284
374
  deadline: opts.deadline,
285
375
  })
286
- .then(mapTx),
376
+ .then((result) => mapTx(result)),
287
377
  });
288
378
  });
289
379
  // ---------------------------------------------------------------------------
@@ -295,7 +385,7 @@ function registerLiquidityCommands(program) {
295
385
  .option('--pm <address>', 'V3 NonfungiblePositionManager address (auto-detected by network)')
296
386
  .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
297
387
  .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
298
- .option('--fee <n>', 'Pool fee tier (default: 3000)')
388
+ .option('--fee <n>', `Pool fee tier (default: ${constants_1.DEFAULT_V3_FEE})`)
299
389
  .option('--tick-lower <n>', 'Lower tick (auto-computed if omitted)')
300
390
  .option('--tick-upper <n>', 'Upper tick (auto-computed if omitted)')
301
391
  .option('--amount0 <raw>', 'Desired amount of token0')
@@ -320,9 +410,11 @@ function registerLiquidityCommands(program) {
320
410
  }
321
411
  const token0 = toWTRXIfNative(token0Input, network);
322
412
  const token1 = toWTRXIfNative(token1Input, network);
323
- if (!opts.amount0 && !opts.amount1) {
324
- console.error('Error: At least one of --amount0 or --amount1 is required');
325
- process.exitCode = 1;
413
+ try {
414
+ assertLiquidityAmounts(opts.amount0, opts.amount1);
415
+ }
416
+ catch (err) {
417
+ (0, output_1.outputError)('Invalid liquidity amounts', err);
326
418
  return;
327
419
  }
328
420
  const token0Display = (0, tokens_1.getSymbolOrAddress)(token0Input, network);
@@ -338,32 +430,40 @@ function registerLiquidityCommands(program) {
338
430
  'Position Manager': pm,
339
431
  Token0: `${token0Display}${token0Note} (${token0})`,
340
432
  Token1: `${token1Display}${token1Note} (${token1})`,
341
- Fee: opts.fee || '3000 (default)',
433
+ Fee: opts.fee || `${constants_1.DEFAULT_V3_FEE} (default)`,
342
434
  'Tick Range': tickRange,
343
- Amount0: opts.amount0 || '(auto)',
344
- Amount1: opts.amount1 || '(auto)',
435
+ Amount0: opts.amount0 ?? '(not provided)',
436
+ Amount1: opts.amount1 ?? '(not provided)',
345
437
  Network: network,
346
438
  },
347
439
  confirmMsg: 'Mint V3 position?',
348
440
  spinnerLabel: 'Minting V3 position...',
349
441
  errorLabel: 'V3 mint failed',
350
- execute: (sdk) => sdk.liquidity.v3.add
442
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).liquidity.v3.add
351
443
  .execute({
352
444
  contracts: withContracts({ sunswapV3PositionManager: pm }),
353
445
  tokenA: token0,
354
446
  tokenB: token1,
355
- fee: opts.fee ? parseInt(opts.fee) : 3000,
447
+ fee: opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V3_FEE,
448
+ pool: await (0, liquidity_v3_1.resolveLegacyV3Pool)(sdk, {
449
+ token0,
450
+ token1,
451
+ fee: opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V3_FEE,
452
+ }),
356
453
  tickLower: opts.tickLower ? parseInt(opts.tickLower) : undefined,
357
454
  tickUpper: opts.tickUpper ? parseInt(opts.tickUpper) : undefined,
358
- tickRangeWidth: opts.tickLower === undefined && opts.tickUpper === undefined ? 100 : undefined,
455
+ tickRangeMode: 'legacy',
456
+ includeComputedMetadata: true,
457
+ tickRangeWidth: opts.tickLower === undefined || opts.tickUpper === undefined ? 100 : undefined,
359
458
  amount0,
360
459
  amount1,
361
460
  amount0Min,
362
461
  amount1Min,
363
462
  recipient: opts.recipient,
463
+ ttlSeconds: 1800,
364
464
  deadline: opts.deadline,
365
465
  })
366
- .then(mapTx),
466
+ .then((result) => mapTx(result, toV3PoolOrder(token0, token1, false, true)[0])),
367
467
  summarizeResult: (result) => {
368
468
  const out = {};
369
469
  if (result?.computedTicks) {
@@ -394,9 +494,11 @@ function registerLiquidityCommands(program) {
394
494
  .action(async (opts) => {
395
495
  const network = (0, context_1.getNetwork)();
396
496
  const pm = getV3PositionManager(network, opts.pm);
397
- if (!opts.amount0 && !opts.amount1) {
398
- console.error('Error: At least one of --amount0 or --amount1 is required');
399
- process.exitCode = 1;
497
+ try {
498
+ assertLiquidityAmounts(opts.amount0, opts.amount1);
499
+ }
500
+ catch (err) {
501
+ (0, output_1.outputError)('Invalid liquidity amounts', err);
400
502
  return;
401
503
  }
402
504
  await (0, command_1.writeAction)({
@@ -404,21 +506,32 @@ function registerLiquidityCommands(program) {
404
506
  summary: {
405
507
  'Position Manager': pm,
406
508
  'Token ID': opts.tokenId,
407
- Amount0: opts.amount0 || '(auto)',
408
- Amount1: opts.amount1 || '(auto)',
509
+ Amount0: opts.amount0 ?? '(not provided)',
510
+ Amount1: opts.amount1 ?? '(not provided)',
409
511
  Network: network,
410
512
  },
411
513
  confirmMsg: 'Increase V3 liquidity?',
412
514
  spinnerLabel: 'Increasing V3 liquidity...',
413
515
  errorLabel: 'V3 increase liquidity failed',
414
- execute: (sdk) => sdk.liquidity.v3.increase
516
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi, BigInt(opts.amount0 ?? '0') === 0n || BigInt(opts.amount1 ?? '0') === 0n
517
+ ? ['positions(uint256)']
518
+ : [])).liquidity.v3.increase
415
519
  .execute({
416
520
  contracts: withContracts({ sunswapV3PositionManager: pm }),
417
521
  tokenId: opts.tokenId,
418
522
  amount0: opts.amount0,
419
523
  amount1: opts.amount1,
524
+ includeComputedMetadata: true,
525
+ pool: BigInt(opts.amount0 ?? '0') === 0n || BigInt(opts.amount1 ?? '0') === 0n
526
+ ? await (0, liquidity_v3_1.resolveLegacyV3Pool)(sdk, {
527
+ tokenId: opts.tokenId,
528
+ positionManager: pm,
529
+ positionAbi: opts.abi,
530
+ })
531
+ : undefined,
420
532
  amount0Min: opts.min0,
421
533
  amount1Min: opts.min1,
534
+ ttlSeconds: 1800,
422
535
  deadline: opts.deadline,
423
536
  })
424
537
  .then(mapTx),
@@ -458,7 +571,7 @@ function registerLiquidityCommands(program) {
458
571
  confirmMsg: 'Decrease V3 liquidity?',
459
572
  spinnerLabel: 'Decreasing V3 liquidity...',
460
573
  errorLabel: 'V3 decrease liquidity failed',
461
- execute: (sdk) => sdk.positions.v3.remove
574
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).positions.v3.remove
462
575
  .execute({
463
576
  contracts: withContracts({ sunswapV3PositionManager: pm }),
464
577
  tokenId: opts.tokenId,
@@ -466,6 +579,7 @@ function registerLiquidityCommands(program) {
466
579
  amount0Min: opts.min0,
467
580
  amount1Min: opts.min1,
468
581
  collectFees: false,
582
+ ttlSeconds: 1800,
469
583
  deadline: opts.deadline,
470
584
  })
471
585
  .then(mapTx),
@@ -492,11 +606,12 @@ function registerLiquidityCommands(program) {
492
606
  confirmMsg: 'Collect V3 fees?',
493
607
  spinnerLabel: 'Collecting V3 fees...',
494
608
  errorLabel: 'V3 collect failed',
495
- execute: (sdk) => sdk.positions.v3.collect
609
+ execute: async (sdk) => (await (0, factory_1.withLiquidityAbi)(sdk, pm, opts.abi)).positions.v3.collect
496
610
  .execute({
497
611
  contracts: withContracts({ sunswapV3PositionManager: pm }),
498
612
  tokenId: opts.tokenId,
499
613
  recipient: opts.recipient,
614
+ estimateFees: true,
500
615
  })
501
616
  .then(mapTx),
502
617
  summarizeResult: (result) => {
@@ -519,7 +634,7 @@ function registerLiquidityCommands(program) {
519
634
  .description('Mint a new SUNSWAP V4 concentrated liquidity position')
520
635
  .requiredOption('--token0 <tokenOrAddress>', 'Token0 (symbol like TRX/USDT or address)')
521
636
  .requiredOption('--token1 <tokenOrAddress>', 'Token1 (symbol like TRX/USDT or address)')
522
- .option('--fee <n>', 'Pool fee tier (e.g. 500)')
637
+ .option('--fee <n>', `Pool fee tier (default: ${constants_1.DEFAULT_V4_FEE})`)
523
638
  .option('--tick-lower <n>', 'Lower tick (auto-computed if omitted)')
524
639
  .option('--tick-upper <n>', 'Upper tick (auto-computed if omitted)')
525
640
  .option('--amount0 <raw>', 'Desired amount of token0')
@@ -541,56 +656,81 @@ function registerLiquidityCommands(program) {
541
656
  process.exitCode = 1;
542
657
  return;
543
658
  }
544
- const token0 = toWTRXIfNative(token0Input, network);
545
- const token1 = toWTRXIfNative(token1Input, network);
659
+ // V4 identifies native TRX with the zero address. WTRX is a different pool currency.
660
+ const token0 = token0Input;
661
+ const token1 = token1Input;
546
662
  const token0Display = (0, tokens_1.getSymbolOrAddress)(token0Input, network);
547
663
  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;
554
- if (!opts.amount0 && !opts.amount1) {
555
- console.error('Error: At least one of --amount0 or --amount1 is required');
556
- process.exitCode = 1;
664
+ const fee = opts.fee ? parseInt(opts.fee) : constants_1.DEFAULT_V4_FEE;
665
+ const tickLower = opts.tickLower !== undefined ? parseInt(opts.tickLower) : undefined;
666
+ const tickUpper = opts.tickUpper !== undefined ? parseInt(opts.tickUpper) : undefined;
667
+ let slippage;
668
+ try {
669
+ slippage = parseOptionalSlippage(opts.slippage);
670
+ }
671
+ catch (err) {
672
+ (0, output_1.outputError)('Invalid --slippage', err);
673
+ return;
674
+ }
675
+ try {
676
+ assertLiquidityAmounts(opts.amount0, opts.amount1);
677
+ }
678
+ catch (err) {
679
+ (0, output_1.outputError)('Invalid liquidity amounts', err);
557
680
  return;
558
681
  }
559
682
  await (0, command_1.writeAction)({
560
683
  title: 'V4 Mint Position',
561
684
  summary: {
562
- Token0: `${token0Display}${token0Note} (${token0})`,
563
- Token1: `${token1Display}${token1Note} (${token1})`,
564
- Fee: opts.fee || '3000 (default)',
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)',
685
+ Token0: `${token0Display} (${token0})`,
686
+ Token1: `${token1Display} (${token1})`,
687
+ Fee: opts.fee || `${constants_1.DEFAULT_V4_FEE} (default)`,
688
+ 'Tick Range': tickLower !== undefined && tickUpper !== undefined
689
+ ? `[${tickLower}, ${tickUpper}]`
690
+ : '(auto)',
691
+ Amount0: opts.amount0 ?? '(not provided)',
692
+ Amount1: opts.amount1 ?? '(not provided)',
693
+ Slippage: slippage?.display ?? '(default)',
571
694
  'Create Pool': opts.createPool ? 'Yes' : 'No',
572
695
  Network: network,
573
696
  },
574
697
  confirmMsg: 'Mint V4 position?',
575
698
  spinnerLabel: 'Minting V4 position...',
576
699
  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),
700
+ execute: async (sdk) => {
701
+ const ticks = await (0, liquidity_v4_1.resolveV4MintTicks)(sdk, {
702
+ token0,
703
+ token1,
704
+ fee,
705
+ tickLower,
706
+ tickUpper,
707
+ sqrtPriceX96: opts.sqrtPrice,
708
+ createPool: opts.createPool,
709
+ });
710
+ return sdk.liquidity.v4.add
711
+ .execute({
712
+ token0,
713
+ token1,
714
+ fee,
715
+ ...ticks,
716
+ amount0: opts.amount0,
717
+ amount1: opts.amount1,
718
+ slippage: slippage?.sdk,
719
+ includeComputedMetadata: true,
720
+ transactionMode: 'multicall',
721
+ recipient: opts.recipient,
722
+ sweepRecipient: opts.recipient,
723
+ ttlSeconds: 1800,
724
+ deadline: opts.deadline,
725
+ sqrtPriceX96: opts.sqrtPrice,
726
+ })
727
+ .then((result) => {
728
+ const mapped = mapTx(result);
729
+ return tickLower === undefined || tickUpper === undefined
730
+ ? { ...mapped, computedTicks: ticks }
731
+ : mapped;
732
+ });
733
+ },
594
734
  summarizeResult: (result) => {
595
735
  const out = {};
596
736
  if (result?.poolCreated !== undefined)
@@ -613,56 +753,81 @@ function registerLiquidityCommands(program) {
613
753
  .command('v4:increase')
614
754
  .description('Increase liquidity of an existing V4 position')
615
755
  .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')
756
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
757
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
758
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
619
759
  .option('--amount0 <raw>', 'Additional amount of token0')
620
760
  .option('--amount1 <raw>', 'Additional amount of token1')
621
761
  .option('--slippage <n>', 'Slippage tolerance as decimal')
622
762
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
623
763
  .action(async (opts) => {
624
764
  const network = (0, context_1.getNetwork)();
625
- let token0Input, token1Input;
765
+ let expectedPair, expectedFee;
626
766
  try {
627
- token0Input = (0, tokens_1.resolveTokenAddress)(opts.token0, network);
628
- token1Input = (0, tokens_1.resolveTokenAddress)(opts.token1, network);
767
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
768
+ expectedFee = parseOptionalV4Fee(opts.fee);
629
769
  }
630
770
  catch (err) {
631
- console.error(err.message);
632
- process.exitCode = 1;
771
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
633
772
  return;
634
773
  }
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
- if (!opts.amount0 && !opts.amount1) {
640
- console.error('Error: At least one of --amount0 or --amount1 is required');
641
- process.exitCode = 1;
774
+ let slippage;
775
+ try {
776
+ slippage = parseOptionalSlippage(opts.slippage);
777
+ }
778
+ catch (err) {
779
+ (0, output_1.outputError)('Invalid --slippage', err);
642
780
  return;
643
781
  }
782
+ try {
783
+ assertLiquidityAmounts(opts.amount0, opts.amount1);
784
+ }
785
+ catch (err) {
786
+ (0, output_1.outputError)('Invalid liquidity amounts', err);
787
+ return;
788
+ }
789
+ const summary = {
790
+ 'Token ID': opts.tokenId,
791
+ Token0: expectedPair.token0 ?? '(from tokenId)',
792
+ Token1: expectedPair.token1 ?? '(from tokenId)',
793
+ Fee: expectedFee ?? '(from tokenId)',
794
+ Amount0: opts.amount0 ?? '(not provided)',
795
+ Amount1: opts.amount1 ?? '(not provided)',
796
+ Slippage: slippage?.display ?? '(default)',
797
+ Network: network,
798
+ };
799
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
644
800
  await (0, command_1.writeAction)({
645
801
  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,
802
+ summary,
803
+ prepareLabel: 'Loading V4 position...',
804
+ prepare: async (sdk) => {
805
+ const prepared = await loadPosition(sdk);
806
+ const [amount0, amount1] = orderV4PositionValues(prepared.reversed, opts.amount0, opts.amount1);
807
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network), {
808
+ Amount0: amount0 ?? '(not provided)',
809
+ Amount1: amount1 ?? '(not provided)',
810
+ });
653
811
  },
654
812
  confirmMsg: 'Increase V4 liquidity?',
655
813
  spinnerLabel: 'Increasing V4 liquidity...',
656
814
  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),
815
+ execute: async (sdk) => {
816
+ const prepared = await loadPosition(sdk);
817
+ const [amount0, amount1] = orderV4PositionValues(prepared.reversed, opts.amount0, opts.amount1);
818
+ return sdk.liquidity.v4.increase
819
+ .execute({
820
+ tokenId: opts.tokenId,
821
+ amount0,
822
+ amount1,
823
+ slippage: slippage?.sdk,
824
+ includeComputedMetadata: true,
825
+ transactionMode: 'multicall',
826
+ ttlSeconds: 1800,
827
+ deadline: opts.deadline,
828
+ })
829
+ .then(mapTx);
830
+ },
666
831
  summarizeResult: (result) => {
667
832
  const out = {};
668
833
  if (result?.computedAmounts) {
@@ -680,51 +845,77 @@ function registerLiquidityCommands(program) {
680
845
  .description('Decrease liquidity of an existing V4 position')
681
846
  .requiredOption('--token-id <id>', 'Position NFT token ID')
682
847
  .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')
848
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
849
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
850
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
686
851
  .option('--min0 <raw>', 'Minimum amount of token0 to receive')
687
852
  .option('--min1 <raw>', 'Minimum amount of token1 to receive')
688
853
  .option('--slippage <n>', 'Slippage tolerance as decimal')
689
854
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
690
855
  .action(async (opts) => {
691
856
  const network = (0, context_1.getNetwork)();
692
- let token0Input, token1Input;
857
+ let expectedPair, expectedFee;
693
858
  try {
694
- token0Input = (0, tokens_1.resolveTokenAddress)(opts.token0, network);
695
- token1Input = (0, tokens_1.resolveTokenAddress)(opts.token1, network);
859
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
860
+ expectedFee = parseOptionalV4Fee(opts.fee);
696
861
  }
697
862
  catch (err) {
698
- console.error(err.message);
699
- process.exitCode = 1;
863
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
700
864
  return;
701
865
  }
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);
866
+ let slippage;
867
+ try {
868
+ slippage = parseOptionalSlippage(opts.slippage);
869
+ }
870
+ catch (err) {
871
+ (0, output_1.outputError)('Invalid --slippage', err);
872
+ return;
873
+ }
874
+ const summary = {
875
+ 'Token ID': opts.tokenId,
876
+ Liquidity: opts.liquidity,
877
+ Token0: expectedPair.token0 ?? '(from tokenId)',
878
+ Token1: expectedPair.token1 ?? '(from tokenId)',
879
+ Fee: expectedFee ?? '(from tokenId)',
880
+ Min0: opts.min0 ?? '(SDK derived)',
881
+ Min1: opts.min1 ?? '(SDK derived)',
882
+ Slippage: slippage?.display ?? '(default)',
883
+ Network: network,
884
+ };
885
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
706
886
  await (0, command_1.writeAction)({
707
887
  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,
888
+ summary,
889
+ prepareLabel: 'Loading V4 position...',
890
+ prepare: async (sdk) => {
891
+ const prepared = await loadPosition(sdk);
892
+ const [min0, min1] = orderV4PositionValues(prepared.reversed, opts.min0, opts.min1);
893
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network), {
894
+ Min0: min0 ?? '(SDK derived)',
895
+ Min1: min1 ?? '(SDK derived)',
896
+ });
714
897
  },
715
898
  confirmMsg: 'Decrease V4 liquidity?',
716
899
  spinnerLabel: 'Decreasing V4 liquidity...',
717
900
  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),
901
+ execute: async (sdk) => {
902
+ const prepared = await loadPosition(sdk);
903
+ const [amount0Min, amount1Min] = orderV4PositionValues(prepared.reversed, opts.min0, opts.min1);
904
+ return sdk.positions.v4.remove
905
+ .execute({
906
+ tokenId: opts.tokenId,
907
+ liquidity: opts.liquidity,
908
+ amount0Min,
909
+ amount1Min,
910
+ slippage: slippage?.sdk,
911
+ includeComputedMetadata: true,
912
+ transactionMode: 'multicall',
913
+ settlementMode: 'close-currency',
914
+ ttlSeconds: 1800,
915
+ deadline: opts.deadline,
916
+ })
917
+ .then(mapTx);
918
+ },
728
919
  summarizeResult: (result) => {
729
920
  const out = {};
730
921
  if (result?.computedAmountMin) {
@@ -741,52 +932,52 @@ function registerLiquidityCommands(program) {
741
932
  .command('v4:collect')
742
933
  .description('Collect accrued fees from an existing V4 position')
743
934
  .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')
935
+ .option('--token0 <tokenOrAddress>', 'Expected token0; provide together with --token1')
936
+ .option('--token1 <tokenOrAddress>', 'Expected token1; provide together with --token0')
937
+ .option('--fee <n>', 'Expected pool fee tier (validated against the position)')
747
938
  .option('--deadline <timestamp>', 'Unix timestamp deadline')
748
939
  .action(async (opts) => {
749
940
  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
- }
941
+ let expectedPair, expectedFee;
942
+ try {
943
+ expectedPair = resolveOptionalV4Pair(opts.token0, opts.token1, network);
944
+ expectedFee = parseOptionalV4Fee(opts.fee);
761
945
  }
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
- }
946
+ catch (err) {
947
+ (0, output_1.outputError)('Invalid V4 position assertions', err);
948
+ return;
772
949
  }
950
+ const summary = {
951
+ 'Token ID': opts.tokenId,
952
+ Token0: expectedPair.token0 ?? '(from tokenId)',
953
+ Token1: expectedPair.token1 ?? '(from tokenId)',
954
+ Fee: expectedFee ?? '(from tokenId)',
955
+ Network: network,
956
+ };
957
+ const loadPosition = createV4PositionLoader(opts.tokenId, expectedPair, expectedFee);
773
958
  await (0, command_1.writeAction)({
774
959
  title: 'V4 Collect Fees',
775
- summary: {
776
- 'Token ID': opts.tokenId,
777
- Token0: token0 || '(auto)',
778
- Token1: token1 || '(auto)',
779
- Network: network,
960
+ summary,
961
+ prepareLabel: 'Loading V4 position...',
962
+ prepare: async (sdk) => {
963
+ const prepared = await loadPosition(sdk);
964
+ Object.assign(summary, v4PositionTokenSummary(prepared.poolKey, network));
780
965
  },
781
966
  confirmMsg: 'Collect V4 fees?',
782
967
  spinnerLabel: 'Collecting V4 fees...',
783
968
  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),
969
+ execute: async (sdk) => {
970
+ await loadPosition(sdk);
971
+ return sdk.positions.v4.collect
972
+ .execute({
973
+ tokenId: opts.tokenId,
974
+ transactionMode: 'multicall',
975
+ settlementMode: 'close-currency',
976
+ ttlSeconds: 1800,
977
+ deadline: opts.deadline,
978
+ })
979
+ .then(mapTx);
980
+ },
790
981
  });
791
982
  });
792
983
  liq
@@ -811,7 +1002,7 @@ function registerLiquidityCommands(program) {
811
1002
  currency1: result.poolKey?.currency1,
812
1003
  fee: fee === undefined ? undefined : String(fee),
813
1004
  tickSpacing: result.poolKey?.tickSpacing ??
814
- (Number.isFinite(Number(fee)) ? tickSpacingForFee(Number(fee)) : undefined),
1005
+ (Number.isFinite(Number(fee)) ? (0, liquidity_v4_1.v4TickSpacingForFee)(Number(fee)) : undefined),
815
1006
  tickLower: result.tickLower,
816
1007
  tickUpper: result.tickUpper,
817
1008
  liquidity: result.liquidity,