@sun-protocol/sun-sdk-protocols 0.1.0-beta.0

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 (60) hide show
  1. package/README.md +30 -0
  2. package/dist/chunk-5XDX5563.js +99 -0
  3. package/dist/chunk-5XDX5563.js.map +1 -0
  4. package/dist/chunk-C2YCVBPI.js +212 -0
  5. package/dist/chunk-C2YCVBPI.js.map +1 -0
  6. package/dist/chunk-ECCGOXNA.js +1317 -0
  7. package/dist/chunk-ECCGOXNA.js.map +1 -0
  8. package/dist/chunk-HD2S3Q7L.js +746 -0
  9. package/dist/chunk-HD2S3Q7L.js.map +1 -0
  10. package/dist/chunk-L5TZCDPH.js +561 -0
  11. package/dist/chunk-L5TZCDPH.js.map +1 -0
  12. package/dist/chunk-OM4OW4KB.js +224 -0
  13. package/dist/chunk-OM4OW4KB.js.map +1 -0
  14. package/dist/chunk-PEGREDLT.js +935 -0
  15. package/dist/chunk-PEGREDLT.js.map +1 -0
  16. package/dist/chunk-TSHXXRH2.js +103 -0
  17. package/dist/chunk-TSHXXRH2.js.map +1 -0
  18. package/dist/chunk-VFVKMC4H.js +521 -0
  19. package/dist/chunk-VFVKMC4H.js.map +1 -0
  20. package/dist/chunk-YMGZDXI4.js +1209 -0
  21. package/dist/chunk-YMGZDXI4.js.map +1 -0
  22. package/dist/common-8VQQ0FSU.d.cts +146 -0
  23. package/dist/common-8VQQ0FSU.d.ts +146 -0
  24. package/dist/execute-BNKh6dT6.d.cts +187 -0
  25. package/dist/execute-CVhcKZxF.d.ts +187 -0
  26. package/dist/index.cjs +5619 -0
  27. package/dist/index.cjs.map +1 -0
  28. package/dist/index.d.cts +139 -0
  29. package/dist/index.d.ts +139 -0
  30. package/dist/index.js +200 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/intents-BSXq1HvW.d.cts +200 -0
  33. package/dist/intents-CwOttD75.d.ts +200 -0
  34. package/dist/liquidity/index.cjs +2441 -0
  35. package/dist/liquidity/index.cjs.map +1 -0
  36. package/dist/liquidity/index.d.cts +83 -0
  37. package/dist/liquidity/index.d.ts +83 -0
  38. package/dist/liquidity/index.js +32 -0
  39. package/dist/liquidity/index.js.map +1 -0
  40. package/dist/positions/index.cjs +1544 -0
  41. package/dist/positions/index.cjs.map +1 -0
  42. package/dist/positions/index.d.cts +159 -0
  43. package/dist/positions/index.d.ts +159 -0
  44. package/dist/positions/index.js +25 -0
  45. package/dist/positions/index.js.map +1 -0
  46. package/dist/pump/index.cjs +1178 -0
  47. package/dist/pump/index.cjs.map +1 -0
  48. package/dist/pump/index.d.cts +16 -0
  49. package/dist/pump/index.d.ts +16 -0
  50. package/dist/pump/index.js +29 -0
  51. package/dist/pump/index.js.map +1 -0
  52. package/dist/swap/index.cjs +2259 -0
  53. package/dist/swap/index.cjs.map +1 -0
  54. package/dist/swap/index.d.cts +33 -0
  55. package/dist/swap/index.d.ts +33 -0
  56. package/dist/swap/index.js +61 -0
  57. package/dist/swap/index.js.map +1 -0
  58. package/dist/types-BTPdCC7k.d.cts +160 -0
  59. package/dist/types-BfrouFmO.d.ts +160 -0
  60. package/package.json +94 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/liquidity/v2.ts","../src/liquidity/v4.ts","../src/liquidity/client.ts"],"sourcesContent":["import {\n CurrencyAmount,\n SDKError,\n TRON_ZERO_ADDRESS,\n assertTronAddress,\n type ContractCallAction,\n type TransactionIntent,\n type TronAddress,\n} from '@sun-protocol/sun-sdk-core'\nimport {\n Pair,\n buildV2AddLiquidityAction,\n buildV2AddLiquidityEthAction,\n buildV2FactoryFeeToRead,\n buildV2FactoryPairRead,\n buildV2LpApproveAction,\n buildV2PairAllowanceRead,\n buildV2PairBalanceRead,\n buildV2PairKLastRead,\n buildV2PairReservesRead,\n buildV2PairTotalSupplyRead,\n buildV2RemoveLiquidityAction,\n buildV2RemoveLiquidityEthAction,\n computeV2PairAddress,\n getV2AddLiquidityMinimums,\n getV2RemoveLiquidityMinimums,\n normalizeV2ReserveResult,\n quoteV2LiquidityAmount,\n} from '@sun-protocol/sun-sdk-sunswap-v2'\nimport { planApproval } from '../approval/plan.js'\nimport {\n nextPlanId,\n normalizeBaseUnitAmount,\n normalizeDeadline,\n normalizeRecipient,\n parseSlippage,\n slippageToBips,\n} from '../common.js'\nimport {\n createContextExecutor,\n requireWalletAddress,\n resolveProtocolContract,\n type ProtocolsContext,\n} from '../context.js'\nimport { executeTransactionPlan } from '../execute-plan.js'\nimport {\n readMulticallRequired,\n readRequiredContract,\n} from '../internal/reads.js'\nimport {\n evmHexToTronAddress,\n normalizeLiquidityPercentage,\n normalizeProtocolToken,\n type ProtocolToken,\n} from '../internal/tokens.js'\nimport { attachApprovalIntent } from '../internal/intents.js'\nimport type {\n TransactionPlan,\n TransactionPlanExecutionResult,\n} from '../types/plan.js'\nimport type {\n V2AddLiquidityInput,\n V2RemoveLiquidityInput,\n} from './types.js'\nimport {\n liquidityIntentScope,\n SUNSWAP_V2_LIQUIDITY_PROTOCOL_ID,\n} from './intents.js'\n\nconst DEFAULT_SLIPPAGE = '0.5%'\n\ninterface V2PairContext {\n readonly tokenA: ProtocolToken\n readonly tokenB: ProtocolToken\n readonly tokenAContract: TronAddress\n readonly tokenBContract: TronAddress\n readonly pair: TronAddress\n readonly tokenASortsBefore: boolean\n}\n\ninterface V2PairReserves {\n readonly reserveA: string\n readonly reserveB: string\n}\n\nfunction parseContractInteger(value: unknown, label: string): string {\n const normalized = Array.isArray(value) && value.length === 1 ? value[0] : value\n if (\n normalized === null\n || normalized === undefined\n || (typeof normalized !== 'string'\n && typeof normalized !== 'number'\n && typeof normalized !== 'bigint'\n && typeof normalized !== 'object')\n ) {\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be an integer-like contract result`, { value })\n }\n\n try {\n const text = normalized.toString()\n if (!/^\\d+$/.test(text)) throw new Error('not an unsigned integer')\n return BigInt(text).toString()\n } catch {\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be an integer-like contract result`, { value })\n }\n}\n\nfunction parseContractAddress(value: unknown, label: string): TronAddress {\n const normalized = Array.isArray(value) && value.length === 1 ? value[0] : value\n if (typeof normalized !== 'string') {\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be an address contract result`, { value })\n }\n\n try {\n return /^0x[0-9a-fA-F]{40}$/.test(normalized)\n ? evmHexToTronAddress(normalized, label)\n : assertTronAddress(normalized, label)\n } catch {\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be an address contract result`, { value })\n }\n}\n\nfunction createPairContext(\n context: ProtocolsContext,\n tokenAInput: string,\n tokenBInput: string,\n): V2PairContext {\n const tokenA = normalizeProtocolToken(context, tokenAInput, 'tokenA')\n const tokenB = normalizeProtocolToken(context, tokenBInput, 'tokenB')\n\n if (tokenA.token.equals(tokenB.token)) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V2 liquidity tokens must be different', {\n tokenA: tokenAInput,\n tokenB: tokenBInput,\n })\n }\n\n return {\n tokenA,\n tokenB,\n tokenAContract: tokenA.kind === 'native' ? tokenA.wrappedContractAddress : tokenA.contractAddress,\n tokenBContract: tokenB.kind === 'native' ? tokenB.wrappedContractAddress : tokenB.contractAddress,\n pair: computeV2PairAddress({\n network: context.network,\n tokenA: tokenA.kind === 'native' ? tokenA.wrappedContractAddress : tokenA.contractAddress,\n tokenB: tokenB.kind === 'native' ? tokenB.wrappedContractAddress : tokenB.contractAddress,\n }),\n tokenASortsBefore: tokenA.token.sortsBefore(tokenB.token),\n }\n}\n\nfunction parsePairReserves(result: unknown, tokenASortsBefore: boolean): V2PairReserves {\n if (!Array.isArray(result) || result.length < 2) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair reserves result is malformed', { result })\n }\n\n let normalized: { readonly reserve0: string; readonly reserve1: string }\n try {\n normalized = normalizeV2ReserveResult(result)\n } catch {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair reserves result is malformed', { result })\n }\n\n const reserve0 = parseContractInteger(normalized.reserve0, 'reserve0')\n const reserve1 = parseContractInteger(normalized.reserve1, 'reserve1')\n return tokenASortsBefore\n ? { reserveA: reserve0, reserveB: reserve1 }\n : { reserveA: reserve1, reserveB: reserve0 }\n}\n\nfunction resolveAddAmounts(input: {\n readonly amountADesired: string\n readonly amountBDesired: string\n readonly reserves: V2PairReserves\n}): { readonly amountA: string; readonly amountB: string } {\n const reserveA = BigInt(input.reserves.reserveA)\n const reserveB = BigInt(input.reserves.reserveB)\n if (reserveA === 0n && reserveB === 0n) {\n return { amountA: input.amountADesired, amountB: input.amountBDesired }\n }\n if (reserveA === 0n || reserveB === 0n) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair has inconsistent zero reserves', {\n reserveA: input.reserves.reserveA,\n reserveB: input.reserves.reserveB,\n })\n }\n\n const amountBOptimal = quoteV2LiquidityAmount(\n input.amountADesired,\n input.reserves.reserveA,\n input.reserves.reserveB,\n )\n if (BigInt(amountBOptimal) <= BigInt(input.amountBDesired)) {\n return { amountA: input.amountADesired, amountB: amountBOptimal }\n }\n\n const amountAOptimal = quoteV2LiquidityAmount(\n input.amountBDesired,\n input.reserves.reserveB,\n input.reserves.reserveA,\n )\n if (BigInt(amountAOptimal) > BigInt(input.amountADesired)) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair reserve quote exceeds desired liquidity amounts', {\n amountADesired: input.amountADesired,\n amountBDesired: input.amountBDesired,\n amountAOptimal,\n amountBOptimal,\n })\n }\n return { amountA: amountAOptimal, amountB: input.amountBDesired }\n}\n\nfunction createPairEntity(pair: V2PairContext, reserves: V2PairReserves): Pair {\n return new Pair(\n CurrencyAmount.fromRawAmount(pair.tokenA.token, reserves.reserveA),\n CurrencyAmount.fromRawAmount(pair.tokenB.token, reserves.reserveB),\n )\n}\n\nfunction validateAddAmounts(\n pair: V2PairContext,\n reserves: V2PairReserves,\n amounts: { readonly amountA: string; readonly amountB: string },\n): void {\n if (BigInt(amounts.amountA) === 0n || BigInt(amounts.amountB) === 0n) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V2 add liquidity amounts must remain positive after reserve optimization', {\n ...amounts,\n ...reserves,\n })\n }\n\n if (BigInt(reserves.reserveA) !== 0n || BigInt(reserves.reserveB) !== 0n) return\n const pairEntity = createPairEntity(pair, reserves)\n try {\n pairEntity.getLiquidityMinted(\n CurrencyAmount.fromRawAmount(pairEntity.liquidityToken, '0'),\n CurrencyAmount.fromRawAmount(pair.tokenA.token, amounts.amountA),\n CurrencyAmount.fromRawAmount(pair.tokenB.token, amounts.amountB),\n )\n } catch {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'Initial V2 liquidity is too small to exceed MINIMUM_LIQUIDITY', {\n ...amounts,\n })\n }\n}\n\nasync function planTokenApproval(input: {\n readonly context: ProtocolsContext\n readonly owner: TronAddress\n readonly token: ProtocolToken\n readonly amount: string\n readonly mode: V2AddLiquidityInput['approval']\n readonly router: TronAddress\n}): Promise<readonly ContractCallAction[]> {\n if (input.token.kind === 'native') return []\n const approval = await planApproval(\n input.context,\n {\n asset: { type: 'token', token: input.token.contractAddress },\n owner: input.owner,\n spender: input.router,\n amount: input.amount,\n },\n { mode: input.mode ?? 'auto' },\n )\n return attachApprovalIntent(\n approval.actions,\n liquidityIntentScope(SUNSWAP_V2_LIQUIDITY_PROTOCOL_ID, 'add-liquidity'),\n input.token.token.symbol ?? input.token.input,\n ) as readonly ContractCallAction[]\n}\n\nfunction buildAddAction(input: {\n readonly context: ProtocolsContext\n readonly planId: string\n readonly pair: V2PairContext\n readonly amountA: string\n readonly amountB: string\n readonly amountAMin: string\n readonly amountBMin: string\n readonly recipient: TronAddress\n readonly deadline: string\n readonly router: TronAddress\n readonly feeLimit?: number\n}): ContractCallAction {\n const options = {\n network: input.context.network,\n router: input.router,\n recipient: input.recipient,\n deadline: input.deadline,\n id: `${input.planId}-tx`,\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n }\n const action = input.pair.tokenA.kind === 'native'\n ? buildV2AddLiquidityEthAction({\n ...options,\n token: input.pair.tokenB.token,\n amountTokenDesired: input.amountB,\n amountEthDesired: input.amountA,\n amountTokenMin: input.amountBMin,\n amountEthMin: input.amountAMin,\n })\n : input.pair.tokenB.kind === 'native'\n ? buildV2AddLiquidityEthAction({\n ...options,\n token: input.pair.tokenA.token,\n amountTokenDesired: input.amountA,\n amountEthDesired: input.amountB,\n amountTokenMin: input.amountAMin,\n amountEthMin: input.amountBMin,\n })\n : buildV2AddLiquidityAction({\n ...options,\n tokenA: input.pair.tokenA.token,\n tokenB: input.pair.tokenB.token,\n amountADesired: input.amountA,\n amountBDesired: input.amountB,\n amountAMin: input.amountAMin,\n amountBMin: input.amountBMin,\n })\n const intent: TransactionIntent = {\n kind: 'add-liquidity',\n scope: liquidityIntentScope(SUNSWAP_V2_LIQUIDITY_PROTOCOL_ID, 'add-liquidity'),\n }\n return {\n ...action,\n intent,\n }\n}\n\nfunction buildRemoveAction(input: {\n readonly context: ProtocolsContext\n readonly planId: string\n readonly pair: V2PairContext\n readonly liquidity: string\n readonly amountAMin: string\n readonly amountBMin: string\n readonly recipient: TronAddress\n readonly deadline: string\n readonly router: TronAddress\n readonly feeLimit?: number\n}): ContractCallAction {\n const options = {\n network: input.context.network,\n router: input.router,\n liquidity: input.liquidity,\n recipient: input.recipient,\n deadline: input.deadline,\n id: `${input.planId}-tx`,\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n }\n let action: ContractCallAction\n if (input.pair.tokenA.kind === 'native') {\n action = buildV2RemoveLiquidityEthAction({\n ...options,\n token: input.pair.tokenB.token,\n amountTokenMin: input.amountBMin,\n amountEthMin: input.amountAMin,\n })\n } else if (input.pair.tokenB.kind === 'native') {\n action = buildV2RemoveLiquidityEthAction({\n ...options,\n token: input.pair.tokenA.token,\n amountTokenMin: input.amountAMin,\n amountEthMin: input.amountBMin,\n })\n } else {\n action = buildV2RemoveLiquidityAction({\n ...options,\n tokenA: input.pair.tokenA.token,\n tokenB: input.pair.tokenB.token,\n amountAMin: input.amountAMin,\n amountBMin: input.amountBMin,\n })\n }\n return {\n ...action,\n intent: {\n kind: 'remove-liquidity',\n scope: liquidityIntentScope(SUNSWAP_V2_LIQUIDITY_PROTOCOL_ID, 'remove-liquidity'),\n },\n }\n}\n\nfunction resolveRemoveLiquidity(input: V2RemoveLiquidityInput, balance: string): string {\n const hasLiquidity = input.liquidity !== undefined\n const hasPercentage = input.percentage !== undefined\n if (hasLiquidity === hasPercentage) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V2 remove requires exactly one of liquidity or percentage')\n }\n\n const liquidity = hasLiquidity\n ? BigInt(normalizeBaseUnitAmount(input.liquidity, 'liquidity'))\n : (() => {\n const percentage = normalizeLiquidityPercentage(input.percentage, 'percentage')\n const numerator = BigInt(percentage.numerator.toString())\n const denominator = BigInt(percentage.denominator.toString())\n const result = (BigInt(balance) * numerator) / denominator\n if (result <= 0n) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'percentage resolves to zero liquidity', {\n balance,\n percentage: percentage.toSignificant(),\n })\n }\n return result\n })()\n\n if (liquidity > BigInt(balance)) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'liquidity cannot exceed wallet LP balance', {\n liquidity: liquidity.toString(),\n balance,\n })\n }\n return liquidity.toString()\n}\n\nexport async function planV2AddLiquidity(\n context: ProtocolsContext,\n input: V2AddLiquidityInput,\n): Promise<TransactionPlan> {\n const router = resolveProtocolContract(context, input.contracts, 'sunswapV2Router')\n const planId = nextPlanId(context, 'liquidity-v2-add')\n const owner = await requireWalletAddress(context, 'V2 add liquidity')\n const recipient = await normalizeRecipient(context, input.recipient, 'V2 add liquidity', owner)\n const deadline = normalizeDeadline(context, input)\n const slippageInput = input.slippage ?? DEFAULT_SLIPPAGE\n const slippage = parseSlippage(slippageInput)\n const pair = createPairContext(context, input.tokenA, input.tokenB)\n const amountADesired = normalizeBaseUnitAmount(input.amountADesired, 'amountADesired')\n const amountBDesired = normalizeBaseUnitAmount(input.amountBDesired, 'amountBDesired')\n const deployedPair = parseContractAddress(await readRequiredContract<unknown>(\n context,\n buildV2FactoryPairRead({\n network: context.network,\n tokenA: pair.tokenAContract,\n tokenB: pair.tokenBContract,\n }),\n 'V2 add liquidity pair lookup',\n ), 'V2 factory pair')\n if (deployedPair !== TRON_ZERO_ADDRESS && deployedPair !== pair.pair) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 factory pair does not match the configured CREATE2 pair', {\n factoryPair: deployedPair,\n computedPair: pair.pair,\n })\n }\n const reserves = deployedPair === TRON_ZERO_ADDRESS\n ? { reserveA: '0', reserveB: '0' }\n : parsePairReserves(await readRequiredContract<unknown>(\n context,\n buildV2PairReservesRead(pair.pair),\n 'V2 add liquidity reserves',\n ), pair.tokenASortsBefore)\n const amounts = resolveAddAmounts({ amountADesired, amountBDesired, reserves })\n validateAddAmounts(pair, reserves, amounts)\n const slippageMinimums = getV2AddLiquidityMinimums(amounts, slippage)\n const minimums = {\n amountAMin: input.amountAMin === undefined\n ? slippageMinimums.amountAMin\n : normalizeBaseUnitAmount(input.amountAMin, 'amountAMin', { allowZero: true }),\n amountBMin: input.amountBMin === undefined\n ? slippageMinimums.amountBMin\n : normalizeBaseUnitAmount(input.amountBMin, 'amountBMin', { allowZero: true }),\n }\n const approvals = [\n ...await planTokenApproval({ context, owner, token: pair.tokenA, amount: amounts.amountA, mode: input.approval, router }),\n ...await planTokenApproval({ context, owner, token: pair.tokenB, amount: amounts.amountB, mode: input.approval, router }),\n ]\n const transaction = buildAddAction({\n context,\n planId,\n pair,\n amountA: amounts.amountA,\n amountB: amounts.amountB,\n amountAMin: minimums.amountAMin,\n amountBMin: minimums.amountBMin,\n recipient,\n deadline,\n router,\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n })\n\n return {\n id: planId,\n kind: 'liquidity',\n network: context.network,\n owner,\n summary: {\n title: 'Add SunSwap V2 liquidity',\n lines: [`Pair ${pair.pair}`, `Recipient ${recipient}`],\n },\n approvals,\n transactions: [transaction],\n metadata: {\n protocol: 'sunswap-v2',\n operation: 'add-liquidity',\n pair: pair.pair,\n tokenA: input.tokenA,\n tokenB: input.tokenB,\n amountADesired,\n amountBDesired,\n amountA: amounts.amountA,\n amountB: amounts.amountB,\n amountAMin: minimums.amountAMin,\n amountBMin: minimums.amountBMin,\n owner,\n recipient,\n deadline,\n slippageBips: slippageToBips(slippageInput),\n approvalMode: input.approval ?? 'auto',\n },\n }\n}\n\nexport async function planV2RemoveLiquidity(\n context: ProtocolsContext,\n input: V2RemoveLiquidityInput,\n): Promise<TransactionPlan> {\n const router = resolveProtocolContract(context, input.contracts, 'sunswapV2Router')\n const planId = nextPlanId(context, 'liquidity-v2-remove')\n const owner = await requireWalletAddress(context, 'V2 remove liquidity')\n const recipient = await normalizeRecipient(context, input.recipient, 'V2 remove liquidity', owner)\n const deadline = normalizeDeadline(context, input)\n const slippageInput = input.slippage ?? DEFAULT_SLIPPAGE\n const slippage = parseSlippage(slippageInput)\n const approvalMode = input.approval ?? 'auto'\n if (approvalMode === 'permit2') {\n throw new SDKError('SDK_WALLET_CAPABILITY_ERROR', 'Permit2 cannot authorize a SunSwap V2 LP token', {\n approvalMode,\n })\n }\n\n const pair = createPairContext(context, input.tokenA, input.tokenB)\n const [reservesResult, totalSupplyResult, balanceResult, feeToResult, kLastResult] = await readMulticallRequired<unknown>(\n context,\n [\n buildV2PairReservesRead(pair.pair),\n buildV2PairTotalSupplyRead(pair.pair),\n buildV2PairBalanceRead(pair.pair, owner),\n buildV2FactoryFeeToRead({ network: context.network }),\n buildV2PairKLastRead(pair.pair),\n ],\n 'V2 remove liquidity state',\n )\n const reserves = parsePairReserves(reservesResult, pair.tokenASortsBefore)\n const totalSupply = parseContractInteger(totalSupplyResult, 'totalSupply')\n const balance = parseContractInteger(balanceResult, 'LP balance')\n const feeTo = parseContractAddress(feeToResult, 'V2 factory feeTo')\n const kLast = parseContractInteger(kLastResult, 'kLast')\n const feeOn = feeTo !== TRON_ZERO_ADDRESS\n if (BigInt(totalSupply) === 0n) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair total supply must be positive', {\n pair: pair.pair,\n totalSupply,\n })\n }\n if (BigInt(reserves.reserveA) === 0n || BigInt(reserves.reserveB) === 0n) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 pair reserves must be positive for removal', {\n pair: pair.pair,\n reserveA: reserves.reserveA,\n reserveB: reserves.reserveB,\n })\n }\n\n const liquidity = resolveRemoveLiquidity(input, balance)\n if (BigInt(liquidity) > BigInt(totalSupply)) {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V2 LP balance exceeds pair total supply', {\n liquidity,\n totalSupply,\n })\n }\n const pairEntity = createPairEntity(pair, reserves)\n const totalSupplyAmount = CurrencyAmount.fromRawAmount(pairEntity.liquidityToken, totalSupply)\n const liquidityAmount = CurrencyAmount.fromRawAmount(pairEntity.liquidityToken, liquidity)\n const amountA = pairEntity.getLiquidityValue(\n pair.tokenA.token,\n totalSupplyAmount,\n liquidityAmount,\n feeOn,\n kLast,\n ).quotient.toString()\n const amountB = pairEntity.getLiquidityValue(\n pair.tokenB.token,\n totalSupplyAmount,\n liquidityAmount,\n feeOn,\n kLast,\n ).quotient.toString()\n if (BigInt(amountA) === 0n || BigInt(amountB) === 0n) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V2 remove liquidity resolves to a zero token amount', {\n liquidity,\n amountA,\n amountB,\n })\n }\n const minimums = getV2RemoveLiquidityMinimums({ amountA, amountB }, slippage)\n const approvals: ContractCallAction[] = []\n if (approvalMode !== 'none') {\n const allowance = parseContractInteger(\n await readRequiredContract<unknown>(\n context,\n buildV2PairAllowanceRead(pair.pair, owner, router),\n 'V2 LP allowance',\n ),\n 'LP allowance',\n )\n if (BigInt(allowance) < BigInt(liquidity)) {\n approvals.push({\n ...buildV2LpApproveAction({\n pair: pair.pair,\n spender: router,\n amount: liquidity,\n id: `${planId}-approve`,\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n }),\n intent: {\n kind: 'approve',\n scope: liquidityIntentScope(SUNSWAP_V2_LIQUIDITY_PROTOCOL_ID, 'remove-liquidity'),\n tokenSymbol: 'LP',\n },\n })\n }\n }\n\n const transaction = buildRemoveAction({\n context,\n planId,\n pair,\n liquidity,\n amountAMin: minimums.amountAMin,\n amountBMin: minimums.amountBMin,\n recipient,\n deadline,\n router,\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n })\n\n return {\n id: planId,\n kind: 'liquidity',\n network: context.network,\n owner,\n summary: {\n title: 'Remove SunSwap V2 liquidity',\n lines: [`Pair ${pair.pair}`, `LP liquidity ${liquidity}`, `Recipient ${recipient}`],\n },\n approvals,\n transactions: [transaction],\n metadata: {\n protocol: 'sunswap-v2',\n operation: 'remove-liquidity',\n pair: pair.pair,\n tokenA: input.tokenA,\n tokenB: input.tokenB,\n liquidity,\n amountA,\n amountB,\n amountAMin: minimums.amountAMin,\n amountBMin: minimums.amountBMin,\n owner,\n recipient,\n deadline,\n slippageBips: slippageToBips(slippageInput),\n approvalMode,\n feeOn,\n feeTo,\n kLast,\n },\n }\n}\n\nexport class V2LiquidityClient {\n constructor(private readonly context: ProtocolsContext) {}\n\n readonly add = {\n plan: (input: V2AddLiquidityInput): Promise<TransactionPlan> => planV2AddLiquidity(this.context, input),\n execute: async (input: V2AddLiquidityInput): Promise<TransactionPlanExecutionResult> =>\n executeTransactionPlan(await planV2AddLiquidity(this.context, input), createContextExecutor(this.context)),\n }\n\n readonly remove = {\n plan: (input: V2RemoveLiquidityInput): Promise<TransactionPlan> => planV2RemoveLiquidity(this.context, input),\n execute: async (input: V2RemoveLiquidityInput): Promise<TransactionPlanExecutionResult> =>\n executeTransactionPlan(await planV2RemoveLiquidity(this.context, input), createContextExecutor(this.context)),\n }\n}\n\nexport function createV2LiquidityClient(context: ProtocolsContext): V2LiquidityClient {\n return new V2LiquidityClient(context)\n}\n","import {\n SDKError,\n TRON_ZERO_ADDRESS,\n assertTronAddress,\n type BigintIsh,\n type ContractCallAction,\n type TransactionIntentScope,\n type TronAddress,\n} from '@sun-protocol/sun-sdk-core'\nimport { TickMath } from '@sun-protocol/sun-sdk-sunswap-v3'\nimport {\n assertV4PoolId,\n buildV4IncreaseLiquidityAction,\n buildV4HookRegistrationBitmapRead,\n buildV4InitializePoolAction,\n buildV4MintPositionAction,\n buildV4MulticallAction,\n buildV4PoolAndPositionInfoRead,\n buildV4PoolSlot0Read,\n buildV4PoolStateReads,\n computeV4PoolId,\n createV4PoolKey,\n decodeV4HooksRegistration,\n encodeV4PoolParameters,\n encodeV4ContractCallAction,\n encodeV4Permit2ForwardCall,\n type V4PoolKey,\n type V4TokenRequirement,\n} from '@sun-protocol/sun-sdk-sunswap-v4'\nimport { planRouterPermit2Authorization } from '../approval/permit2.js'\nimport {\n createContextExecutor,\n requireWalletAddress,\n requireWalletSnapshot,\n resolveProtocolContract,\n type ProtocolsContext,\n} from '../context.js'\nimport {\n applySlippageMax,\n nextPlanId,\n normalizeBaseUnitAmount,\n normalizeDeadline,\n slippageToBips,\n} from '../common.js'\nimport { executeTransactionPlan } from '../execute-plan.js'\nimport {\n readMulticallRequired,\n readRequiredContract,\n} from '../internal/reads.js'\nimport { attachApprovalIntent } from '../internal/intents.js'\nimport { evmHexToTronAddress, normalizeProtocolToken } from '../internal/tokens.js'\nimport type {\n TransactionPlan,\n TransactionPlanExecutionResult,\n} from '../types/plan.js'\nimport type {\n V4IncreaseLiquidityInput,\n V4InitializePoolInput,\n V4MintPositionInput,\n V4PoolReadInput,\n V4PoolSnapshot,\n} from './types.js'\nimport {\n liquidityIntentScope,\n SUNSWAP_V4_LIQUIDITY_PROTOCOL_ID,\n} from './intents.js'\n\ninterface V4Slot0ObjectResult {\n readonly sqrtPriceX96?: unknown\n readonly tick?: unknown\n}\n\ninterface V4PositionInfoObjectResult {\n readonly poolKey?: unknown\n readonly tickLower?: unknown\n readonly tickUpper?: unknown\n}\n\ninterface V4PoolKeySource {\n readonly poolKey?: V4PoolKey\n readonly token0?: string\n readonly token1?: string\n readonly fee?: number\n readonly tickSpacing?: number\n readonly hooks?: TronAddress | string\n readonly dynamicFee?: boolean\n readonly hooksRegistration?: number\n}\n\ninterface V4PoolKeyResolution {\n readonly poolKey: V4PoolKey\n readonly derived: boolean\n readonly amountsSwapped: boolean\n}\n\ninterface V4AmountSource {\n readonly liquidity?: BigintIsh\n readonly amount0Max?: BigintIsh\n readonly amount1Max?: BigintIsh\n readonly amount0?: BigintIsh\n readonly amount1?: BigintIsh\n readonly slippage?: V4MintPositionInput['slippage']\n readonly contracts?: V4MintPositionInput['contracts']\n readonly sqrtPriceX96?: BigintIsh\n readonly createPool?: boolean\n readonly roundingMode?: V4MintPositionInput['roundingMode']\n readonly poolInitializationMode?: V4MintPositionInput['poolInitializationMode']\n}\n\ninterface V4ResolvedLiquidityAmounts {\n readonly liquidity: string\n readonly amount0Max: string\n readonly amount1Max: string\n readonly amount0Desired: string\n readonly amount1Desired: string\n readonly derived: boolean\n}\n\ninterface V4PoolInitializationResolution {\n readonly shouldInitialize: boolean\n readonly sqrtPriceX96?: string\n}\n\ninterface V4PositionContext {\n readonly poolKey: V4PoolKey\n readonly tickLower: number\n readonly tickUpper: number\n}\n\nconst Q96 = 1n << 96n\n\nfunction parseString(value: unknown, label: string): string {\n if (typeof value === 'bigint' || typeof value === 'number' || typeof value === 'string') {\n return BigInt(value.toString()).toString()\n }\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be an integer-like contract result`, { value })\n}\n\nfunction parseNumber(value: unknown, label: string): number {\n const parsed = Number(parseString(value, label))\n if (!Number.isSafeInteger(parsed)) {\n throw new SDKError('SDK_CONTRACT_ERROR', `${label} must be a safe integer`, { value })\n }\n return parsed\n}\n\nfunction unwrapSingle(value: unknown): unknown {\n return Array.isArray(value) && value.length === 1 ? value[0] : value\n}\n\nfunction signed24(value: bigint): number {\n const masked = value & 0xffffffn\n return Number((masked & 0x800000n) === 0n ? masked : masked - 0x1000000n)\n}\n\nfunction parsePackedPositionTicks(value: unknown): { tickLower: number; tickUpper: number } {\n const info = BigInt(String(unwrapSingle(value)))\n return {\n tickLower: signed24(info >> 8n),\n tickUpper: signed24(info >> 32n),\n }\n}\n\nfunction parseV4Address(value: unknown, label: string): TronAddress {\n const raw = String(unwrapSingle(value))\n try {\n return assertTronAddress(raw, label)\n } catch {\n const evmHex = /^41[0-9a-fA-F]{40}$/.test(raw) ? `0x${raw.slice(2)}` : raw\n return evmHexToTronAddress(evmHex, label)\n }\n}\n\nfunction parsePositionPoolKey(\n value: unknown,\n network: ProtocolsContext['network'],\n): V4PoolKey {\n if (Array.isArray(value) && value.length >= 5) {\n return createV4PoolKey({\n network,\n currencyA: parseV4Address(value[0], 'poolKey.currency0'),\n currencyB: parseV4Address(value[1], 'poolKey.currency1'),\n hooks: parseV4Address(value[2], 'poolKey.hooks'),\n fee: parseNumber(value[3], 'poolKey.fee'),\n parameters: String(value[4]),\n })\n }\n if (typeof value === 'object' && value !== null) {\n const key = value as Record<string, unknown>\n if (\n key.currency0 !== undefined &&\n key.currency1 !== undefined &&\n key.hooks !== undefined &&\n key.fee !== undefined &&\n key.parameters !== undefined\n ) {\n return createV4PoolKey({\n network,\n currencyA: parseV4Address(key.currency0, 'poolKey.currency0'),\n currencyB: parseV4Address(key.currency1, 'poolKey.currency1'),\n hooks: parseV4Address(key.hooks, 'poolKey.hooks'),\n fee: parseNumber(key.fee, 'poolKey.fee'),\n parameters: String(key.parameters),\n })\n }\n }\n throw new SDKError('SDK_CONTRACT_ERROR', 'V4 position context is missing poolKey', { value })\n}\n\nfunction parseSlot0(result: unknown): { sqrtPriceX96: string; tick: number } {\n if (Array.isArray(result)) {\n return {\n sqrtPriceX96: parseString(result[0], 'sqrtPriceX96'),\n tick: parseNumber(result[1], 'tick'),\n }\n }\n if (typeof result === 'object' && result !== null) {\n const slot0 = result as V4Slot0ObjectResult\n return {\n sqrtPriceX96: parseString(slot0.sqrtPriceX96, 'sqrtPriceX96'),\n tick: parseNumber(slot0.tick, 'tick'),\n }\n }\n throw new SDKError('SDK_CONTRACT_ERROR', 'V4 slot0 result is malformed', { result })\n}\n\nasync function resolveV4PoolKey(context: ProtocolsContext, input: V4PoolKeySource): Promise<V4PoolKeyResolution> {\n if (input.poolKey !== undefined) {\n return { poolKey: input.poolKey, derived: false, amountsSwapped: false }\n }\n if (\n input.token0 === undefined\n || input.token1 === undefined\n || input.fee === undefined\n || input.tickSpacing === undefined\n ) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V4 poolKey or complete token pool inputs are required')\n }\n\n const token0 = normalizeProtocolToken(context, input.token0, 'token0').contractAddress\n const token1 = normalizeProtocolToken(context, input.token1, 'token1').contractAddress\n const hooks = assertTronAddress(input.hooks ?? TRON_ZERO_ADDRESS, 'hooks')\n if (input.dynamicFee && hooks === TRON_ZERO_ADDRESS) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'Dynamic V4 fees require a non-zero hooks contract')\n }\n const hooksRegistration = input.hooksRegistration ?? (hooks === TRON_ZERO_ADDRESS\n ? 0\n : parseNumber(\n unwrapSingle(await readRequiredContract<unknown>(\n context,\n buildV4HookRegistrationBitmapRead({ network: context.network, hooks }),\n 'V4 hook registration read',\n )),\n 'hooksRegistration',\n ))\n const poolKey = createV4PoolKey({\n network: context.network,\n currencyA: token0,\n currencyB: token1,\n hooks,\n fee: input.dynamicFee ? 0x800000 : input.fee,\n parameters: encodeV4PoolParameters({\n tickSpacing: input.tickSpacing,\n hooksRegistration: decodeV4HooksRegistration(hooksRegistration),\n }),\n })\n return {\n poolKey,\n derived: true,\n amountsSwapped: poolKey.currency0 !== token0,\n }\n}\n\nfunction parseV4PositionContext(\n result: unknown,\n network: ProtocolsContext['network'],\n): V4PositionContext {\n let poolKey: unknown\n let tickLower: unknown\n let tickUpper: unknown\n if (Array.isArray(result)) {\n poolKey = result[0]\n if (result[2] === undefined && result[1] !== undefined) {\n const ticks = parsePackedPositionTicks(result[1])\n tickLower = ticks.tickLower\n tickUpper = ticks.tickUpper\n } else {\n tickLower = result[1]\n tickUpper = result[2]\n }\n } else if (typeof result === 'object' && result !== null) {\n const info = result as V4PositionInfoObjectResult\n poolKey = info.poolKey\n tickLower = info.tickLower\n tickUpper = info.tickUpper\n } else {\n throw new SDKError('SDK_CONTRACT_ERROR', 'V4 position context result is malformed', { result })\n }\n return {\n poolKey: parsePositionPoolKey(poolKey, network),\n tickLower: parseNumber(tickLower, 'tickLower'),\n tickUpper: parseNumber(tickUpper, 'tickUpper'),\n }\n}\n\nfunction assertV4PoolKeyMatches(tokenId: string, supplied: V4PoolKey, position: V4PoolKey): void {\n const suppliedPoolId = computeV4PoolId(supplied)\n const positionPoolId = computeV4PoolId(position)\n if (suppliedPoolId !== positionPoolId) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V4 pool context does not match the tokenId position', {\n tokenId,\n suppliedPoolId,\n positionPoolId,\n })\n }\n}\n\nasync function resolveV4PositionContext(\n context: ProtocolsContext,\n tokenId: string,\n contracts: V4IncreaseLiquidityInput['contracts'],\n): Promise<V4PositionContext> {\n const result = await readRequiredContract<unknown>(\n context,\n buildV4PoolAndPositionInfoRead({\n network: context.network,\n tokenId,\n positionManager: resolveProtocolContract(context, contracts, 'sunswapV4PositionManager'),\n }),\n 'V4 position context read',\n )\n return parseV4PositionContext(result, context.network)\n}\n\nasync function shouldInitializeV4Pool(\n context: ProtocolsContext,\n poolKey: V4PoolKey,\n input: V4AmountSource,\n): Promise<V4PoolInitializationResolution> {\n if (!input.createPool) return { shouldInitialize: false }\n if (input.poolInitializationMode === 'trust-input') return { shouldInitialize: true }\n try {\n const slot0Result = await readRequiredContract<unknown>(\n context,\n buildV4PoolSlot0Read({\n network: context.network,\n poolId: computeV4PoolId(poolKey),\n poolManager: resolveProtocolContract(context, input.contracts, 'sunswapV4PoolManager'),\n }),\n 'V4 pool initialization check',\n )\n const sqrtPriceX96 = parseSlot0(slot0Result).sqrtPriceX96\n return BigInt(sqrtPriceX96) === 0n\n ? { shouldInitialize: true }\n : { shouldInitialize: false, sqrtPriceX96 }\n } catch {\n return { shouldInitialize: true }\n }\n}\n\nfunction maxV4LiquidityForAmounts(input: {\n readonly sqrtPriceX96: string\n readonly tickLower: number\n readonly tickUpper: number\n readonly amount0: string\n readonly amount1: string\n}): string {\n const sqrtPrice = BigInt(input.sqrtPriceX96)\n let sqrtA = BigInt(TickMath.getSqrtRatioAtTick(input.tickLower).toString())\n let sqrtB = BigInt(TickMath.getSqrtRatioAtTick(input.tickUpper).toString())\n if (sqrtA > sqrtB) [sqrtA, sqrtB] = [sqrtB, sqrtA]\n const amount0 = BigInt(input.amount0)\n const amount1 = BigInt(input.amount1)\n const difference = sqrtB - sqrtA\n let liquidity: bigint\n if (sqrtPrice <= sqrtA) {\n liquidity = (amount0 * sqrtA * sqrtB) / (Q96 * difference)\n } else if (sqrtPrice < sqrtB) {\n const liquidity0 = (amount0 * sqrtPrice * sqrtB) / (Q96 * (sqrtB - sqrtPrice))\n const liquidity1 = (amount1 * Q96) / (sqrtPrice - sqrtA)\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1\n } else {\n liquidity = (amount1 * Q96) / difference\n }\n return liquidity.toString()\n}\n\nasync function resolveV4SqrtPrice(\n context: ProtocolsContext,\n poolKey: V4PoolKey,\n input: V4AmountSource,\n): Promise<string> {\n if (input.createPool) {\n if (input.sqrtPriceX96 === undefined) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'sqrtPriceX96 is required when createPool is true')\n }\n return normalizeBaseUnitAmount(input.sqrtPriceX96, 'sqrtPriceX96')\n }\n const slot0Result = await readRequiredContract<unknown>(\n context,\n buildV4PoolSlot0Read({\n network: context.network,\n poolId: computeV4PoolId(poolKey),\n poolManager: resolveProtocolContract(context, input.contracts, 'sunswapV4PoolManager'),\n }),\n 'V4 pool state read',\n )\n return parseSlot0(slot0Result).sqrtPriceX96\n}\n\nasync function resolveV4LiquidityAmounts(\n context: ProtocolsContext,\n input: V4AmountSource & {\n readonly poolKey: V4PoolKey\n readonly tickLower: number\n readonly tickUpper: number\n readonly amountsSwapped: boolean\n },\n): Promise<V4ResolvedLiquidityAmounts> {\n const hasResolvedAmount = input.liquidity !== undefined\n || input.amount0Max !== undefined\n || input.amount1Max !== undefined\n if (hasResolvedAmount) {\n if (input.liquidity === undefined || input.amount0Max === undefined || input.amount1Max === undefined) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'liquidity, amount0Max, and amount1Max must be provided together')\n }\n return {\n liquidity: normalizeBaseUnitAmount(input.liquidity, 'liquidity'),\n amount0Max: normalizeBaseUnitAmount(input.amount0Max, 'amount0Max', { allowZero: true }),\n amount1Max: normalizeBaseUnitAmount(input.amount1Max, 'amount1Max', { allowZero: true }),\n amount0Desired: normalizeBaseUnitAmount(input.amount0Max, 'amount0Max', { allowZero: true }),\n amount1Desired: normalizeBaseUnitAmount(input.amount1Max, 'amount1Max', { allowZero: true }),\n derived: false,\n }\n }\n if (input.amount0 === undefined && input.amount1 === undefined) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V4 liquidity requires at least one of amount0 or amount1')\n }\n if (input.tickLower >= input.tickUpper) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'tickLower must be less than tickUpper', {\n tickLower: input.tickLower,\n tickUpper: input.tickUpper,\n })\n }\n\n const userAmount0 = normalizeBaseUnitAmount(input.amount0 ?? '0', 'amount0', { allowZero: true })\n const userAmount1 = normalizeBaseUnitAmount(input.amount1 ?? '0', 'amount1', { allowZero: true })\n const amount0 = input.amountsSwapped ? userAmount1 : userAmount0\n const amount1 = input.amountsSwapped ? userAmount0 : userAmount1\n const liquidity = maxV4LiquidityForAmounts({\n sqrtPriceX96: await resolveV4SqrtPrice(context, input.poolKey, input),\n tickLower: input.tickLower,\n tickUpper: input.tickUpper,\n amount0,\n amount1,\n })\n if (BigInt(liquidity) <= 0n) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'V4 amount inputs resolve to zero liquidity', {\n amount0,\n amount1,\n tickLower: input.tickLower,\n tickUpper: input.tickUpper,\n })\n }\n const slippageBips = slippageToBips(input.slippage ?? '0.5%')\n const halfUp = (amount: bigint, bips: number): string =>\n ((amount * BigInt(10_000 + bips) + 5_000n) / 10_000n).toString()\n return {\n liquidity,\n amount0Max: input.roundingMode === 'half-up'\n ? halfUp(BigInt(amount0), slippageBips)\n : applySlippageMax(BigInt(amount0), slippageBips).toString(),\n amount1Max: input.roundingMode === 'half-up'\n ? halfUp(BigInt(amount1), slippageBips)\n : applySlippageMax(BigInt(amount1), slippageBips).toString(),\n amount0Desired: amount0,\n amount1Desired: amount1,\n derived: true,\n }\n}\n\nfunction nativeCallValue(\n poolKey: V4PoolKey,\n amounts: V4ResolvedLiquidityAmounts,\n mode: V4MintPositionInput['nativeCallValueMode'],\n): bigint | undefined {\n if (mode !== 'desired') return undefined\n let value = 0n\n if (poolKey.currency0 === TRON_ZERO_ADDRESS) value += BigInt(amounts.amount0Desired)\n if (poolKey.currency1 === TRON_ZERO_ADDRESS) value += BigInt(amounts.amount1Desired)\n return value\n}\n\nfunction planMetadata(input: {\n readonly operation: string\n readonly poolId?: string\n readonly tokenId?: string\n readonly owner?: string\n readonly sweepRecipient?: string\n readonly deadline?: string\n readonly poolKeyDerived?: boolean\n readonly amountsDerived?: boolean\n readonly createPool?: boolean\n}): Record<string, unknown> {\n return {\n protocol: 'sunswap-v4',\n operation: input.operation,\n ...(input.poolId !== undefined ? { poolId: input.poolId } : {}),\n ...(input.tokenId !== undefined ? { tokenId: input.tokenId } : {}),\n ...(input.owner !== undefined ? { owner: input.owner } : {}),\n ...(input.sweepRecipient !== undefined ? { sweepRecipient: input.sweepRecipient } : {}),\n ...(input.deadline !== undefined ? { deadline: input.deadline } : {}),\n ...(input.poolKeyDerived !== undefined ? { poolKeyDerived: input.poolKeyDerived } : {}),\n ...(input.amountsDerived !== undefined ? { amountsDerived: input.amountsDerived } : {}),\n ...(input.createPool !== undefined ? { createPool: input.createPool } : {}),\n }\n}\n\nasync function approvalsFromV4Action(\n context: ProtocolsContext,\n action: ContractCallAction,\n owner: TronAddress,\n mode: V4MintPositionInput['approval'],\n scope: TransactionIntentScope<'liquidity'>,\n): Promise<readonly ContractCallAction[]> {\n const requirements = (action.tokenRequirements ?? []) as readonly V4TokenRequirement[]\n const approvals: ContractCallAction[] = []\n\n for (const requirement of requirements) {\n if (BigInt(requirement.amount) === 0n) continue\n if (mode === 'none') continue\n\n const authorization = await planRouterPermit2Authorization(context, {\n owner,\n token: requirement.token,\n spender: requirement.spender,\n amount: requirement.amount,\n approval: 'approve',\n })\n for (const approval of authorization.actions) {\n if (approval.type !== 'approve' && approval.type !== 'contract-call') {\n throw new SDKError(\n 'SDK_RUNTIME_ERROR',\n 'V4 Permit2 authorization produced a non-contract action',\n { actionType: approval.type },\n )\n }\n approvals.push(...attachApprovalIntent(\n [approval],\n scope,\n requirement.token,\n ) as readonly ContractCallAction[])\n }\n }\n\n return approvals\n}\n\nexport class V4LiquidityClient {\n constructor(private readonly context: ProtocolsContext) {}\n\n async read(input: V4PoolReadInput): Promise<V4PoolSnapshot> {\n const poolId = assertV4PoolId(input.poolId)\n const [slot0Result, liquidityResult] = await readMulticallRequired<unknown>(\n this.context,\n buildV4PoolStateReads({\n network: this.context.network,\n poolId,\n poolManager: resolveProtocolContract(this.context, input.contracts, 'sunswapV4PoolManager'),\n }),\n 'V4 pool state read',\n )\n const slot0 = parseSlot0(slot0Result)\n return {\n protocol: 'sunswap-v4',\n poolId,\n sqrtPriceX96: slot0.sqrtPriceX96,\n tick: slot0.tick,\n liquidity: parseString(liquidityResult, 'liquidity'),\n }\n }\n\n readonly initialize = {\n plan: async (input: V4InitializePoolInput): Promise<TransactionPlan> => this.planInitialize(input),\n execute: async (input: V4InitializePoolInput): Promise<TransactionPlanExecutionResult> =>\n executeTransactionPlan(await this.planInitialize(input), createContextExecutor(this.context)),\n }\n\n readonly add = {\n plan: async (input: V4MintPositionInput): Promise<TransactionPlan> => this.planMint(input),\n execute: async (input: V4MintPositionInput): Promise<TransactionPlanExecutionResult> =>\n executeTransactionPlan(await this.planMint(input), createContextExecutor(this.context)),\n }\n\n readonly increase = {\n plan: async (input: V4IncreaseLiquidityInput): Promise<TransactionPlan> => this.planIncrease(input),\n execute: async (input: V4IncreaseLiquidityInput): Promise<TransactionPlanExecutionResult> =>\n executeTransactionPlan(await this.planIncrease(input), createContextExecutor(this.context)),\n }\n\n private async planInitialize(input: V4InitializePoolInput): Promise<TransactionPlan> {\n const { address: owner } = await requireWalletSnapshot(this.context, 'V4 initialize pool')\n const positionManager = resolveProtocolContract(this.context, input.contracts, 'sunswapV4PositionManager')\n const planId = nextPlanId(this.context, 'liquidity-v4-initialize')\n const poolKey = await resolveV4PoolKey(this.context, input)\n const action = buildV4InitializePoolAction({\n network: this.context.network,\n positionManager,\n poolKey: poolKey.poolKey,\n sqrtPriceX96: normalizeBaseUnitAmount(input.sqrtPriceX96, 'sqrtPriceX96'),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-tx`,\n })\n const poolId = computeV4PoolId(poolKey.poolKey)\n const transaction = {\n ...action,\n intent: {\n kind: 'create-pool' as const,\n scope: liquidityIntentScope(SUNSWAP_V4_LIQUIDITY_PROTOCOL_ID, 'initialize-pool'),\n poolId,\n },\n }\n return {\n id: planId,\n kind: 'liquidity',\n network: this.context.network,\n owner,\n summary: {\n title: 'Initialize SunSwap V4 pool',\n lines: [`Pool ${poolId}`],\n },\n approvals: [],\n transactions: [transaction],\n metadata: planMetadata({ operation: 'initialize-pool', poolId, poolKeyDerived: poolKey.derived }),\n }\n }\n\n private async planMint(input: V4MintPositionInput): Promise<TransactionPlan> {\n const positionManager = resolveProtocolContract(this.context, input.contracts, 'sunswapV4PositionManager')\n const planId = nextPlanId(this.context, 'liquidity-v4-mint')\n const { address: walletAddress } = await requireWalletSnapshot(this.context, 'V4 mint position')\n const owner = input.owner !== undefined ? assertTronAddress(input.owner, 'owner') : walletAddress\n if (owner !== walletAddress) {\n throw new SDKError('SDK_WALLET_ACCOUNT_MISMATCH', 'V4 mint owner does not match the connected wallet', {\n expectedAddress: owner,\n actualAddress: walletAddress,\n })\n }\n const deadline = normalizeDeadline(this.context, input)\n const poolKey = await resolveV4PoolKey(this.context, input)\n const initialization = await shouldInitializeV4Pool(this.context, poolKey.poolKey, input)\n const amounts = await resolveV4LiquidityAmounts(this.context, {\n ...input,\n poolKey: poolKey.poolKey,\n amountsSwapped: poolKey.amountsSwapped,\n ...(initialization.sqrtPriceX96 !== undefined ? { sqrtPriceX96: initialization.sqrtPriceX96 } : {}),\n ...(initialization.shouldInitialize ? { createPool: true } : { createPool: false }),\n })\n if (input.createPool && input.sqrtPriceX96 === undefined) {\n throw new SDKError('SDK_INVALID_ARGUMENT', 'sqrtPriceX96 is required when createPool is true')\n }\n const hasNativeCurrency = poolKey.poolKey.currency0 === TRON_ZERO_ADDRESS\n || poolKey.poolKey.currency1 === TRON_ZERO_ADDRESS\n const sweepRecipient = hasNativeCurrency\n ? input.sweepRecipient !== undefined\n ? assertTronAddress(input.sweepRecipient, 'sweepRecipient')\n : owner\n : undefined\n const desiredNativeCallValue = nativeCallValue(poolKey.poolKey, amounts, input.nativeCallValueMode)\n const action = buildV4MintPositionAction({\n network: this.context.network,\n positionManager,\n positionConfig: { poolKey: poolKey.poolKey, tickLower: input.tickLower, tickUpper: input.tickUpper },\n liquidity: amounts.liquidity,\n amount0Max: amounts.amount0Max,\n amount1Max: amounts.amount1Max,\n owner,\n deadline,\n ...(desiredNativeCallValue !== undefined ? { callValue: desiredNativeCallValue } : {}),\n ...(sweepRecipient !== undefined ? { sweepRecipient } : {}),\n ...(input.hookData !== undefined ? { hookData: input.hookData } : {}),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-tx`,\n })\n const scope = liquidityIntentScope(\n SUNSWAP_V4_LIQUIDITY_PROTOCOL_ID,\n initialization.shouldInitialize ? 'initialize-and-mint' : 'mint-position',\n )\n const approvals = await approvalsFromV4Action(this.context, action, owner, input.approval, scope)\n const poolId = computeV4PoolId(poolKey.poolKey)\n const initializeAction = initialization.shouldInitialize\n ? buildV4InitializePoolAction({\n network: this.context.network,\n positionManager,\n poolKey: poolKey.poolKey,\n sqrtPriceX96: normalizeBaseUnitAmount(input.sqrtPriceX96 as BigintIsh, 'sqrtPriceX96'),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-initialize`,\n })\n : undefined\n const calls = [\n ...(input.permit2Signatures ?? []).map(permit => encodeV4Permit2ForwardCall({ owner, permit })),\n ...(initializeAction ? [encodeV4ContractCallAction(initializeAction)] : []),\n encodeV4ContractCallAction(action),\n ]\n const transactionAction = initializeAction || input.transactionMode === 'multicall' || (input.permit2Signatures?.length ?? 0) > 0\n ? buildV4MulticallAction({\n network: this.context.network,\n positionManager,\n calls,\n ...(action.callValue !== undefined ? { callValue: action.callValue } : {}),\n ...(action.tokenRequirements !== undefined ? { tokenRequirements: action.tokenRequirements } : {}),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-tx`,\n })\n : action\n const transaction = {\n ...transactionAction,\n waitForReceipt: 'included' as const,\n intent: {\n kind: 'add-liquidity' as const,\n scope,\n },\n }\n\n return {\n id: planId,\n kind: 'liquidity',\n network: this.context.network,\n owner,\n summary: {\n title: 'Mint SunSwap V4 position',\n lines: [`Pool ${poolId}`, `Owner ${owner}`],\n },\n approvals,\n transactions: [transaction],\n metadata: planMetadata({\n operation: 'mint-position',\n poolId,\n owner,\n ...(sweepRecipient !== undefined ? { sweepRecipient } : {}),\n deadline,\n poolKeyDerived: poolKey.derived,\n amountsDerived: amounts.derived,\n createPool: initialization.shouldInitialize,\n }),\n }\n }\n\n private async planIncrease(input: V4IncreaseLiquidityInput): Promise<TransactionPlan> {\n const positionManager = resolveProtocolContract(this.context, input.contracts, 'sunswapV4PositionManager')\n const planId = nextPlanId(this.context, 'liquidity-v4-increase')\n const owner = await requireWalletAddress(this.context, 'V4 increase liquidity')\n const deadline = normalizeDeadline(this.context, input)\n const tokenId = normalizeBaseUnitAmount(input.tokenId, 'tokenId')\n const poolKeyNeedsPosition = input.poolKey === undefined && input.token0 === undefined\n const position = await resolveV4PositionContext(this.context, tokenId, input.contracts)\n const poolKey = poolKeyNeedsPosition\n ? { poolKey: position.poolKey, derived: true, amountsSwapped: false }\n : await resolveV4PoolKey(this.context, input)\n assertV4PoolKeyMatches(tokenId, poolKey.poolKey, position.poolKey)\n const amounts = await resolveV4LiquidityAmounts(this.context, {\n ...input,\n poolKey: poolKey.poolKey,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n amountsSwapped: poolKey.amountsSwapped,\n })\n const hasNativeCurrency = poolKey.poolKey.currency0 === TRON_ZERO_ADDRESS\n || poolKey.poolKey.currency1 === TRON_ZERO_ADDRESS\n const sweepRecipient = hasNativeCurrency\n ? input.sweepRecipient !== undefined\n ? assertTronAddress(input.sweepRecipient, 'sweepRecipient')\n : owner\n : undefined\n const desiredNativeCallValue = nativeCallValue(poolKey.poolKey, amounts, input.nativeCallValueMode)\n const action = buildV4IncreaseLiquidityAction({\n network: this.context.network,\n positionManager,\n poolKey: poolKey.poolKey,\n tokenId,\n liquidity: amounts.liquidity,\n amount0Max: amounts.amount0Max,\n amount1Max: amounts.amount1Max,\n deadline,\n ...(desiredNativeCallValue !== undefined ? { callValue: desiredNativeCallValue } : {}),\n ...(sweepRecipient !== undefined ? { sweepRecipient } : {}),\n ...(input.hookData !== undefined ? { hookData: input.hookData } : {}),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-tx`,\n })\n const scope = liquidityIntentScope(SUNSWAP_V4_LIQUIDITY_PROTOCOL_ID, 'increase-liquidity')\n const approvals = await approvalsFromV4Action(this.context, action, owner, input.approval, scope)\n const poolId = computeV4PoolId(poolKey.poolKey)\n const permitCalls = (input.permit2Signatures ?? []).map(permit => encodeV4Permit2ForwardCall({ owner, permit }))\n const transactionAction = input.transactionMode === 'multicall' || permitCalls.length > 0\n ? buildV4MulticallAction({\n network: this.context.network,\n positionManager,\n calls: [...permitCalls, encodeV4ContractCallAction(action)],\n ...(action.callValue !== undefined ? { callValue: action.callValue } : {}),\n ...(action.tokenRequirements !== undefined ? { tokenRequirements: action.tokenRequirements } : {}),\n ...(input.feeLimit !== undefined ? { feeLimit: input.feeLimit } : {}),\n id: `${planId}-tx`,\n })\n : action\n const transaction = {\n ...transactionAction,\n waitForReceipt: 'included' as const,\n intent: {\n kind: 'add-liquidity' as const,\n scope,\n positionId: tokenId,\n },\n }\n\n return {\n id: planId,\n kind: 'liquidity',\n network: this.context.network,\n owner,\n summary: {\n title: 'Increase SunSwap V4 liquidity',\n lines: [`Position ${tokenId}`, `Pool ${poolId}`],\n },\n approvals,\n transactions: [transaction],\n metadata: planMetadata({\n operation: 'increase-liquidity',\n poolId,\n tokenId,\n owner,\n ...(sweepRecipient !== undefined ? { sweepRecipient } : {}),\n deadline,\n poolKeyDerived: poolKey.derived,\n amountsDerived: amounts.derived,\n }),\n }\n }\n}\n","import type { ProtocolsContext } from '../context.js'\nimport { V2LiquidityClient } from './v2.js'\nimport { V3LiquidityClient } from './v3.js'\nimport { V4LiquidityClient } from './v4.js'\n\nexport class LiquidityClient {\n readonly v4: {\n readonly initialize: V4LiquidityClient['initialize']\n readonly read: V4LiquidityClient['read']\n readonly add: V4LiquidityClient['add']\n readonly increase: V4LiquidityClient['increase']\n }\n readonly v3: {\n readonly add: V3LiquidityClient['add']\n readonly increase: V3LiquidityClient['increase']\n }\n\n readonly v2: V2LiquidityClient\n\n constructor(context: ProtocolsContext) {\n this.v2 = new V2LiquidityClient(context)\n const v3Client = new V3LiquidityClient(context)\n const v4Client = new V4LiquidityClient(context)\n this.v3 = {\n add: v3Client.add,\n increase: v3Client.increase,\n }\n this.v4 = {\n initialize: v4Client.initialize,\n read: (input) => v4Client.read(input),\n add: v4Client.add,\n increase: v4Client.increase,\n }\n }\n}\n\nexport function createLiquidityClient(context: ProtocolsContext): LiquidityClient {\n return new LiquidityClient(context)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAyCP,IAAM,mBAAmB;AAgBzB,SAAS,qBAAqB,OAAgB,OAAuB;AACnE,QAAM,aAAa,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI;AAC3E,MACE,eAAe,QACZ,eAAe,UACd,OAAO,eAAe,YACrB,OAAO,eAAe,YACtB,OAAO,eAAe,YACtB,OAAO,eAAe,UAC3B;AACA,UAAM,IAAI,SAAS,sBAAsB,GAAG,KAAK,4CAA4C,EAAE,MAAM,CAAC;AAAA,EACxG;AAEA,MAAI;AACF,UAAM,OAAO,WAAW,SAAS;AACjC,QAAI,CAAC,QAAQ,KAAK,IAAI,EAAG,OAAM,IAAI,MAAM,yBAAyB;AAClE,WAAO,OAAO,IAAI,EAAE,SAAS;AAAA,EAC/B,QAAQ;AACN,UAAM,IAAI,SAAS,sBAAsB,GAAG,KAAK,4CAA4C,EAAE,MAAM,CAAC;AAAA,EACxG;AACF;AAEA,SAAS,qBAAqB,OAAgB,OAA4B;AACxE,QAAM,aAAa,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI;AAC3E,MAAI,OAAO,eAAe,UAAU;AAClC,UAAM,IAAI,SAAS,sBAAsB,GAAG,KAAK,uCAAuC,EAAE,MAAM,CAAC;AAAA,EACnG;AAEA,MAAI;AACF,WA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AI,kBAAkB,OAAO;AAC9C,SAAK,KAAK;AAAA,MACR,KAAK,SAAS;AAAA,MACd,UAAU,SAAS;AAAA,IACrB;AACA,SAAK,KAAK;AAAA,MACR,YAAY,SAAS;AAAA,MACrB,MAAM,CAAC,UAAU,SAAS,KAAK,KAAK;AAAA,MACpC,KAAK,SAAS;AAAA,MACd,UAAU,SAAS;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,sBAAsB,SAA4C;AAChF,SAAO,IAAI,gBAAgB,OAAO;AACpC;","names":["SDKError","TRON_ZERO_ADDRESS","assertTronAddress","SDKError","assertTronAddress","TRON_ZERO_ADDRESS"]}
@@ -0,0 +1,146 @@
1
+ import { FetchLike, JsonParser, RouterApiClient, SunPumpApiClient } from '@sun-protocol/sun-sdk-api';
2
+ import { NetworkEndpoints, ChainConfig } from '@sun-protocol/sun-sdk-chains';
3
+ import { TronAddress, Network, TransactionAction, ContractCallAction, DeferredContractCallAction, Percent, BigintIsh } from '@sun-protocol/sun-sdk-core';
4
+ import { TronClient, WalletAdapter, GetWallet, SubmittedCallback, Runtime, TransactionReceipt } from '@sun-protocol/sun-sdk-runtime';
5
+
6
+ type ApprovalMode = 'auto' | 'approve' | 'permit2' | 'none';
7
+ interface ContractOverrides {
8
+ readonly psmUsdt?: TronAddress | string;
9
+ readonly psmUsdd?: TronAddress | string;
10
+ readonly psm?: TronAddress | string;
11
+ readonly psmGemJoin?: TronAddress | string;
12
+ readonly psmInfoReader?: TronAddress | string;
13
+ readonly sunswapV2Router?: TronAddress | string;
14
+ readonly sunswapV3Router?: TronAddress | string;
15
+ readonly sunswapV3Factory?: TronAddress | string;
16
+ readonly sunswapV3PositionManager?: TronAddress | string;
17
+ readonly sunswapV4PoolManager?: TronAddress | string;
18
+ readonly sunswapV4PositionManager?: TronAddress | string;
19
+ readonly sunswapV4LpFeeHelper?: TronAddress | string;
20
+ }
21
+ /**
22
+ * @deprecated Reserved compatibility field. Router and Permit2 support is
23
+ * provided by the SDK and does not require adapter injection.
24
+ */
25
+ interface ProtocolAdapterDependencies {
26
+ readonly universalRouter?: unknown;
27
+ readonly permit2?: unknown;
28
+ }
29
+ interface ProtocolClientOverrides {
30
+ readonly routerApi?: RouterApiClient;
31
+ readonly sunPumpApi?: SunPumpApiClient;
32
+ }
33
+ interface ProtocolClientOptions {
34
+ readonly network: Network;
35
+ readonly tronClient?: TronClient;
36
+ readonly wallet?: WalletAdapter;
37
+ readonly getWallet?: GetWallet;
38
+ readonly onSubmitted?: SubmittedCallback;
39
+ readonly fetchImpl?: FetchLike;
40
+ readonly jsonParser?: JsonParser;
41
+ readonly endpoints?: Partial<NetworkEndpoints>;
42
+ readonly clients?: ProtocolClientOverrides;
43
+ readonly adapters?: ProtocolAdapterDependencies;
44
+ readonly now?: () => number;
45
+ /** Async Unix-millisecond clock for final Swap deadlines; defaults to the SUN time service. */
46
+ readonly getTransactionTime?: () => Promise<number>;
47
+ readonly idFactory?: () => string;
48
+ }
49
+ interface SunSDKCreateOptions extends ProtocolClientOptions {
50
+ readonly runtime?: Runtime;
51
+ }
52
+
53
+ type TransactionPlanKind = 'swap' | 'liquidity' | 'position' | 'pump';
54
+ interface PlanSummary {
55
+ readonly title: string;
56
+ readonly lines: readonly string[];
57
+ }
58
+ interface TransactionPlan {
59
+ readonly id: string;
60
+ readonly kind: TransactionPlanKind;
61
+ readonly network: Network;
62
+ /** Wallet address bound to plans containing runtime or wallet-signature actions. */
63
+ readonly owner?: TronAddress;
64
+ readonly summary: PlanSummary;
65
+ readonly approvals: readonly TransactionAction[];
66
+ readonly transactions: readonly TransactionAction[];
67
+ readonly metadata: Record<string, unknown>;
68
+ }
69
+ interface ExecutedActionResult {
70
+ readonly action: TransactionAction;
71
+ readonly result: unknown;
72
+ readonly txid?: string;
73
+ readonly receipt?: TransactionReceipt;
74
+ readonly materializedAction?: ContractCallAction;
75
+ }
76
+ type TransactionPlanFinalResult = {
77
+ readonly type: 'transaction';
78
+ readonly txid: string;
79
+ readonly raw: unknown;
80
+ } | {
81
+ readonly type: 'signature';
82
+ readonly signature: string;
83
+ } | {
84
+ readonly type: 'api';
85
+ readonly data: unknown;
86
+ };
87
+ interface TransactionPlanExecutionResult {
88
+ readonly plan: TransactionPlan;
89
+ readonly actions: readonly ExecutedActionResult[];
90
+ readonly txids: readonly string[];
91
+ readonly finalResult: TransactionPlanFinalResult | undefined;
92
+ }
93
+
94
+ interface TransactionPlanExecutor {
95
+ readonly network?: Network;
96
+ getAddress?(): Promise<TronAddress>;
97
+ sendAction?: Runtime['sendAction'];
98
+ waitForTransactionReceipt?: NonNullable<Runtime['waitForTransactionReceipt']>;
99
+ signTypedData?: Runtime['signTypedData'];
100
+ executeHttpAction?(action: TransactionAction): Promise<unknown>;
101
+ materializeAction?(action: DeferredContractCallAction, completedActions: readonly ExecutedActionResult[]): Promise<ContractCallAction>;
102
+ }
103
+ declare function executeTransactionPlan(plan: TransactionPlan, executor: TransactionPlanExecutor): Promise<TransactionPlanExecutionResult>;
104
+
105
+ interface ProtocolsContext {
106
+ readonly network: Network;
107
+ readonly chain: ChainConfig;
108
+ readonly endpoints: NetworkEndpoints;
109
+ readonly runtime?: Runtime;
110
+ readonly fetchImpl: FetchLike;
111
+ readonly jsonParser?: JsonParser;
112
+ readonly routerApi: RouterApiClient;
113
+ readonly sunPumpApi?: SunPumpApiClient;
114
+ readonly adapters: ProtocolAdapterDependencies;
115
+ readonly now: () => number;
116
+ readonly getTransactionTime: () => Promise<number>;
117
+ readonly idFactory: () => string;
118
+ }
119
+ /**
120
+ * Creates the public context used by staged transaction orchestration.
121
+ *
122
+ * Keep this available to consumers that render and execute TransactionPlan
123
+ * actions one step at a time instead of using a client's execute() shortcut.
124
+ */
125
+ declare function createProtocolsContext(options: SunSDKCreateOptions): ProtocolsContext;
126
+ declare function requireRuntime(context: ProtocolsContext, operation: string): Runtime;
127
+ declare function requireWalletAddress(context: ProtocolsContext, operation: string): Promise<TronAddress>;
128
+ interface ProtocolWalletSnapshot {
129
+ readonly wallet: WalletAdapter;
130
+ readonly address: TronAddress;
131
+ }
132
+ /** Resolves one wallet adapter for the current plan boundary. */
133
+ declare function requireWalletSnapshot(context: ProtocolsContext, operation: string): Promise<ProtocolWalletSnapshot>;
134
+ /** Creates the base public executor for staged TransactionPlan execution. */
135
+ declare function createContextExecutor(context: ProtocolsContext): TransactionPlanExecutor;
136
+
137
+ type SlippageInput = Percent | `${number}%`;
138
+ interface PlanTimingOptions {
139
+ readonly deadline?: BigintIsh;
140
+ readonly ttlSeconds?: number;
141
+ }
142
+ interface RecipientOptions {
143
+ readonly recipient?: TronAddress | string;
144
+ }
145
+
146
+ export { type ApprovalMode as A, type ContractOverrides as C, type ExecutedActionResult as E, type ProtocolsContext as P, type RecipientOptions as R, type SlippageInput as S, type TransactionPlan as T, type TransactionPlanExecutionResult as a, type TransactionPlanExecutor as b, type ProtocolClientOptions as c, type PlanTimingOptions as d, type SunSDKCreateOptions as e, type PlanSummary as f, type ProtocolAdapterDependencies as g, type ProtocolClientOverrides as h, type TransactionPlanFinalResult as i, type TransactionPlanKind as j, createContextExecutor as k, createProtocolsContext as l, executeTransactionPlan as m, requireWalletAddress as n, requireWalletSnapshot as o, requireRuntime as r };
@@ -0,0 +1,146 @@
1
+ import { FetchLike, JsonParser, RouterApiClient, SunPumpApiClient } from '@sun-protocol/sun-sdk-api';
2
+ import { NetworkEndpoints, ChainConfig } from '@sun-protocol/sun-sdk-chains';
3
+ import { TronAddress, Network, TransactionAction, ContractCallAction, DeferredContractCallAction, Percent, BigintIsh } from '@sun-protocol/sun-sdk-core';
4
+ import { TronClient, WalletAdapter, GetWallet, SubmittedCallback, Runtime, TransactionReceipt } from '@sun-protocol/sun-sdk-runtime';
5
+
6
+ type ApprovalMode = 'auto' | 'approve' | 'permit2' | 'none';
7
+ interface ContractOverrides {
8
+ readonly psmUsdt?: TronAddress | string;
9
+ readonly psmUsdd?: TronAddress | string;
10
+ readonly psm?: TronAddress | string;
11
+ readonly psmGemJoin?: TronAddress | string;
12
+ readonly psmInfoReader?: TronAddress | string;
13
+ readonly sunswapV2Router?: TronAddress | string;
14
+ readonly sunswapV3Router?: TronAddress | string;
15
+ readonly sunswapV3Factory?: TronAddress | string;
16
+ readonly sunswapV3PositionManager?: TronAddress | string;
17
+ readonly sunswapV4PoolManager?: TronAddress | string;
18
+ readonly sunswapV4PositionManager?: TronAddress | string;
19
+ readonly sunswapV4LpFeeHelper?: TronAddress | string;
20
+ }
21
+ /**
22
+ * @deprecated Reserved compatibility field. Router and Permit2 support is
23
+ * provided by the SDK and does not require adapter injection.
24
+ */
25
+ interface ProtocolAdapterDependencies {
26
+ readonly universalRouter?: unknown;
27
+ readonly permit2?: unknown;
28
+ }
29
+ interface ProtocolClientOverrides {
30
+ readonly routerApi?: RouterApiClient;
31
+ readonly sunPumpApi?: SunPumpApiClient;
32
+ }
33
+ interface ProtocolClientOptions {
34
+ readonly network: Network;
35
+ readonly tronClient?: TronClient;
36
+ readonly wallet?: WalletAdapter;
37
+ readonly getWallet?: GetWallet;
38
+ readonly onSubmitted?: SubmittedCallback;
39
+ readonly fetchImpl?: FetchLike;
40
+ readonly jsonParser?: JsonParser;
41
+ readonly endpoints?: Partial<NetworkEndpoints>;
42
+ readonly clients?: ProtocolClientOverrides;
43
+ readonly adapters?: ProtocolAdapterDependencies;
44
+ readonly now?: () => number;
45
+ /** Async Unix-millisecond clock for final Swap deadlines; defaults to the SUN time service. */
46
+ readonly getTransactionTime?: () => Promise<number>;
47
+ readonly idFactory?: () => string;
48
+ }
49
+ interface SunSDKCreateOptions extends ProtocolClientOptions {
50
+ readonly runtime?: Runtime;
51
+ }
52
+
53
+ type TransactionPlanKind = 'swap' | 'liquidity' | 'position' | 'pump';
54
+ interface PlanSummary {
55
+ readonly title: string;
56
+ readonly lines: readonly string[];
57
+ }
58
+ interface TransactionPlan {
59
+ readonly id: string;
60
+ readonly kind: TransactionPlanKind;
61
+ readonly network: Network;
62
+ /** Wallet address bound to plans containing runtime or wallet-signature actions. */
63
+ readonly owner?: TronAddress;
64
+ readonly summary: PlanSummary;
65
+ readonly approvals: readonly TransactionAction[];
66
+ readonly transactions: readonly TransactionAction[];
67
+ readonly metadata: Record<string, unknown>;
68
+ }
69
+ interface ExecutedActionResult {
70
+ readonly action: TransactionAction;
71
+ readonly result: unknown;
72
+ readonly txid?: string;
73
+ readonly receipt?: TransactionReceipt;
74
+ readonly materializedAction?: ContractCallAction;
75
+ }
76
+ type TransactionPlanFinalResult = {
77
+ readonly type: 'transaction';
78
+ readonly txid: string;
79
+ readonly raw: unknown;
80
+ } | {
81
+ readonly type: 'signature';
82
+ readonly signature: string;
83
+ } | {
84
+ readonly type: 'api';
85
+ readonly data: unknown;
86
+ };
87
+ interface TransactionPlanExecutionResult {
88
+ readonly plan: TransactionPlan;
89
+ readonly actions: readonly ExecutedActionResult[];
90
+ readonly txids: readonly string[];
91
+ readonly finalResult: TransactionPlanFinalResult | undefined;
92
+ }
93
+
94
+ interface TransactionPlanExecutor {
95
+ readonly network?: Network;
96
+ getAddress?(): Promise<TronAddress>;
97
+ sendAction?: Runtime['sendAction'];
98
+ waitForTransactionReceipt?: NonNullable<Runtime['waitForTransactionReceipt']>;
99
+ signTypedData?: Runtime['signTypedData'];
100
+ executeHttpAction?(action: TransactionAction): Promise<unknown>;
101
+ materializeAction?(action: DeferredContractCallAction, completedActions: readonly ExecutedActionResult[]): Promise<ContractCallAction>;
102
+ }
103
+ declare function executeTransactionPlan(plan: TransactionPlan, executor: TransactionPlanExecutor): Promise<TransactionPlanExecutionResult>;
104
+
105
+ interface ProtocolsContext {
106
+ readonly network: Network;
107
+ readonly chain: ChainConfig;
108
+ readonly endpoints: NetworkEndpoints;
109
+ readonly runtime?: Runtime;
110
+ readonly fetchImpl: FetchLike;
111
+ readonly jsonParser?: JsonParser;
112
+ readonly routerApi: RouterApiClient;
113
+ readonly sunPumpApi?: SunPumpApiClient;
114
+ readonly adapters: ProtocolAdapterDependencies;
115
+ readonly now: () => number;
116
+ readonly getTransactionTime: () => Promise<number>;
117
+ readonly idFactory: () => string;
118
+ }
119
+ /**
120
+ * Creates the public context used by staged transaction orchestration.
121
+ *
122
+ * Keep this available to consumers that render and execute TransactionPlan
123
+ * actions one step at a time instead of using a client's execute() shortcut.
124
+ */
125
+ declare function createProtocolsContext(options: SunSDKCreateOptions): ProtocolsContext;
126
+ declare function requireRuntime(context: ProtocolsContext, operation: string): Runtime;
127
+ declare function requireWalletAddress(context: ProtocolsContext, operation: string): Promise<TronAddress>;
128
+ interface ProtocolWalletSnapshot {
129
+ readonly wallet: WalletAdapter;
130
+ readonly address: TronAddress;
131
+ }
132
+ /** Resolves one wallet adapter for the current plan boundary. */
133
+ declare function requireWalletSnapshot(context: ProtocolsContext, operation: string): Promise<ProtocolWalletSnapshot>;
134
+ /** Creates the base public executor for staged TransactionPlan execution. */
135
+ declare function createContextExecutor(context: ProtocolsContext): TransactionPlanExecutor;
136
+
137
+ type SlippageInput = Percent | `${number}%`;
138
+ interface PlanTimingOptions {
139
+ readonly deadline?: BigintIsh;
140
+ readonly ttlSeconds?: number;
141
+ }
142
+ interface RecipientOptions {
143
+ readonly recipient?: TronAddress | string;
144
+ }
145
+
146
+ export { type ApprovalMode as A, type ContractOverrides as C, type ExecutedActionResult as E, type ProtocolsContext as P, type RecipientOptions as R, type SlippageInput as S, type TransactionPlan as T, type TransactionPlanExecutionResult as a, type TransactionPlanExecutor as b, type ProtocolClientOptions as c, type PlanTimingOptions as d, type SunSDKCreateOptions as e, type PlanSummary as f, type ProtocolAdapterDependencies as g, type ProtocolClientOverrides as h, type TransactionPlanFinalResult as i, type TransactionPlanKind as j, createContextExecutor as k, createProtocolsContext as l, executeTransactionPlan as m, requireWalletAddress as n, requireWalletSnapshot as o, requireRuntime as r };