@latchprotocol/widgets 0.1.1 → 0.1.3

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/chunks/{SwapWidget-CwkRtOfn.js → SwapWidget-B0oDyBNK.js} +2 -2
  3. package/dist/chunks/SwapWidget-B0oDyBNK.js.map +1 -0
  4. package/dist/chunks/{scan-Dhu7f4Nl.js → scan-Cdm3p_wF.js} +2 -2
  5. package/dist/chunks/scan-Cdm3p_wF.js.map +1 -0
  6. package/dist/chunks/{useLocker-CGpgCh75.js → useLocker-m3WH-bQm.js} +2 -2
  7. package/dist/chunks/{useLocker-CGpgCh75.js.map → useLocker-m3WH-bQm.js.map} +1 -1
  8. package/dist/components/LaunchWidget.d.ts +7 -6
  9. package/dist/components/LaunchWidget.d.ts.map +1 -1
  10. package/dist/components/LiquidityWidget.d.ts +2 -1
  11. package/dist/components/LiquidityWidget.d.ts.map +1 -1
  12. package/dist/components/LockerWidget.d.ts +2 -1
  13. package/dist/components/LockerWidget.d.ts.map +1 -1
  14. package/dist/components/LocksWidgets.d.ts +3 -2
  15. package/dist/components/LocksWidgets.d.ts.map +1 -1
  16. package/dist/components/SwapWidget.d.ts.map +1 -1
  17. package/dist/components/TokenTrustPanel.d.ts +2 -1
  18. package/dist/components/TokenTrustPanel.d.ts.map +1 -1
  19. package/dist/components/lockCharts.d.ts +3 -2
  20. package/dist/components/lockCharts.d.ts.map +1 -1
  21. package/dist/components/primitives.d.ts +12 -11
  22. package/dist/components/primitives.d.ts.map +1 -1
  23. package/dist/components/swap/SwapSettings.d.ts +2 -1
  24. package/dist/components/swap/SwapSettings.d.ts.map +1 -1
  25. package/dist/components/swap/TokenSelect.d.ts +5 -4
  26. package/dist/components/swap/TokenSelect.d.ts.map +1 -1
  27. package/dist/context/WidgetProvider.d.ts +2 -1
  28. package/dist/context/WidgetProvider.d.ts.map +1 -1
  29. package/dist/embed/lockBadge.d.ts +1 -1
  30. package/dist/embed.js +6 -6
  31. package/dist/embed.js.map +1 -1
  32. package/dist/headless.js +2 -2
  33. package/dist/index.js +9 -9
  34. package/dist/index.js.map +1 -1
  35. package/dist/latch-embed.js +1 -1
  36. package/dist/latch-embed.js.map +1 -1
  37. package/dist/latch-embed.mjs +1 -1
  38. package/dist/latch-embed.mjs.map +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunks/SwapWidget-CwkRtOfn.js.map +0 -1
  41. package/dist/chunks/scan-Dhu7f4Nl.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useLocker-CGpgCh75.js","sources":["../../src/adapters/binDistribution.ts","../../src/adapters/sale.ts","../../src/callpath/liquidity.ts","../../src/adapters/viem.ts","../../src/hooks/useLocks.ts","../../src/trust/model.ts","../../src/hooks/useTokenTrust.ts","../../src/locker/model.ts","../../src/hooks/useLocker.ts"],"sourcesContent":["// SPDX-License-Identifier: MIT\n/**\n * How a bin mint spreads its two amounts across a span of bins.\n *\n * `BinPool.mint` takes, per bin, the share of `amount0` (X) and of `amount1`\n * (Y) it receives, each scaled to 1e18. Bins strictly below the active id can\n * only hold Y, bins strictly above it only X, and the active bin holds both.\n * A share that sums to more than 1e18 on either side reverts; one that sums to\n * less leaves part of the amount undeposited. The uniform spread here sums each\n * side to EXACTLY 1e18 by pushing the rounding dust into that side's last bin.\n *\n * The active bin's composition is the pool's, not the depositor's: a deposit\n * whose X:Y ratio differs from the active bin's reserves pays the pool's\n * composition fee on the difference. This helper does not fold that in; the\n * amounts a quote reports are what the position manager pulls.\n */\n\nimport type { BinLiquidityShare } from \"./protocol.js\";\nimport { BIN_DISTRIBUTION_SCALE } from \"../callpath/constants.js\";\n\n/** Spreads liquidity evenly across a bin span, as a bin mint requires. */\nexport function buildUniformBinDistribution(\n binIdLower: number,\n binIdUpper: number,\n activeId: number,\n): BinLiquidityShare[] {\n if (binIdLower > binIdUpper) {\n throw new RangeError(`binIdLower ${binIdLower} exceeds binIdUpper ${binIdUpper}`);\n }\n const ids: number[] = [];\n for (let id = binIdLower; id <= binIdUpper; id += 1) ids.push(id);\n\n const xBins = ids.filter((id) => id >= activeId).length;\n const yBins = ids.filter((id) => id <= activeId).length;\n // The last bin on each side takes the rounding dust so the side sums to 1e18.\n const lastX = binIdUpper;\n const lastY = Math.min(activeId, binIdUpper);\n\n const shares: BinLiquidityShare[] = [];\n let xAssigned = 0n;\n let yAssigned = 0n;\n for (const id of ids) {\n const rawX = id >= activeId && xBins > 0 ? BIN_DISTRIBUTION_SCALE / BigInt(xBins) : 0n;\n const rawY = id <= activeId && yBins > 0 ? BIN_DISTRIBUTION_SCALE / BigInt(yBins) : 0n;\n const distributionX = id === lastX && rawX > 0n ? BIN_DISTRIBUTION_SCALE - xAssigned : rawX;\n const distributionY = id === lastY && rawY > 0n ? BIN_DISTRIBUTION_SCALE - yAssigned : rawY;\n xAssigned += distributionX;\n yAssigned += distributionY;\n shares.push({ binId: id, deltaId: id - activeId, distributionX, distributionY });\n }\n return shares;\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Optional extension point: a third-party token sale.\n *\n * ## Nothing in Latch implements this, on purpose\n *\n * A Latch launch is a pool with `LaunchGuardHook` attached and a decaying LP\n * fee. Buying into one is an ordinary swap. There is no `buy`, no soft or hard\n * cap, no allocation, no claim, and no per-wallet limit anywhere in the\n * protocol — see {@link ../callpath/launch.js} for why a per-wallet limit is\n * not implementable at the hook layer at all.\n *\n * This package used to ship a `LAUNCHPAD_ABI` describing a sale contract with\n * all of those features. No deployed contract implemented it, so every byte of\n * calldata it produced was guaranteed to fail. It has been deleted.\n *\n * ## What replaces it\n *\n * The shape of an *answer*, not the shape of somebody's contract. If you run a\n * genuine sale contract, you implement {@link TokenSaleAdapter} against your own\n * ABI and hang it off `ProtocolAdapter.sale`. Your `buildBuy` returns a\n * {@link ../adapters/protocol.js | WidgetTransactionRequest} — the same\n * adapter-neutral `{to, data, value}` the rest of this package speaks — so this\n * package never has to guess at a function selector it cannot verify.\n *\n * That is the whole point of putting it here: an unverifiable ABI is a\n * liability wherever it lives, and the one place it is honest is behind an\n * interface the integrator fills in from a contract they actually deployed.\n *\n * Nothing in this package reads `ProtocolAdapter.sale`. The styled\n * `LaunchWidget` binds to `LaunchGuardHook` and to nothing else. Consuming\n * these types means building your own UI on top of them.\n */\n\nimport type { Address } from \"viem\";\nimport type { ResolvedIntegratorConfig } from \"../config/integrator.js\";\nimport type { DataSource, TokenInfo, WidgetTransactionRequest } from \"./protocol.js\";\n\n/** Lifecycle of a third-party token sale. */\nexport type TokenSaleStatus =\n | \"upcoming\"\n | \"live\"\n | \"paused\"\n | \"ended\"\n | \"sold-out\"\n | \"cancelled\";\n\n/** Shape of a sale's price curve, if it has one. */\nexport type TokenSalePriceCurve =\n | { readonly kind: \"fixed\"; readonly price: bigint }\n | { readonly kind: \"linear\"; readonly startPrice: bigint; readonly endPrice: bigint }\n | {\n readonly kind: \"exponential\";\n readonly startPrice: bigint;\n readonly endPrice: bigint;\n /** Curvature exponent, scaled to 1e18. */\n readonly exponent: bigint;\n };\n\n/**\n * A sale, as your adapter reports it.\n *\n * Every field is optional-by-nullability where a sale might not have the\n * concept. Return `null` rather than zero: a UI can say \"no cap\" from `null`,\n * but `0n` reads as \"cap reached\".\n */\nexport interface TokenSaleInfo {\n /** The sale contract. */\n readonly id: Address;\n readonly token: TokenInfo;\n /** Currency buyers pay in. */\n readonly paymentToken: TokenInfo;\n readonly status: TokenSaleStatus;\n readonly totalForSale: bigint;\n readonly sold: bigint;\n readonly raised: bigint;\n readonly softCap: bigint | null;\n readonly hardCap: bigint | null;\n /** Unix seconds. */\n readonly startTime: bigint;\n readonly endTime: bigint;\n /** Maximum a single wallet may spend, in the payment currency. */\n readonly perWalletCap: bigint | null;\n readonly minPurchase: bigint;\n readonly priceCurve: TokenSalePriceCurve | null;\n readonly source: DataSource;\n}\n\n/** One account's standing in a sale. */\nexport interface TokenSaleAccountState {\n readonly saleId: Address;\n readonly account: Address;\n readonly spent: bigint;\n readonly allocated: bigint;\n /** Remaining spend allowed under the per-wallet cap. `null` when uncapped. */\n readonly capRemaining: bigint | null;\n readonly eligible: boolean;\n readonly ineligibleReason: string | null;\n readonly source: DataSource;\n}\n\n/** Quote for a sale purchase. */\nexport interface TokenSaleQuote {\n readonly sale: TokenSaleInfo;\n readonly amountIn: bigint;\n readonly tokensOut: bigint;\n /** Effective price paid, in payment units per whole token. */\n readonly effectivePrice: bigint;\n readonly source: DataSource;\n}\n\n/** Request to build a sale purchase transaction. */\nexport interface TokenSaleBuyRequest {\n readonly quote: TokenSaleQuote;\n readonly minTokensOut: bigint;\n readonly recipient: Address;\n readonly deadline: bigint;\n /**\n * The validated integrator config from the provider.\n *\n * Whether a sale contract can pay a referrer at all is a property of that\n * contract. If yours cannot, ignore this and do not silently drop the fee\n * into a transfer the user does not see.\n */\n readonly integrator: ResolvedIntegratorConfig;\n}\n\n/**\n * The seam. Implement it against your own sale contract.\n *\n * Every method may throw; the headless layer surfaces the error rather than\n * substituting a default.\n */\nexport interface TokenSaleAdapter {\n /** Identifies the implementation in error messages, e.g. `\"acme-launchpad\"`. */\n readonly kind: string;\n listSales(): Promise<readonly TokenSaleInfo[]>;\n getSale(id: Address): Promise<TokenSaleInfo | null>;\n getSaleAccountState(id: Address, account: Address): Promise<TokenSaleAccountState>;\n quoteBuy(sale: TokenSaleInfo, amountIn: bigint): Promise<TokenSaleQuote>;\n buildBuy(request: TokenSaleBuyRequest): Promise<WidgetTransactionRequest>;\n}\n\n/** Thrown by a host that wires a sale UI without wiring a sale adapter. */\nexport class NoSaleAdapterError extends Error {\n constructor() {\n super(\n \"[@latchprotocol/widgets] no sale adapter is configured. Latch has no sale contract - \" +\n \"a launch is a pool with LaunchGuardHook attached, and buying into one is a swap. \" +\n \"Set ProtocolAdapter.sale only if you run your own sale contract.\",\n );\n this.name = \"NoSaleAdapterError\";\n }\n}\n\n/** Narrowing helper, so a host can branch without a cast. */\nexport function hasSaleAdapter(\n adapter: { readonly sale?: TokenSaleAdapter },\n): adapter is { readonly sale: TokenSaleAdapter } {\n return adapter.sale !== undefined;\n}\n","// SPDX-License-Identifier: MIT\r\n/**\r\n * Liquidity call-path construction for both pool types.\r\n *\r\n * Concentrated liquidity and the liquidity book differ in what a \"range\" is -\r\n * a tick pair versus a span of bins - and in the shape of their position\r\n * manager params. Everything above this file works with the single\r\n * {@link ../adapters/protocol.js | LiquidityRange} union; the divergence is\r\n * confined to the two encoders here.\r\n *\r\n * Both paths go through `PositionManager.modifyLiquidities(unlockData, deadline)`\r\n * with the same `abi.encode(actions, params)` transport the swap path uses.\r\n *\r\n * ## Why there is no integrator fee on this path\r\n *\r\n * `PAY_PORTION` and `TAKE_PORTION` split an output currency. Adding liquidity\r\n * has no output to split, and removing it returns the user's own principal -\r\n * skimming that is not a referral fee, it is a withdrawal charge. Integrator\r\n * revenue on liquidity, if it is ever added, belongs in a hook that earns from\r\n * the position, not in a router step that taxes the deposit. The `integrator`\r\n * config is still carried here so it can be recorded in analytics events.\r\n */\r\n\r\nimport { encodeAbiParameters, encodeFunctionData, type Address, type Hex } from \"viem\";\r\nimport { NATIVE_CURRENCY, type PoolKey } from \"@latchprotocol/sdk\";\r\nimport { ACTIONS, MSG_SENDER, POSITION_MANAGER_ABI } from \"./constants.js\";\r\nimport { plan } from \"./plan.js\";\r\nimport { POOL_KEY_COMPONENTS } from \"./swap.js\";\r\n\r\nconst CL_MINT_PARAMS = [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"tickLower\", type: \"int24\" },\r\n { name: \"tickUpper\", type: \"int24\" },\r\n { name: \"liquidity\", type: \"uint256\" },\r\n { name: \"amount0Max\", type: \"uint128\" },\r\n { name: \"amount1Max\", type: \"uint128\" },\r\n { name: \"owner\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n] as const;\r\n\r\nconst CL_MODIFY_PARAMS = [\r\n { name: \"tokenId\", type: \"uint256\" },\r\n { name: \"liquidity\", type: \"uint256\" },\r\n { name: \"amount0\", type: \"uint128\" },\r\n { name: \"amount1\", type: \"uint128\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n] as const;\r\n\r\nconst CURRENCY_PAIR = [\r\n { name: \"currency0\", type: \"address\" },\r\n { name: \"currency1\", type: \"address\" },\r\n] as const;\r\n\r\nconst CURRENCY_PAIR_AND_ADDRESS = [\r\n { name: \"currency0\", type: \"address\" },\r\n { name: \"currency1\", type: \"address\" },\r\n { name: \"recipient\", type: \"address\" },\r\n] as const;\r\n\r\nconst CURRENCY_AND_ADDRESS = [\r\n { name: \"currency\", type: \"address\" },\r\n { name: \"to\", type: \"address\" },\r\n] as const;\r\n\r\n/**\r\n * `SWEEP(native, MSG_SENDER)`, appended to a deposit that attaches native value.\r\n *\r\n * `SETTLE_PAIR` pays the vault exactly the native debt and leaves the rest of\r\n * `msg.value` - the slippage headroom between the amount pulled and\r\n * `amountMax` - sitting in the position manager, where anyone's next sweep\r\n * would take it. This returns it to the caller in the same transaction.\r\n */\r\nfunction sweepNativeStep(): readonly [number, Hex, string] {\r\n return [\r\n ACTIONS.SWEEP,\r\n encodeAbiParameters(CURRENCY_AND_ADDRESS, [NATIVE_CURRENCY, MSG_SENDER]),\r\n \"sweep unspent native value back to the caller\",\r\n ];\r\n}\r\n\r\nconst BIN_ADD_LIQUIDITY_PARAMS = [\r\n {\r\n name: \"params\",\r\n type: \"tuple\",\r\n components: [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"amount0\", type: \"uint128\" },\r\n { name: \"amount1\", type: \"uint128\" },\r\n { name: \"amount0Max\", type: \"uint128\" },\r\n { name: \"amount1Max\", type: \"uint128\" },\r\n { name: \"activeIdDesired\", type: \"uint256\" },\r\n { name: \"idSlippage\", type: \"uint256\" },\r\n { name: \"deltaIds\", type: \"int256[]\" },\r\n { name: \"distributionX\", type: \"uint256[]\" },\r\n { name: \"distributionY\", type: \"uint256[]\" },\r\n { name: \"minLiquidities\", type: \"uint256[]\" },\r\n { name: \"to\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n ],\r\n },\r\n] as const;\r\n\r\nconst BIN_REMOVE_LIQUIDITY_PARAMS = [\r\n {\r\n name: \"params\",\r\n type: \"tuple\",\r\n components: [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"amount0Min\", type: \"uint128\" },\r\n { name: \"amount1Min\", type: \"uint128\" },\r\n { name: \"ids\", type: \"uint256[]\" },\r\n { name: \"amounts\", type: \"uint256[]\" },\r\n { name: \"from\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n ],\r\n },\r\n] as const;\r\n\r\nfunction poolKeyStruct(key: PoolKey): {\r\n currency0: Address;\r\n currency1: Address;\r\n hooks: Address;\r\n poolManager: Address;\r\n fee: number;\r\n parameters: Hex;\r\n} {\r\n return {\r\n currency0: key.currency0,\r\n currency1: key.currency1,\r\n hooks: key.hooks,\r\n poolManager: key.poolManager,\r\n fee: key.fee,\r\n parameters: key.parameters,\r\n };\r\n}\r\n\r\n/** An encoded position-manager call. */\r\nexport interface EncodedLiquidityCall {\r\n readonly to: Address;\r\n readonly data: Hex;\r\n readonly value: bigint;\r\n readonly planTrace: string;\r\n}\r\n\r\n/** Arguments for minting a new concentrated-liquidity position. */\r\nexport interface BuildCLMintArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly tickLower: number;\r\n readonly tickUpper: number;\r\n readonly liquidity: bigint;\r\n readonly amount0Max: bigint;\r\n readonly amount1Max: bigint;\r\n readonly owner: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n /** Native value to attach, when one side of the pair is the native asset. */\r\n readonly value?: bigint;\r\n}\r\n\r\n/** Encodes `CL_MINT_POSITION` followed by `SETTLE_PAIR` (and `SWEEP` of the native side when value is attached). */\r\nexport function buildCLMintCall(args: BuildCLMintArgs): EncodedLiquidityCall {\r\n assertTickRange(args.tickLower, args.tickUpper);\r\n if (args.liquidity <= 0n) {\r\n throw new RangeError(`[@latchprotocol/widgets] liquidity must be positive: ${args.liquidity}`);\r\n }\r\n const p = plan()\r\n .add(\r\n ACTIONS.CL_MINT_POSITION,\r\n encodeAbiParameters(CL_MINT_PARAMS, [\r\n poolKeyStruct(args.poolKey),\r\n args.tickLower,\r\n args.tickUpper,\r\n args.liquidity,\r\n args.amount0Max,\r\n args.amount1Max,\r\n args.owner,\r\n args.hookData ?? \"0x\",\r\n ]),\r\n `mint CL position [${args.tickLower}, ${args.tickUpper}]`,\r\n )\r\n .add(\r\n ACTIONS.SETTLE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR, [args.poolKey.currency0, args.poolKey.currency1]),\r\n \"settle both currencies from the caller\",\r\n );\r\n if ((args.value ?? 0n) > 0n) p.add(...sweepNativeStep());\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: args.value ?? 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for decreasing or closing a concentrated-liquidity position. */\r\nexport interface BuildCLDecreaseArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly tokenId: bigint;\r\n readonly liquidity: bigint;\r\n readonly amount0Min: bigint;\r\n readonly amount1Min: bigint;\r\n readonly recipient: Address;\r\n readonly owner: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n}\r\n\r\n/** Encodes `CL_DECREASE_LIQUIDITY` followed by `TAKE_PAIR`. */\r\nexport function buildCLDecreaseCall(args: BuildCLDecreaseArgs): EncodedLiquidityCall {\r\n if (args.liquidity <= 0n) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] liquidity to remove must be positive: ${args.liquidity}`,\r\n );\r\n }\r\n const recipient = args.recipient === args.owner ? MSG_SENDER : args.recipient;\r\n const p = plan()\r\n .add(\r\n ACTIONS.CL_DECREASE_LIQUIDITY,\r\n encodeAbiParameters(CL_MODIFY_PARAMS, [\r\n args.tokenId,\r\n args.liquidity,\r\n args.amount0Min,\r\n args.amount1Min,\r\n args.hookData ?? \"0x\",\r\n ]),\r\n `decrease CL position #${args.tokenId} by ${args.liquidity}`,\r\n )\r\n .add(\r\n ACTIONS.TAKE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR_AND_ADDRESS, [\r\n args.poolKey.currency0,\r\n args.poolKey.currency1,\r\n recipient,\r\n ]),\r\n \"take both currencies to the recipient\",\r\n );\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for adding liquidity to a bin pool. */\r\nexport interface BuildBinAddArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly amount0: bigint;\r\n readonly amount1: bigint;\r\n readonly amount0Max: bigint;\r\n readonly amount1Max: bigint;\r\n readonly activeIdDesired: number;\r\n readonly idSlippage: number;\r\n /** Bin offsets relative to the active id, one entry per bin. */\r\n readonly deltaIds: readonly number[];\r\n /** Share of `amount0` per bin, scaled to 1e18. Must sum to <= 1e18. */\r\n readonly distributionX: readonly bigint[];\r\n /** Share of `amount1` per bin, scaled to 1e18. Must sum to <= 1e18. */\r\n readonly distributionY: readonly bigint[];\r\n readonly to: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n readonly value?: bigint;\r\n}\r\n\r\n/** Encodes `BIN_ADD_LIQUIDITY` followed by `SETTLE_PAIR` (and `SWEEP` of the native side when value is attached). */\r\nexport function buildBinAddCall(args: BuildBinAddArgs): EncodedLiquidityCall {\r\n const binCount = args.deltaIds.length;\r\n if (binCount === 0) {\r\n throw new RangeError(\"[@latchprotocol/widgets] a bin mint must target at least one bin\");\r\n }\r\n if (args.distributionX.length !== binCount || args.distributionY.length !== binCount) {\r\n throw new RangeError(\r\n \"[@latchprotocol/widgets] deltaIds, distributionX and distributionY must be the same length\",\r\n );\r\n }\r\n if (!Number.isInteger(args.activeIdDesired) || args.activeIdDesired < 0) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] activeIdDesired must be a non-negative integer: ${args.activeIdDesired}`,\r\n );\r\n }\r\n\r\n const p = plan()\r\n .add(\r\n ACTIONS.BIN_ADD_LIQUIDITY,\r\n encodeAbiParameters(BIN_ADD_LIQUIDITY_PARAMS, [\r\n {\r\n poolKey: poolKeyStruct(args.poolKey),\r\n amount0: args.amount0,\r\n amount1: args.amount1,\r\n amount0Max: args.amount0Max,\r\n amount1Max: args.amount1Max,\r\n activeIdDesired: BigInt(args.activeIdDesired),\r\n idSlippage: BigInt(args.idSlippage),\r\n deltaIds: args.deltaIds.map((id) => BigInt(id)),\r\n distributionX: [...args.distributionX],\r\n distributionY: [...args.distributionY],\r\n // One entry per bin. Zero means \"accept whatever the pool mints\"; the\r\n // real slippage guard for a bin mint is idSlippage plus amountNMax.\r\n minLiquidities: args.deltaIds.map(() => 0n),\r\n to: args.to,\r\n hookData: args.hookData ?? \"0x\",\r\n },\r\n ]),\r\n `add bin liquidity across ${binCount} bins around id ${args.activeIdDesired}`,\r\n )\r\n .add(\r\n ACTIONS.SETTLE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR, [args.poolKey.currency0, args.poolKey.currency1]),\r\n \"settle both currencies from the caller\",\r\n );\r\n if ((args.value ?? 0n) > 0n) p.add(...sweepNativeStep());\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: args.value ?? 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for removing liquidity from a bin pool. */\r\nexport interface BuildBinRemoveArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly amount0Min: bigint;\r\n readonly amount1Min: bigint;\r\n /** Bin ids being burned. */\r\n readonly ids: readonly number[];\r\n /** Share amount burned per bin, aligned with `ids`. */\r\n readonly amounts: readonly bigint[];\r\n readonly from: Address;\r\n readonly recipient: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n}\r\n\r\n/** Encodes `BIN_REMOVE_LIQUIDITY` followed by `TAKE_PAIR`. */\r\nexport function buildBinRemoveCall(args: BuildBinRemoveArgs): EncodedLiquidityCall {\r\n if (args.ids.length === 0) {\r\n throw new RangeError(\"[@latchprotocol/widgets] a bin burn must target at least one bin\");\r\n }\r\n if (args.ids.length !== args.amounts.length) {\r\n throw new RangeError(\"[@latchprotocol/widgets] ids and amounts must be the same length\");\r\n }\r\n const recipient = args.recipient === args.from ? MSG_SENDER : args.recipient;\r\n const p = plan()\r\n .add(\r\n ACTIONS.BIN_REMOVE_LIQUIDITY,\r\n encodeAbiParameters(BIN_REMOVE_LIQUIDITY_PARAMS, [\r\n {\r\n poolKey: poolKeyStruct(args.poolKey),\r\n amount0Min: args.amount0Min,\r\n amount1Min: args.amount1Min,\r\n ids: args.ids.map((id) => BigInt(id)),\r\n amounts: [...args.amounts],\r\n from: args.from,\r\n hookData: args.hookData ?? \"0x\",\r\n },\r\n ]),\r\n `remove bin liquidity from ${args.ids.length} bins`,\r\n )\r\n .add(\r\n ACTIONS.TAKE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR_AND_ADDRESS, [\r\n args.poolKey.currency0,\r\n args.poolKey.currency1,\r\n recipient,\r\n ]),\r\n \"take both currencies to the recipient\",\r\n );\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\nfunction assertTickRange(tickLower: number, tickUpper: number): void {\r\n if (!Number.isInteger(tickLower) || !Number.isInteger(tickUpper)) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] ticks must be integers: [${tickLower}, ${tickUpper}]`,\r\n );\r\n }\r\n if (tickLower >= tickUpper) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] tickLower must be below tickUpper: [${tickLower}, ${tickUpper}]`,\r\n );\r\n }\r\n}\r\n","// SPDX-License-Identifier: MIT\n/**\n * Live protocol adapter, backed by viem.\n *\n * This is the implementation that produces **real calldata** and submits real\n * transactions. It is the swap and liquidity call paths from `src/callpath/`\n * wired to a viem `PublicClient` for reads and a wallet for writes.\n *\n * ## What it can and cannot do today\n *\n * Bounded honestly, feature by feature:\n *\n * - **Encoding** is complete and unit-tested. `buildSwap`, `buildAddLiquidity`\n * and `buildRemoveLiquidity` produce the exact calldata the router and\n * position managers decode, integrator fee step included.\n * - **Launches** are read from the launch guards, keyed by pool id: CL pools\n * from `contracts.launchGuardHook`, Bin pools from `contracts.binLaunchGuardHook`.\n * With neither configured every launch read throws\n * `ChainConfigError` rather than guessing an address. On a chain with no\n * `LaunchGuardHook` deployed, that is the correct and only answer.\n * - **Token, balance and allowance reads** are ordinary ERC-20 and Permit2\n * calls and will work against any chain that has them.\n * - **Pool discovery** is not on-chain: the singleton has no pool enumeration.\n * Pass the pools you support, or wire an indexer (`@latchprotocol/sdk/indexer`\n * describes the schema).\n * - **Quoting** requires either a deployed quoter or a host-supplied function.\n * Without one, `quoteSwap` throws {@link UnsupportedOperationError} rather\n * than inventing a number - a fabricated quote is worse than no quote.\n */\n\nimport {\n BaseError,\n ExecutionRevertedError,\n decodeAbiParameters,\n encodeFunctionData,\n isAddressEqual,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport {\n BIN_LAUNCH_GUARD_HOOK_ABI,\n CLOCK_MODE_CALLDATA,\n LAUNCHPAD_KIT_V2_ABI,\n TIMESTAMP_CLOCK_MODE,\n binRawPriceFromId,\n getDeployment,\n isDynamicLPFee,\n quoterAbiFor,\n poolKeyToId,\n readBinPoolKeyParameters,\n readCLPoolKeyParameters,\n readContractClock,\n type PoolId,\n type PoolKey,\n} from \"@latchprotocol/sdk\";\n\n/* getSlot0 on both pool managers: the pool's own price, for the no-impact output. */\nconst CL_SLOT0_ABI = [\n {\n type: \"function\",\n name: \"getSlot0\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"sqrtPriceX96\", type: \"uint160\" },\n { name: \"tick\", type: \"int24\" },\n { name: \"protocolFee\", type: \"uint24\" },\n { name: \"lpFee\", type: \"uint24\" },\n ],\n },\n] as const;\nconst BIN_SLOT0_ABI = [\n {\n type: \"function\",\n name: \"getSlot0\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"activeId\", type: \"uint24\" },\n { name: \"protocolFee\", type: \"uint24\" },\n { name: \"lpFee\", type: \"uint24\" },\n ],\n },\n] as const;\nconst Q192 = 2n ** 192n;\n\n/* The pool-manager views the liquidity paths read: pool liquidity and fee\n growth (CL, for a position's amounts and uncollected fees), bin reserves and\n share supply (Bin, for what a holder's shares are worth). */\nconst CL_POOL_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"getLiquidity\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [{ name: \"liquidity\", type: \"uint128\" }],\n },\n {\n type: \"function\",\n name: \"getFeeGrowthGlobals\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"feeGrowthGlobal0x128\", type: \"uint256\" },\n { name: \"feeGrowthGlobal1x128\", type: \"uint256\" },\n ],\n },\n {\n type: \"function\",\n name: \"getPoolTickInfo\",\n stateMutability: \"view\",\n inputs: [\n { name: \"id\", type: \"bytes32\" },\n { name: \"tick\", type: \"int24\" },\n ],\n outputs: [\n {\n name: \"info\",\n type: \"tuple\",\n components: [\n { name: \"liquidityGross\", type: \"uint128\" },\n { name: \"liquidityNet\", type: \"int128\" },\n { name: \"feeGrowthOutside0X128\", type: \"uint256\" },\n { name: \"feeGrowthOutside1X128\", type: \"uint256\" },\n ],\n },\n ],\n },\n] as const;\nconst BIN_POOL_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"getBin\",\n stateMutability: \"view\",\n inputs: [\n { name: \"id\", type: \"bytes32\" },\n { name: \"binId\", type: \"uint24\" },\n ],\n outputs: [\n { name: \"binReserveX\", type: \"uint128\" },\n { name: \"binReserveY\", type: \"uint128\" },\n { name: \"binLiquidity\", type: \"uint256\" },\n { name: \"totalShares\", type: \"uint256\" },\n ],\n },\n] as const;\nconst POOL_KEY_OUTPUT = {\n name: \"poolKey\",\n type: \"tuple\",\n components: [\n { name: \"currency0\", type: \"address\" },\n { name: \"currency1\", type: \"address\" },\n { name: \"hooks\", type: \"address\" },\n { name: \"poolManager\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"parameters\", type: \"bytes32\" },\n ],\n} as const;\n/* CLPositionManager: a solmate ERC-721 with no owner enumeration, so a\n holder's tokens come from `Transfer(to)` logs confirmed by `ownerOf`. */\nconst CL_POSM_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"ownerOf\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"uint256\" }],\n outputs: [{ name: \"owner\", type: \"address\" }],\n },\n {\n type: \"function\",\n name: \"positions\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [\n POOL_KEY_OUTPUT,\n { name: \"tickLower\", type: \"int24\" },\n { name: \"tickUpper\", type: \"int24\" },\n { name: \"liquidity\", type: \"uint128\" },\n { name: \"feeGrowthInside0LastX128\", type: \"uint256\" },\n { name: \"feeGrowthInside1LastX128\", type: \"uint256\" },\n { name: \"subscriber\", type: \"address\" },\n ],\n },\n {\n type: \"event\",\n name: \"Transfer\",\n inputs: [\n { name: \"from\", type: \"address\", indexed: true },\n { name: \"to\", type: \"address\", indexed: true },\n { name: \"id\", type: \"uint256\", indexed: true },\n ],\n },\n] as const;\n/* BinPositionManager: ERC-1155-like shares per (pool, bin); the token ids a\n holder ever received come from `TransferBatch(to)` logs, the live balance from `balanceOf`. */\nconst BIN_POSM_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"positions\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [POOL_KEY_OUTPUT, { name: \"binId\", type: \"uint24\" }],\n },\n {\n type: \"function\",\n name: \"balanceOf\",\n stateMutability: \"view\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"id\", type: \"uint256\" },\n ],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n },\n {\n type: \"event\",\n name: \"TransferBatch\",\n inputs: [\n { name: \"sender\", type: \"address\", indexed: true },\n { name: \"from\", type: \"address\", indexed: true },\n { name: \"to\", type: \"address\", indexed: true },\n { name: \"ids\", type: \"uint256[]\", indexed: false },\n { name: \"amounts\", type: \"uint256[]\", indexed: false },\n ],\n },\n] as const;\nimport type { ChainConfig } from \"../config/chain.js\";\nimport { nextBlockClock, requireContract } from \"../config/chain.js\";\nimport {\n ERC20_ABI,\n MAX_UINT160,\n MAX_UINT256,\n MAX_UINT48,\n PERMIT2_ABI,\n} from \"../callpath/constants.js\";\nimport { buildSwapCall, type SwapHop } from \"../callpath/swap.js\";\nimport {\n buildBinAddCall,\n buildBinRemoveCall,\n buildCLDecreaseCall,\n buildCLMintCall,\n} from \"../callpath/liquidity.js\";\nimport {\n decodeLaunchGuard,\n isLaunchConfigured,\n launchGuardAbiFor,\n type DurationClock,\n type RawLaunchGuard,\n} from \"../callpath/launch.js\";\nimport {\n amountsForLiquidity,\n getLiquidityForAmounts,\n getSqrtRatioAtTick,\n uncollectedFees,\n} from \"../core/clMath.js\";\nimport { binShareAmounts, binStepOf, tickSpacingOf } from \"../core/pool.js\";\nimport { buildUniformBinDistribution } from \"./binDistribution.js\";\nimport {\n UnsupportedOperationError,\n WalletNotConnectedError,\n type AddLiquidityExecutionRequest,\n type AddLiquidityQuote,\n type AddLiquidityQuoteRequest,\n type ApprovalRequirement,\n type LaunchInfo,\n type PoolInfo,\n type PoolType,\n type PoolState,\n type PositionInfo,\n type ProtocolAdapter,\n type RemoveLiquidityExecutionRequest,\n type RemoveLiquidityQuote,\n type SwapExecutionRequest,\n type SwapQuoteRequest,\n type SwapQuoteResult,\n type TokenInfo,\n type TransactionOutcome,\n type WidgetTransactionRequest,\n} from \"./protocol.js\";\n\nconst NATIVE: Address = \"0x0000000000000000000000000000000000000000\";\n\n/** Minimal wallet surface. Any wallet stack that can sign satisfies this. */\nexport interface WidgetWallet {\n /** Currently selected account, or `null`. */\n getAccount(): Promise<Address | null>;\n /** Submits a transaction and returns its hash. */\n sendTransaction(request: {\n to: Address;\n data: Hex;\n value: bigint;\n }): Promise<Hex>;\n}\n\n/**\n * Host-supplied functions for the parts the protocol cannot answer on its own.\n *\n * Each one is optional. Omitting a function makes the corresponding widget\n * feature fail loudly with a named error instead of degrading to invented data.\n */\nexport interface ViemAdapterOverrides {\n quoteSwap?: (request: SwapQuoteRequest, pools: readonly PoolInfo[]) => Promise<SwapQuoteResult>;\n quoteAddLiquidity?: (request: AddLiquidityQuoteRequest) => Promise<AddLiquidityQuote>;\n quoteRemoveLiquidity?: (\n position: PositionInfo,\n percentBps: number,\n ) => Promise<RemoveLiquidityQuote>;\n listPositions?: (owner: Address, pool?: PoolInfo) => Promise<readonly PositionInfo[]>;\n getPoolState?: (pool: PoolInfo) => Promise<PoolState>;\n /** Resolves a route. Defaults to a direct pool match over `pools`. */\n findRoute?: (\n tokenIn: TokenInfo,\n tokenOut: TokenInfo,\n pools: readonly PoolInfo[],\n ) => readonly SwapHop[];\n}\n\n/** Options for {@link createViemAdapter}. */\nexport interface ViemAdapterOptions {\n readonly chain: ChainConfig;\n readonly publicClient: PublicClient;\n readonly wallet?: WidgetWallet;\n /** Tokens offered in the picker. There is no on-chain token registry. */\n readonly tokens: readonly TokenInfo[];\n /**\n * Pools this integrator supports. There is no on-chain pool enumeration.\n *\n * Launch pools live in this list too: a launch is a pool. `listLaunches`\n * selects the ones whose key names `contracts.launchGuardHook`, so there is\n * no separate launch list to keep in sync.\n */\n readonly pools: readonly PoolInfo[];\n /**\n * The block the position managers were deployed at (or any earlier one).\n *\n * Neither position manager enumerates a holder's positions, so\n * `listPositions` reconstructs them from `Transfer` / `TransferBatch` logs\n * addressed to the owner and confirms each against live state. The scan\n * starts here. Without it `listPositions` throws rather than scanning from\n * genesis, which public endpoints refuse and which would read as \"no\n * positions\" when it silently returned nothing.\n */\n readonly positionsFromBlock?: bigint;\n readonly overrides?: ViemAdapterOverrides;\n}\n\nclass ViemProtocolAdapter implements ProtocolAdapter {\n readonly kind = \"viem\";\n readonly isMock = false;\n readonly chain: ChainConfig;\n\n readonly #options: ViemAdapterOptions;\n\n constructor(options: ViemAdapterOptions) {\n this.#options = options;\n this.chain = options.chain;\n }\n\n get #client(): PublicClient {\n return this.#options.publicClient;\n }\n\n get #overrides(): ViemAdapterOverrides {\n return this.#options.overrides ?? {};\n }\n\n async getAccount(): Promise<Address | null> {\n const wallet = this.#options.wallet;\n if (wallet === undefined) return null;\n return wallet.getAccount();\n }\n\n async listTokens(): Promise<readonly TokenInfo[]> {\n return this.#options.tokens;\n }\n\n async getToken(address: Address): Promise<TokenInfo | null> {\n const known = this.#options.tokens.find((token) => isAddressEqual(token.address, address));\n if (known !== undefined) return known;\n if (isAddressEqual(address, NATIVE)) {\n return {\n address: NATIVE,\n symbol: this.chain.nativeCurrency.symbol,\n name: this.chain.nativeCurrency.name,\n decimals: this.chain.nativeCurrency.decimals,\n isNative: true,\n };\n }\n const [symbol, name, decimals] = await Promise.all([\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"symbol\" }),\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"name\" }),\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"decimals\" }),\n ]);\n return { address, symbol, name, decimals: Number(decimals) };\n }\n\n async getBalance(token: TokenInfo, owner: Address): Promise<bigint> {\n if (token.isNative === true || isAddressEqual(token.address, NATIVE)) {\n return this.#client.getBalance({ address: owner });\n }\n return this.#client.readContract({\n address: token.address,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [owner],\n });\n }\n\n async listPools(): Promise<readonly PoolInfo[]> {\n return this.#options.pools;\n }\n\n /**\n * The pool's live state from its manager's `getSlot0` (plus `getLiquidity`\n * for a CL pool). An uninitialised pool answers a zero price, which is\n * reported as an error rather than as tick 0.\n */\n async getPoolState(pool: PoolInfo): Promise<PoolState> {\n const override = this.#overrides.getPoolState;\n if (override !== undefined) return override(pool);\n if (pool.poolType === \"CL\") {\n const [[sqrtPriceX96, tick], liquidity] = await Promise.all([\n this.#client.readContract({ address: pool.key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] }),\n this.#client.readContract({ address: pool.key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getLiquidity\", args: [pool.id] }),\n ]);\n if (sqrtPriceX96 === 0n) {\n throw new UnsupportedOperationError(\"getPoolState\", `pool ${pool.id} is not initialised on ${pool.key.poolManager}`);\n }\n return { poolId: pool.id, poolType: \"CL\", currentTick: tick, sqrtPriceX96, liquidity, source: \"live\" };\n }\n const [activeId] = await this.#client.readContract({ address: pool.key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n if (activeId === 0) {\n throw new UnsupportedOperationError(\"getPoolState\", `pool ${pool.id} is not initialised on ${pool.key.poolManager}`);\n }\n return { poolId: pool.id, poolType: \"BIN\", activeId, source: \"live\" };\n }\n\n /**\n * The two allowances `spender` needs before it can pull `token` through\n * Permit2: ERC-20 to Permit2, then Permit2 to the spender. The spender is\n * the router for a swap (the default) and a position manager for a\n * liquidity add; the liquidity hooks pass it, because an allowance to the\n * router does nothing for a mint.\n */\n async getApprovalRequirements(\n token: TokenInfo,\n owner: Address,\n amount: bigint,\n spender?: Address,\n ): Promise<readonly ApprovalRequirement[]> {\n if (token.isNative === true || isAddressEqual(token.address, NATIVE)) return [];\n const permit2 = requireContract(this.chain, \"permit2\", \"pull the input token for a swap\");\n const router = spender ?? requireContract(this.chain, \"universalRouter\", \"execute a swap\");\n\n const requirements: ApprovalRequirement[] = [];\n\n const erc20Allowance = await this.#client.readContract({\n address: token.address,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [owner, permit2],\n });\n if (erc20Allowance < amount) {\n requirements.push({\n kind: \"erc20-to-permit2\",\n token,\n spender: permit2,\n current: erc20Allowance,\n required: amount,\n });\n }\n\n const [permit2Amount, expiration] = await this.#client.readContract({\n address: permit2,\n abi: PERMIT2_ABI,\n functionName: \"allowance\",\n args: [owner, token.address, router],\n });\n const nowSeconds = BigInt(Math.floor(Date.now() / 1000));\n const expired = BigInt(expiration) !== 0n && BigInt(expiration) <= nowSeconds;\n if (BigInt(permit2Amount) < amount || expired) {\n requirements.push({\n kind: \"permit2-to-router\",\n token,\n spender: router,\n current: expired ? 0n : BigInt(permit2Amount),\n required: amount,\n });\n }\n\n return requirements;\n }\n\n async buildApproval(requirement: ApprovalRequirement): Promise<WidgetTransactionRequest> {\n if (requirement.kind === \"erc20-to-permit2\") {\n return {\n to: requirement.token.address,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [requirement.spender, MAX_UINT256],\n }),\n value: 0n,\n summary: `Approve ${requirement.token.symbol} for Permit2`,\n source: \"live\",\n };\n }\n const permit2 = requireContract(this.chain, \"permit2\", \"approve the router through Permit2\");\n return {\n to: permit2,\n data: encodeFunctionData({\n abi: PERMIT2_ABI,\n functionName: \"approve\",\n args: [requirement.token.address, requirement.spender, MAX_UINT160, Number(MAX_UINT48)],\n }),\n value: 0n,\n summary: `Approve ${requirement.spender} to spend ${requirement.token.symbol} via Permit2`,\n source: \"live\",\n };\n }\n\n /**\n * Quotes an exact-input swap.\n *\n * With `overrides.quoteSwap` the host answers. Otherwise every configured\n * pool holding both tokens is quoted DIRECTLY against the deployed quoter for\n * its type (`contracts.quoter` for CL, `contracts.binQuoter` for Bin) and the\n * best output wins. No multi-hop routing: a route this adapter did not quote\n * is a route it cannot vouch for. Throws when no quoter can answer.\n *\n * The LP fee shown beside the quote is the pool's static fee, or, for a\n * dynamic-fee pool whose hook is a launch guard, the guard's `currentFee`.\n * Any other dynamic pool is reported `lpFeeUnknown`, which the widget renders\n * as \"dynamic\" rather than as a rate it did not read.\n */\n async quoteSwap(request: SwapQuoteRequest): Promise<SwapQuoteResult> {\n const override = this.#overrides.quoteSwap;\n if (override !== undefined) return override(request, this.#options.pools);\n\n const contracts = this.chain.contracts;\n const candidates = this.#options.pools.filter(\n (pool) =>\n (request.poolId === undefined || pool.id === request.poolId) &&\n ((isAddressEqual(pool.token0.address, request.tokenIn.address) &&\n isAddressEqual(pool.token1.address, request.tokenOut.address)) ||\n (isAddressEqual(pool.token1.address, request.tokenIn.address) &&\n isAddressEqual(pool.token0.address, request.tokenOut.address))),\n );\n if (candidates.length === 0) {\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n request.poolId !== undefined\n ? `pool ${request.poolId} is not a configured pool holding both ${request.tokenIn.symbol} and ${request.tokenOut.symbol}.`\n : `no configured pool holds both ${request.tokenIn.symbol} and ${request.tokenOut.symbol}. ` +\n \"This adapter quotes direct pools only; supply `overrides.quoteSwap` for multi-hop routes.\",\n );\n }\n const quotable = candidates.filter((pool) =>\n pool.poolType === \"CL\" ? contracts.quoter !== undefined : contracts.binQuoter !== undefined,\n );\n if (quotable.length === 0) {\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n `a pool for this pair exists but no quoter is configured for its type (${candidates.map((p) => p.poolType).join(\", \")}). ` +\n \"Set `contracts.quoter` (CL) / `contracts.binQuoter` (Bin), or supply `overrides.quoteSwap`. \" +\n \"This adapter will not estimate a price it cannot verify.\",\n );\n }\n\n const results = await Promise.all(\n quotable.map(async (pool) => {\n const quoter = (pool.poolType === \"CL\" ? contracts.quoter : contracts.binQuoter) as Address;\n try {\n const { result } = await this.#client.simulateContract({\n address: quoter,\n abi: quoterAbiFor(pool.poolType),\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n poolKey: pool.key,\n zeroForOne: isAddressEqual(pool.key.currency0, request.tokenIn.address),\n exactAmount: request.amountIn,\n hookData: \"0x\",\n },\n ],\n });\n const [amountOut, gasEstimate] = result as readonly [bigint, bigint];\n return { pool, amountOut, gasEstimate, error: null as Error | null };\n } catch (error) {\n return { pool, amountOut: 0n, gasEstimate: 0n, error: error instanceof Error ? error : new Error(String(error)) };\n }\n }),\n );\n const answered = results.filter((r) => r.error === null);\n if (answered.length === 0) {\n const first = results[0]?.error;\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n `every direct pool for this pair failed to quote${first === null || first === undefined ? \"\" : `: ${first.message}`}`,\n );\n }\n const best = answered.reduce((a, b) => (b.amountOut > a.amountOut ? b : a));\n const pool = best.pool;\n\n let lpFeePips = pool.lpFeePips;\n let lpFeeUnknown = false;\n if (isDynamicLPFee(pool.lpFeePips)) {\n const guardFee = await this.#launchGuardFee(pool);\n if (guardFee === null) {\n lpFeePips = 0;\n lpFeeUnknown = true;\n } else {\n lpFeePips = guardFee;\n }\n }\n\n /* The output the same input would fetch at the pool's CURRENT price, net of\n the known LP fee, so the breakdown can isolate price impact from the fee.\n With a hook-set fee the adapter cannot separate the two and reports no\n spot rather than an impact that silently includes the fee. */\n const spotAmountOut = lpFeeUnknown ? null : await this.#spotAmountOut(pool, request.tokenIn.address, request.amountIn, lpFeePips);\n\n return {\n route: [\n {\n poolId: pool.id,\n poolType: pool.poolType,\n tokenIn: request.tokenIn,\n tokenOut: request.tokenOut,\n lpFeePips,\n hooks: pool.hooks,\n },\n ],\n amountIn: request.amountIn,\n grossAmountOut: best.amountOut,\n spotAmountOut,\n lpFeeAmount: (request.amountIn * BigInt(lpFeePips)) / 1_000_000n,\n lpFeePips,\n ...(lpFeeUnknown ? { lpFeeUnknown } : {}),\n estimatedGas: best.gasEstimate,\n source: \"live\",\n };\n }\n\n /**\n * `currentFee(poolId)` when the pool's hook is one of the configured launch\n * guards; `null` when the hook is not a guard (the fee is then genuinely\n * unreadable in advance). A guard that REVERTS `currentFee` — an unclaimed\n * pool id — is also `null`. Anything else (transport failure, an unknown\n * `CLOCK_MODE`) is thrown: an unreachable RPC is an error state, never a\n * quote annotated \"dynamic\".\n */\n async #launchGuardFee(pool: PoolInfo): Promise<number | null> {\n const guard = this.#guardFor(pool);\n if (guard === null) return null;\n const abi =\n guard.poolType === \"CL\" ? launchGuardAbiFor(await this.#launchClock(guard.hook, \"CL\")) : BIN_LAUNCH_GUARD_HOOK_ABI;\n try {\n const fee = await this.#client.readContract({ address: guard.hook, abi, functionName: \"currentFee\", args: [pool.id] });\n return Number(fee);\n } catch (error) {\n if (error instanceof BaseError && error.walk((x: unknown) => x instanceof ExecutionRevertedError) !== null) {\n return null;\n }\n throw error;\n }\n }\n\n /** The configured launch guard this pool names, if any, with the pool type it serves. */\n #guardFor(pool: PoolInfo): { readonly hook: Address; readonly poolType: PoolType } | null {\n const { launchGuardHook, binLaunchGuardHook } = this.chain.contracts;\n if (pool.poolType === \"CL\" && launchGuardHook !== undefined && isAddressEqual(pool.hooks, launchGuardHook)) {\n return { hook: launchGuardHook, poolType: \"CL\" };\n }\n if (pool.poolType === \"BIN\" && binLaunchGuardHook !== undefined && isAddressEqual(pool.hooks, binLaunchGuardHook)) {\n return { hook: binLaunchGuardHook, poolType: \"BIN\" };\n }\n return null;\n }\n\n /** `amountIn` priced at the pool's spot from `getSlot0`, less `lpFeePips`; `null` when the read fails. */\n async #spotAmountOut(pool: PoolInfo, tokenIn: Address, amountIn: bigint, lpFeePips: number): Promise<bigint | null> {\n const zeroForOne = isAddressEqual(pool.key.currency0, tokenIn);\n const afterFee = (amountIn * BigInt(1_000_000 - lpFeePips)) / 1_000_000n;\n try {\n if (pool.poolType === \"CL\") {\n const [sqrtPriceX96] = await this.#client.readContract({ address: pool.key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n if (sqrtPriceX96 === 0n) return null;\n const p2 = sqrtPriceX96 * sqrtPriceX96;\n return zeroForOne ? (afterFee * p2) / Q192 : (afterFee * Q192) / p2;\n }\n const [activeId] = await this.#client.readContract({ address: pool.key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n const { binStep } = readBinPoolKeyParameters(pool.key);\n const raw1per0 = binRawPriceFromId(Number(activeId), binStep);\n if (!Number.isFinite(raw1per0) || raw1per0 <= 0) return null;\n /* 1e18-scaled fixed point keeps the bigint arithmetic exact enough for an impact figure. */\n const SCALE = 10n ** 18n;\n const scaled = BigInt(Math.round(raw1per0 * 1e18));\n if (scaled === 0n) return null;\n return zeroForOne ? (afterFee * scaled) / SCALE : (afterFee * SCALE) / scaled;\n } catch {\n return null;\n }\n }\n\n async buildSwap(request: SwapExecutionRequest): Promise<WidgetTransactionRequest> {\n const router = requireContract(this.chain, \"universalRouter\", \"execute a swap\");\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"build a swap\");\n\n const hops = this.#resolveHops(request);\n const call = buildSwapCall({\n router,\n hops,\n amountIn: request.amountIn,\n minAmountOutGross: request.minAmountOutGross,\n minAmountOutNet: request.minAmountOutNet,\n expectedAmountOutGross: request.quote.grossAmountOut,\n integrator: request.integrator,\n recipient: request.recipient,\n sender: account,\n deadline: request.deadline,\n });\n\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Swap ${request.tokenIn.symbol} for ${request.tokenOut.symbol}`,\n ...(call.integratorFee\n ? {\n integratorFee: {\n referrer: call.integratorFee.referrer,\n feeBps: call.integratorFee.feeBps,\n currency: call.integratorFee.currency,\n expectedAmount: call.integratorFee.expectedAmount,\n },\n }\n : {}),\n source: \"live\",\n };\n }\n\n #resolveHops(request: SwapExecutionRequest): readonly SwapHop[] {\n const override = this.#overrides.findRoute;\n if (override !== undefined) {\n return override(request.tokenIn, request.tokenOut, this.#options.pools);\n }\n const hops: SwapHop[] = [];\n for (const step of request.quote.route) {\n const pool = this.#options.pools.find((candidate) => candidate.id === step.poolId);\n if (pool === undefined) {\n throw new UnsupportedOperationError(\n \"buildSwap\",\n `the quote routes through pool ${step.poolId}, which is not in the configured pool list`,\n );\n }\n hops.push({\n poolKey: pool.key,\n poolType: pool.poolType,\n currencyIn: step.tokenIn.address,\n currencyOut: step.tokenOut.address,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n }\n return hops;\n }\n\n /**\n * Turns desired amounts into the liquidity the pool will mint and the\n * amounts it will pull, from live state and the pool's own formulas\n * (`core/clMath.ts`; `adapters/binDistribution.ts`). The amounts reported\n * are what the position manager settles: an add rounds towards the pool.\n */\n async quoteAddLiquidity(request: AddLiquidityQuoteRequest): Promise<AddLiquidityQuote> {\n const override = this.#overrides.quoteAddLiquidity;\n if (override !== undefined) return override(request);\n const { pool, range } = request;\n if (range.type === \"CL\") {\n if (pool.poolType !== \"CL\") {\n throw new UnsupportedOperationError(\"quoteAddLiquidity\", \"tick range given for a bin pool\");\n }\n const spacing = tickSpacingOf(pool);\n if (range.tickLower % spacing !== 0 || range.tickUpper % spacing !== 0) {\n throw new RangeError(\n `[@latchprotocol/widgets] ticks must be multiples of the pool's spacing ${spacing}: [${range.tickLower}, ${range.tickUpper}]`,\n );\n }\n const state = await this.getPoolState(pool);\n const sqrtPriceX96 = state.sqrtPriceX96 as bigint;\n const liquidity = getLiquidityForAmounts(\n sqrtPriceX96,\n getSqrtRatioAtTick(range.tickLower),\n getSqrtRatioAtTick(range.tickUpper),\n request.amount0Desired,\n request.amount1Desired,\n );\n if (liquidity === 0n) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n \"these amounts mint no liquidity in this range: at the pool's price the range needs the other token, or the amounts are too small\",\n );\n }\n const amounts = amountsForLiquidity(sqrtPriceX96, range.tickLower, range.tickUpper, liquidity, true);\n const inRange = (state.currentTick as number) >= range.tickLower && (state.currentTick as number) < range.tickUpper;\n const poolLiquidity = state.liquidity ?? 0n;\n const shareBps = inRange ? Number((liquidity * 10_000n) / (poolLiquidity + liquidity)) : null;\n return { pool, range, amount0: amounts.amount0, amount1: amounts.amount1, liquidity, shareBps, source: \"live\" };\n }\n if (pool.poolType !== \"BIN\") {\n throw new UnsupportedOperationError(\"quoteAddLiquidity\", \"bin range given for a CL pool\");\n }\n const state = await this.getPoolState(pool);\n const activeId = state.activeId as number;\n if (Math.abs(activeId - range.activeIdDesired) > range.idSlippage) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n `the active bin is ${activeId}, more than ${range.idSlippage} bins from the ${range.activeIdDesired} the range was built around; rebuild the range`,\n );\n }\n const distribution = buildUniformBinDistribution(range.binIdLower, range.binIdUpper, range.activeIdDesired);\n const takesX = distribution.some((share) => share.distributionX > 0n);\n const takesY = distribution.some((share) => share.distributionY > 0n);\n const amount0 = takesX ? request.amount0Desired : 0n;\n const amount1 = takesY ? request.amount1Desired : 0n;\n if (amount0 + amount1 === 0n) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n \"nothing to deposit: the chosen bins take only the token whose amount is zero\",\n );\n }\n /* Bin shares are minted per bin from the deposit's value in that bin; the\n total is not a single figure the way CL liquidity is. Reported as the\n sum of what the distribution places, in currency1 units at each bin's\n price, which is what `BinPool.mint` credits. */\n const binStep = binStepOf(pool);\n let liquidity = 0n;\n for (const share of distribution) {\n const x = (amount0 * share.distributionX) / 10n ** 18n;\n const y = (amount1 * share.distributionY) / 10n ** 18n;\n const price = binRawPriceFromId(share.binId, binStep);\n liquidity += BigInt(Math.floor(Number(x) * price)) + y;\n }\n return { pool, range, amount0, amount1, liquidity, shareBps: null, binDistribution: distribution, source: \"live\" };\n }\n\n async buildAddLiquidity(\n request: AddLiquidityExecutionRequest,\n ): Promise<WidgetTransactionRequest> {\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"add liquidity\");\n const { quote } = request;\n const nativeValue = this.#nativeValueFor(quote.pool, request.amount0Max, request.amount1Max);\n\n if (quote.range.type === \"CL\") {\n const positionManager = requireContract(\n this.chain,\n \"clPositionManager\",\n \"mint a concentrated-liquidity position\",\n );\n const call = buildCLMintCall({\n positionManager,\n poolKey: quote.pool.key,\n tickLower: quote.range.tickLower,\n tickUpper: quote.range.tickUpper,\n liquidity: quote.liquidity,\n amount0Max: request.amount0Max,\n amount1Max: request.amount1Max,\n owner: request.recipient,\n deadline: request.deadline,\n value: nativeValue,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Add liquidity to ${quote.pool.token0.symbol}/${quote.pool.token1.symbol}`,\n source: \"live\",\n };\n }\n\n const positionManager = requireContract(\n this.chain,\n \"binPositionManager\",\n \"add liquidity to a bin pool\",\n );\n const distribution = quote.binDistribution;\n if (distribution === undefined || distribution.length === 0) {\n throw new UnsupportedOperationError(\n \"buildAddLiquidity\",\n \"a bin mint needs a per-bin distribution; the quote did not supply one\",\n );\n }\n const call = buildBinAddCall({\n positionManager,\n poolKey: quote.pool.key,\n amount0: quote.amount0,\n amount1: quote.amount1,\n amount0Max: request.amount0Max,\n amount1Max: request.amount1Max,\n activeIdDesired: quote.range.activeIdDesired,\n idSlippage: quote.range.idSlippage,\n deltaIds: distribution.map((share) => share.deltaId),\n distributionX: distribution.map((share) => share.distributionX),\n distributionY: distribution.map((share) => share.distributionY),\n to: request.recipient,\n deadline: request.deadline,\n value: nativeValue,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Add liquidity to ${quote.pool.token0.symbol}/${quote.pool.token1.symbol}`,\n source: \"live\",\n };\n }\n\n #nativeValueFor(pool: PoolInfo, amount0Max: bigint, amount1Max: bigint): bigint {\n if (isAddressEqual(pool.token0.address, NATIVE)) return amount0Max;\n if (isAddressEqual(pool.token1.address, NATIVE)) return amount1Max;\n return 0n;\n }\n\n /**\n * A holder's positions, reconstructed from position-manager logs and\n * confirmed against live state. Needs `positionsFromBlock`.\n *\n * CL: `Transfer(to = owner)` candidates, each confirmed by `ownerOf`, then\n * `positions(tokenId)` for the key, ticks and liquidity; amounts and fees\n * from the pool's slot0, tick info and fee-growth globals, exactly as the\n * pool would credit them. Bin: `TransferBatch(to = owner)` candidates, each\n * confirmed by `balanceOf`, grouped by pool; amounts from each bin's\n * reserves and share supply. A position on a pool not in the configured\n * list still appears, with its tokens read off their contracts.\n */\n async listPositions(owner: Address, pool?: PoolInfo): Promise<readonly PositionInfo[]> {\n const override = this.#overrides.listPositions;\n if (override !== undefined) return override(owner, pool);\n const fromBlock = this.#options.positionsFromBlock;\n if (fromBlock === undefined) {\n throw new UnsupportedOperationError(\n \"listPositions\",\n \"position enumeration scans the position managers' transfer logs and needs \" +\n \"`positionsFromBlock` (the block they were deployed at) in the adapter options.\",\n );\n }\n const wanted = pool?.poolType;\n const [cl, bin] = await Promise.all([\n wanted === \"BIN\" ? Promise.resolve([]) : this.#listCLPositions(owner, fromBlock, pool),\n wanted === \"CL\" ? Promise.resolve([]) : this.#listBinPositions(owner, fromBlock, pool),\n ]);\n return [...cl, ...bin];\n }\n\n async #listCLPositions(owner: Address, fromBlock: bigint, only?: PoolInfo): Promise<readonly PositionInfo[]> {\n const positionManager = this.chain.contracts.clPositionManager;\n if (positionManager === undefined) return [];\n const logs = await this.#client.getLogs({\n address: positionManager,\n event: CL_POSM_VIEWS_ABI[2],\n args: { to: owner },\n fromBlock,\n toBlock: \"latest\",\n });\n const candidates = [...new Set(logs.map((log) => log.args.id as bigint))];\n const out: PositionInfo[] = [];\n for (const tokenId of candidates) {\n let holder: Address;\n try {\n holder = await this.#client.readContract({ address: positionManager, abi: CL_POSM_VIEWS_ABI, functionName: \"ownerOf\", args: [tokenId] });\n } catch {\n continue; // burned\n }\n if (!isAddressEqual(holder, owner)) continue;\n const [key, tickLower, tickUpper, liquidity, feeGrowthInside0Last, feeGrowthInside1Last] = await this.#client.readContract({\n address: positionManager,\n abi: CL_POSM_VIEWS_ABI,\n functionName: \"positions\",\n args: [tokenId],\n });\n const poolInfo = await this.#poolInfoFor(key, \"CL\", only);\n if (poolInfo === null) continue;\n const [[sqrtPriceX96, currentTick], [feeGrowthGlobal0, feeGrowthGlobal1], lower, upper] = await Promise.all([\n this.#client.readContract({ address: key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [poolInfo.id] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getFeeGrowthGlobals\", args: [poolInfo.id] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getPoolTickInfo\", args: [poolInfo.id, tickLower] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getPoolTickInfo\", args: [poolInfo.id, tickUpper] }),\n ]);\n const amounts = amountsForLiquidity(sqrtPriceX96, tickLower, tickUpper, liquidity, false);\n const fees = uncollectedFees({\n liquidity,\n tickLower,\n tickUpper,\n currentTick,\n feeGrowthGlobal0X128: feeGrowthGlobal0,\n feeGrowthGlobal1X128: feeGrowthGlobal1,\n lower,\n upper,\n feeGrowthInside0LastX128: feeGrowthInside0Last,\n feeGrowthInside1LastX128: feeGrowthInside1Last,\n });\n out.push({\n id: `cl:${tokenId}`,\n tokenId,\n pool: poolInfo,\n range: { type: \"CL\", tickLower, tickUpper },\n liquidity,\n amount0: amounts.amount0,\n amount1: amounts.amount1,\n feesOwed0: fees.fees0,\n feesOwed1: fees.fees1,\n inRange: currentTick >= tickLower && currentTick < tickUpper,\n source: \"live\",\n });\n }\n return out;\n }\n\n async #listBinPositions(owner: Address, fromBlock: bigint, only?: PoolInfo): Promise<readonly PositionInfo[]> {\n const positionManager = this.chain.contracts.binPositionManager;\n if (positionManager === undefined) return [];\n const logs = await this.#client.getLogs({\n address: positionManager,\n event: BIN_POSM_VIEWS_ABI[2],\n args: { to: owner },\n fromBlock,\n toBlock: \"latest\",\n });\n const candidates = [...new Set(logs.flatMap((log) => (log.args.ids ?? []) as readonly bigint[]))];\n /* Group the held bins by pool. */\n const byPool = new Map<string, { key: PoolKey; bins: { binId: number; shares: bigint }[] }>();\n for (const tokenId of candidates) {\n const shares = await this.#client.readContract({ address: positionManager, abi: BIN_POSM_VIEWS_ABI, functionName: \"balanceOf\", args: [owner, tokenId] });\n if (shares === 0n) continue;\n const [key, binId] = await this.#client.readContract({ address: positionManager, abi: BIN_POSM_VIEWS_ABI, functionName: \"positions\", args: [tokenId] });\n const id = poolKeyToId(key);\n const entry = byPool.get(id) ?? { key, bins: [] };\n entry.bins.push({ binId, shares });\n byPool.set(id, entry);\n }\n const out: PositionInfo[] = [];\n for (const [poolId, { key, bins }] of byPool) {\n const poolInfo = await this.#poolInfoFor(key, \"BIN\", only);\n if (poolInfo === null) continue;\n const [activeId] = await this.#client.readContract({ address: key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [poolId as PoolId] });\n let amount0 = 0n;\n let amount1 = 0n;\n let liquidity = 0n;\n const sortedBins = [...bins].sort((a, b) => a.binId - b.binId);\n for (const bin of sortedBins) {\n const [reserveX, reserveY, , totalShares] = await this.#client.readContract({\n address: key.poolManager,\n abi: BIN_POOL_VIEWS_ABI,\n functionName: \"getBin\",\n args: [poolId as PoolId, bin.binId],\n });\n const amounts = binShareAmounts({ shares: bin.shares, totalShares, reserveX, reserveY });\n amount0 += amounts.amount0;\n amount1 += amounts.amount1;\n liquidity += bin.shares;\n }\n const first = sortedBins[0] as { binId: number };\n const last = sortedBins[sortedBins.length - 1] as { binId: number };\n out.push({\n id: `bin:${poolId}`,\n pool: poolInfo,\n range: { type: \"BIN\", activeIdDesired: activeId, binIdLower: first.binId, binIdUpper: last.binId, idSlippage: 0 },\n liquidity,\n amount0,\n amount1,\n /* Bin fees compound into the bins' reserves; they are inside amount0/amount1, never a separate figure. */\n feesOwed0: 0n,\n feesOwed1: 0n,\n binAmounts: sortedBins.map((bin) => ({ binId: bin.binId, amount: bin.shares })),\n inRange: sortedBins.some((bin) => bin.binId === activeId),\n source: \"live\",\n });\n }\n return out;\n }\n\n /**\n * The `PoolInfo` for a position's key: the configured one when the pool is\n * listed, else one built from the key with both tokens read off their\n * contracts. `null` when `only` names a different pool.\n */\n async #poolInfoFor(key: PoolKey, poolType: PoolType, only?: PoolInfo): Promise<PoolInfo | null> {\n const id = poolKeyToId(key);\n if (only !== undefined) return only.id.toLowerCase() === id.toLowerCase() ? only : null;\n const listed = this.#options.pools.find((candidate) => candidate.id.toLowerCase() === id.toLowerCase());\n if (listed !== undefined) return listed;\n const [token0, token1] = await Promise.all([this.getToken(key.currency0), this.getToken(key.currency1)]);\n if (token0 === null || token1 === null) return null;\n const granularity =\n poolType === \"CL\" ? { tickSpacing: readCLPoolKeyParameters(key).tickSpacing } : { binStep: readBinPoolKeyParameters(key).binStep };\n return { id, key, poolType, token0, token1, lpFeePips: key.fee, hooks: key.hooks, ...granularity };\n }\n\n /**\n * What withdrawing `percentBps` of a position returns as PRINCIPAL, rounded\n * down as the pool rounds a burn. A CL decrease also pays out the position's\n * uncollected fees (`feesOwed0/1` on the position); they are not in these\n * figures because the position manager's minimum-out check is on the\n * principal alone, and a floor that counted fees could revert an honest\n * withdrawal.\n */\n async quoteRemoveLiquidity(position: PositionInfo, percentBps: number): Promise<RemoveLiquidityQuote> {\n const override = this.#overrides.quoteRemoveLiquidity;\n if (override !== undefined) return override(position, percentBps);\n if (!Number.isInteger(percentBps) || percentBps <= 0 || percentBps > 10_000) {\n throw new RangeError(`[@latchprotocol/widgets] percentBps must be an integer in (0, 10000]: ${percentBps}`);\n }\n const { pool } = position;\n if (position.range.type === \"CL\") {\n const state = await this.getPoolState(pool);\n const liquidity = (position.liquidity * BigInt(percentBps)) / 10_000n;\n const amounts = amountsForLiquidity(state.sqrtPriceX96 as bigint, position.range.tickLower, position.range.tickUpper, liquidity, false);\n return { position, percentBps, amount0: amounts.amount0, amount1: amounts.amount1, source: \"live\" };\n }\n const held = position.binAmounts ?? [];\n let amount0 = 0n;\n let amount1 = 0n;\n for (const bin of held) {\n const [reserveX, reserveY, , totalShares] = await this.#client.readContract({\n address: pool.key.poolManager,\n abi: BIN_POOL_VIEWS_ABI,\n functionName: \"getBin\",\n args: [pool.id, bin.binId],\n });\n const amounts = binShareAmounts({ shares: (bin.amount * BigInt(percentBps)) / 10_000n, totalShares, reserveX, reserveY });\n amount0 += amounts.amount0;\n amount1 += amounts.amount1;\n }\n return { position, percentBps, amount0, amount1, source: \"live\" };\n }\n\n async buildRemoveLiquidity(\n request: RemoveLiquidityExecutionRequest,\n ): Promise<WidgetTransactionRequest> {\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"remove liquidity\");\n const { position } = request;\n\n if (position.range.type === \"CL\") {\n const positionManager = requireContract(\n this.chain,\n \"clPositionManager\",\n \"decrease a concentrated-liquidity position\",\n );\n if (position.tokenId === undefined) {\n throw new UnsupportedOperationError(\n \"buildRemoveLiquidity\",\n \"a CL position must carry its ERC-721 tokenId\",\n );\n }\n const liquidity = (position.liquidity * BigInt(request.percentBps)) / 10_000n;\n const call = buildCLDecreaseCall({\n positionManager,\n poolKey: position.pool.key,\n tokenId: position.tokenId,\n liquidity,\n amount0Min: request.amount0Min,\n amount1Min: request.amount1Min,\n recipient: request.recipient,\n owner: account,\n deadline: request.deadline,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Remove ${request.percentBps / 100}% of position #${position.tokenId}`,\n source: \"live\",\n };\n }\n\n const positionManager = requireContract(\n this.chain,\n \"binPositionManager\",\n \"remove liquidity from a bin pool\",\n );\n const binAmounts = position.binAmounts;\n if (binAmounts === undefined || binAmounts.length === 0) {\n throw new UnsupportedOperationError(\n \"buildRemoveLiquidity\",\n \"a bin burn needs the per-bin share amounts held by the position\",\n );\n }\n const call = buildBinRemoveCall({\n positionManager,\n poolKey: position.pool.key,\n amount0Min: request.amount0Min,\n amount1Min: request.amount1Min,\n ids: binAmounts.map((entry) => entry.binId),\n amounts: binAmounts.map(\n (entry) => (entry.amount * BigInt(request.percentBps)) / 10_000n,\n ),\n from: account,\n recipient: request.recipient,\n deadline: request.deadline,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Remove ${request.percentBps / 100}% of a bin position`,\n source: \"live\",\n };\n }\n\n /**\n * Requires at least one launch guard. A chain with neither is \"no launchpad\n * here\", signalled the way every missing contract is: `ChainConfigError`\n * naming `launchGuardHook`, which `isLaunchpadNotConfigured` recognises.\n */\n #requireAnyGuard(usedFor: string): void {\n const { launchGuardHook, binLaunchGuardHook } = this.chain.contracts;\n if (launchGuardHook === undefined && binLaunchGuardHook === undefined) {\n requireContract(this.chain, \"launchGuardHook\", usedFor);\n }\n }\n\n /**\n * Every configured pool whose key names one of the chain's launch guards:\n * CL pools naming `launchGuardHook`, Bin pools naming `binLaunchGuardHook`.\n *\n * There is no on-chain enumeration of launches any more than there is of\n * pools, so the candidate set is the pool list the host supplied. Throws\n * `ChainConfigError` when no guard address is configured, which is how a\n * caller distinguishes \"no launchpad on this chain\" from \"no launches yet\".\n */\n async listLaunches(): Promise<readonly LaunchInfo[]> {\n this.#requireAnyGuard(\"read a launch schedule\");\n const candidates = this.#options.pools.filter((pool) => this.#guardFor(pool) !== null);\n const launches = await Promise.all(candidates.map((pool) => this.#readLaunch(pool)));\n return launches.filter((launch): launch is LaunchInfo => launch !== null);\n }\n\n async getLaunch(poolId: PoolId): Promise<LaunchInfo | null> {\n this.#requireAnyGuard(\"read a launch schedule\");\n const pool = this.#options.pools.find((candidate) => candidate.id === poolId);\n if (pool === undefined) {\n throw new UnsupportedOperationError(\n \"getLaunch\",\n `pool ${poolId} is not in the configured pool list. The singleton has no pool ` +\n \"enumeration, so the widget can only read pools the host declared.\",\n );\n }\n if (this.#guardFor(pool) === null) return null;\n return this.#readLaunch(pool);\n }\n\n /**\n * The pools a `LaunchpadKitV2` launch opened for `token`, read from the kit's\n * `legsOf(token)` and then from the guards, in leg order.\n *\n * Every leg's pool must be in the host's pool list — the kit knows the ids,\n * not the keys, and a pool the host has not declared cannot be quoted or\n * swapped through anyway. A missing one is an error naming the id, not a\n * shorter list.\n */\n async getLaunchesForToken(token: Address): Promise<readonly LaunchInfo[]> {\n const kit = requireContract(this.chain, \"launchpadKitV2\", \"look a launch up by its token\");\n const poolIds = await this.#client.readContract({\n address: kit,\n abi: LAUNCHPAD_KIT_V2_ABI,\n functionName: \"legsOf\",\n args: [token],\n });\n if (poolIds.length === 0) return [];\n const missing = poolIds.filter((id) => this.#options.pools.every((pool) => pool.id !== id));\n if (missing.length > 0) {\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `the kit lists ${poolIds.length} pool(s) for ${token} but ${missing.length} of them ` +\n `(${missing.join(\", \")}) are not in the configured pool list. Declare them (the pool ` +\n \"manager's Initialize log carries the key) so the widget can read and route through them.\",\n );\n }\n const unguarded = poolIds.filter((id) => {\n const pool = this.#options.pools.find((candidate) => candidate.id === id) as PoolInfo;\n return this.#guardFor(pool) === null;\n });\n if (unguarded.length > 0) {\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `${unguarded.length} of the kit's pools for ${token} (${unguarded.join(\", \")}) name a launch guard ` +\n \"this chain config does not declare. Set `contracts.launchGuardHook` (CL) and \" +\n \"`contracts.binLaunchGuardHook` (Bin) to the kit's guards; a launch cannot be shown with a leg missing.\",\n );\n }\n const launches = await Promise.all(\n poolIds.map(async (id) => {\n const pool = this.#options.pools.find((candidate) => candidate.id === id) as PoolInfo;\n const launch = await this.#readLaunch(pool);\n if (launch === null) {\n // The kit only records legs it configured itself, so an unclaimed guard record here\n // means the guard and the kit disagree - say so rather than drop the leg.\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `the kit lists pool ${id} for ${token} but its guard has no launch record for it`,\n );\n }\n return launch;\n }),\n );\n return launches;\n }\n\n /**\n * Which generation a launch hook is, by configuration first, then the SDK\n * address book, then the hook's own `CLOCK_MODE()` (a revert means the\n * block-numbered build). A transport failure throws; it is never a revert.\n */\n async #launchClock(hook: Address, poolType: PoolType = \"CL\"): Promise<DurationClock> {\n if (poolType === \"CL\") {\n const configured = this.chain.contracts.launchGuardHookClock;\n if (configured !== undefined) return configured;\n }\n const deployment = getDeployment(this.chain.chainId);\n if (poolType === \"CL\" && deployment?.launchGuardHook && isAddressEqual(deployment.launchGuardHook, hook)) {\n const clock = deployment.durationClocks.launchGuardHook;\n if (clock !== null) return clock;\n }\n const v2 = deployment?.launchpadV2;\n if (v2 !== undefined) {\n const known = poolType === \"CL\" ? v2.clLaunchGuardHook : v2.binLaunchGuardHook;\n if (known !== null && isAddressEqual(known, hook)) return \"timestamp\";\n }\n try {\n const { data } = await this.#client.call({ to: hook, data: CLOCK_MODE_CALLDATA });\n if (data === undefined || data === \"0x\") return \"contract-block\";\n const [mode] = decodeAbiParameters([{ type: \"string\" }], data);\n if (mode === TIMESTAMP_CLOCK_MODE) return \"timestamp\";\n throw new UnsupportedOperationError(\"getLaunch\", `hook ${hook} reports an unknown CLOCK_MODE \"${mode}\"`);\n } catch (error) {\n if (error instanceof BaseError && error.walk((x: unknown) => x instanceof ExecutionRevertedError) !== null) {\n return \"contract-block\";\n }\n throw error;\n }\n }\n\n async #readLaunch(pool: PoolInfo): Promise<LaunchInfo | null> {\n const bound = this.#guardFor(pool);\n if (bound === null) return null;\n const hook = bound.hook;\n const durationClock = await this.#launchClock(hook, bound.poolType);\n if (bound.poolType === \"BIN\" && durationClock !== \"timestamp\") {\n throw new UnsupportedOperationError(\n \"getLaunch\",\n `BinLaunchGuardHook ${hook} answers as a block-numbered build; no such build exists, so this is not a Bin launch guard.`,\n );\n }\n /* Both guards return the same `Launch` struct; the Bin ABI is the timestamp shape. */\n const abi = bound.poolType === \"CL\" ? launchGuardAbiFor(durationClock) : BIN_LAUNCH_GUARD_HOOK_ABI;\n const raw = await this.#client.readContract({\n address: hook,\n abi,\n functionName: \"getLaunch\",\n args: [pool.id],\n });\n const guard = decodeLaunchGuard(raw as unknown as RawLaunchGuard, durationClock);\n if (!isLaunchConfigured(guard)) return null;\n\n const [currentFeePips, clock] = await Promise.all([\n this.#client.readContract({\n address: hook,\n abi,\n functionName: \"currentFee\",\n args: [pool.id],\n }),\n /* \"Now\" on the HOOK's clock. The timestamp build compares with\n block.timestamp. The block-numbered build compares with the EVM's\n block.number, which on an Arbitrum chain (Robinhood, 4663) is\n Ethereum's block number while the RPC head is the L2 block; against\n the RPC head every unopened launch rendered as settled. */\n readContractClock(this.#client, this.chain.chainId),\n ]);\n const readAt = durationClock === \"timestamp\" ? clock.timestamp : clock.contractBlockNumber;\n\n const [launchToken, quoteToken] = guard.launchTokenIsCurrency0\n ? [pool.token0, pool.token1]\n : [pool.token1, pool.token0];\n\n return {\n poolId: pool.id,\n pool,\n hook,\n launchToken,\n quoteToken,\n guard,\n currentFeePips: Number(currentFeePips),\n readAt,\n source: \"live\",\n };\n }\n\n async sendTransaction(request: WidgetTransactionRequest): Promise<Hex> {\n const wallet = this.#options.wallet;\n if (wallet === undefined) throw new WalletNotConnectedError(\"send a transaction\");\n return wallet.sendTransaction({\n to: request.to,\n data: request.data,\n value: request.value,\n });\n }\n\n /**\n * The clock the next block will carry, as closely as the RPC can say: the\n * later of the PENDING block's timestamp (anvil and geth-style nodes compute\n * the next block's; an RPC without one refuses or echoes the latest) and the\n * latest block's. See `nextBlockClock` for why the pending read matters.\n */\n async getBlockTimestamp(): Promise<bigint> {\n const [pending, latest] = await Promise.allSettled([\n this.#client.getBlock({ blockTag: \"pending\" }),\n this.#client.getBlock({ blockTag: \"latest\" }),\n ]);\n const clock = nextBlockClock(\n pending.status === \"fulfilled\" ? pending.value.timestamp : null,\n latest.status === \"fulfilled\" ? latest.value.timestamp : null,\n );\n if (clock === null) throw latest.status === \"rejected\" ? latest.reason : new Error(\"no block timestamp could be read\");\n return clock;\n }\n\n async waitForTransaction(hash: Hex): Promise<TransactionOutcome> {\n const receipt = await this.#client.waitForTransactionReceipt({ hash });\n return {\n hash,\n status: receipt.status === \"success\" ? \"success\" : \"reverted\",\n blockNumber: receipt.blockNumber,\n source: \"live\",\n };\n }\n}\n\n/** Creates the live, viem-backed adapter. */\nexport function createViemAdapter(options: ViemAdapterOptions): ProtocolAdapter {\n return new ViemProtocolAdapter(options);\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Headless readers for the lock widgets: one pool's position locks or one\n * token's locks, read through the MIT SDK (`@latchprotocol/sdk/lock`), plus\n * the chain clock their countdowns run on.\n *\n * No provider is required: a lock badge is read-only and takes a viem\n * `PublicClient` directly, so a host can drop it beside any pool without the\n * swap stack. A `null` lock address (the chain has no address for it) leaves the\n * resource `idle`; the component says \"coming soon\" rather than reading.\n * The loaders themselves live in `../locks/fetch.ts`, React-free.\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { advanceChainNow, type LpLockerSource } from \"../locks/model.js\";\nimport {\n DEFAULT_NATIVE,\n fetchPoolLocks,\n fetchTokenLocks,\n poolLocksEnabled,\n type NativeCurrencyMeta,\n type PoolLocksData,\n type TokenLocksData,\n} from \"../locks/fetch.js\";\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\n\nexport { fetchPoolLocks, fetchTokenLocks, poolLocksEnabled, type LocksReadOptions, type NativeCurrencyMeta, type PoolLocksData, type TokenLocksData } from \"../locks/fetch.js\";\n\nexport interface UseLocksOptions {\n readonly native?: NativeCurrencyMeta;\n /** Re-read interval; default 60 s. 0 disables polling. */\n readonly refetchIntervalMs?: number;\n /** The protocol's LP lockers: their permanent liquidity is read and counted. */\n readonly lp?: LpLockerSource;\n}\n\n/** Every lock in one pool, as a React resource. See {@link fetchPoolLocks}. */\nexport function usePoolLocks(\n client: PublicClient,\n positionLock: Address | null,\n poolId: Hex,\n options: UseLocksOptions = {},\n): AsyncResource<PoolLocksData> {\n const native = options.native ?? DEFAULT_NATIVE;\n const lp = options.lp ?? {};\n return useAsyncResource(\n () => fetchPoolLocks(client, positionLock, poolId, { native, lp }),\n [client, positionLock, poolId, native.symbol, native.decimals, lp.lpLocker, lp.binLpLocker, lp.poolType, lp.lpLockerFromBlock, (lp.lpLockerTokenIds ?? []).join(\",\")],\n { enabled: poolLocksEnabled(positionLock, lp), refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n\n/** Every lock of one token, as a React resource. See {@link fetchTokenLocks}. */\nexport function useTokenLocks(\n client: PublicClient,\n tokenLock: Address | null,\n token: Address,\n options: UseLocksOptions = {},\n): AsyncResource<TokenLocksData> {\n const native = options.native ?? DEFAULT_NATIVE;\n const lp = options.lp ?? {};\n const hasLp = !!lp.lpLocker || !!lp.binLpLocker;\n return useAsyncResource(\n () => fetchTokenLocks(client, tokenLock, token, { native, lp }),\n [client, tokenLock, token, native.symbol, native.decimals, lp.lpLocker, lp.binLpLocker, lp.lpLockerFromBlock, (lp.lpLockerTokenIds ?? []).join(\",\")],\n { enabled: tokenLock !== null || hasLp, refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n\n/**\n * The chain's `block.timestamp` now: `chainNow` as read, advanced by the\n * local clock once a second. `null` until there is a read.\n */\nexport function useChainClock(chainNow: bigint | null, readAtMs: number | null): bigint | null {\n const [nowMs, setNowMs] = useState(() => Date.now());\n useEffect(() => {\n if (chainNow === null) return;\n const id = setInterval(() => setNowMs(Date.now()), 1000);\n return () => clearInterval(id);\n }, [chainNow]);\n if (chainNow === null || readAtMs === null) return null;\n return advanceChainNow(chainNow, readAtMs, nowMs);\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Token trust: the pure half of `TokenTrustPanel`.\n *\n * Turns the SDK's `readTokenTrust` result into labelled rows, each carrying\n * the words (from `@latchprotocol/sdk/trust`'s formatters, so every surface\n * says the same thing) and the contract each figure came from (name and\n * address, linkable; no view names or block numbers in user copy — owner rule\n * 2026-09-27). Nothing is added that was not read; nothing says \"safe\".\n */\n\nimport type { Address, Hex } from \"viem\";\nimport {\n describeCreatorTax,\n describeLaunch,\n describeLiquidity,\n describeLpFee,\n describeProtocolFee,\n describeRegistry,\n describeTokenLocks,\n formatTrustSource,\n summarizeTokenTrust,\n type PoolTrust,\n type TokenTrust,\n type TokenTrustSummary,\n type TrustLine,\n type TrustSource,\n type TrustTone,\n} from \"@latchprotocol/sdk/trust\";\nimport { shareBarFromBps, tokenShareBar, type ShareBarView } from \"../locks/model.js\";\n\nexport interface TrustRowView {\n readonly key: string;\n readonly label: string;\n readonly headline: string;\n readonly detail: string | null;\n readonly tone: TrustTone;\n /** One line per source: \"LatchTokenLock 0x12ab…cdef\". */\n readonly provenance: readonly string[];\n /** The same sources, for linking each contract to an explorer. */\n readonly sources: readonly TrustSource[];\n /** A locked-share bar for the rows that measure one (liquidity, token locks); `null` otherwise. */\n readonly share?: ShareBarView | null;\n}\n\nexport interface TrustPoolView {\n readonly poolId: Hex;\n readonly title: string;\n /** How the pool was found, in words. */\n readonly foundBy: string;\n readonly rows: readonly TrustRowView[];\n}\n\nexport interface TokenTrustView {\n readonly summary: TokenTrustSummary;\n readonly launch: TrustRowView;\n readonly tokenLocks: TrustRowView;\n readonly creatorTax: TrustRowView;\n readonly pools: readonly TrustPoolView[];\n /** Pools found but not described, one sentence each. */\n readonly failedPools: readonly string[];\n /** Which pools are listed, and that the list is not every pool of the token. */\n readonly discoveryNote: string;\n readonly readAtNote: string;\n}\n\ntype Sectionish = { readonly status: string; readonly sources?: readonly TrustSource[]; readonly source?: TrustSource | null };\n\nfunction sourcesOf(s: Sectionish): readonly TrustSource[] {\n if (s.status === \"read\") return s.sources ?? [];\n if (s.status === \"error\" && s.source) return [s.source];\n return [];\n}\n\nfunction row(key: string, label: string, line: TrustLine, sources: readonly TrustSource[], t: Pick<TokenTrust, \"readAt\">): TrustRowView {\n return { key, label, headline: line.headline, detail: line.detail, tone: line.tone, provenance: sources.map((s) => formatTrustSource(s, t.readAt).split(\" · \")[0] ?? s.contract), sources };\n}\n\nconst ORIGIN_WORDS: Record<PoolTrust[\"origins\"][number], string> = {\n \"launch-leg\": \"a Kit v2 launch leg\",\n \"lp-locker\": \"an LP-locker lock\",\n \"position-lock\": \"a LatchPositionLock time lock\",\n given: \"this page's pool list\",\n};\n\nfunction joinWords(words: readonly string[]): string {\n if (words.length <= 1) return words[0] ?? \"\";\n return `${words.slice(0, -1).join(\", \")} and ${words[words.length - 1]}`;\n}\n\n/** Symbols the host resolved, by lowercase address; the short address otherwise. */\nexport type SymbolBook = Readonly<Record<string, string>>;\n\nconst labelOf = (book: SymbolBook, a: Address): string => book[a.toLowerCase()] ?? `${a.slice(0, 6)}…${a.slice(-4)}`;\n\nfunction poolView(p: PoolTrust, t: TokenTrust, book: SymbolBook): TrustPoolView {\n const rows: TrustRowView[] = [\n {\n ...row(\"liquidity\", \"Liquidity locks\", describeLiquidity(p.liquidity, p.kind), sourcesOf(p.liquidity), t),\n share:\n p.liquidity.status !== \"read\" || !p.liquidity.measurable\n ? null\n : p.kind === \"Bin\"\n ? shareBarFromBps([{ key: \"permanent\", label: \"Locked permanently (LP locker)\", bps: p.liquidity.lockedActiveBps }], \"of the active bin\")\n : shareBarFromBps(\n [\n { key: \"permanent\", label: \"Locked permanently (LP locker)\", bps: p.liquidity.permanentActiveBps },\n { key: \"time\", label: \"Time-locked until a date\", bps: p.liquidity.timeLockedActiveBps },\n ],\n \"of active liquidity\",\n ),\n },\n row(\"lp-fee\", \"LP fee\", describeLpFee(p.lpFee), p.lpFee.kind === \"error\" ? [] : p.lpFee.source === null ? [] : [p.lpFee.source], t),\n row(\"protocol-fee\", \"Protocol fee\", describeProtocolFee(p.protocolFee), sourcesOf(p.protocolFee), t),\n ];\n if (p.tax.status !== \"not-a-launch-pool\") rows.push(row(\"tax\", \"Creator tax\", describeCreatorTax(p.tax, t.readAt.chainNow), sourcesOf(p.tax), t));\n rows.push(row(\"registry\", \"Hook in LatchRegistry\", describeRegistry(p.registry), p.registry.status === \"no-hook\" ? [] : sourcesOf(p.registry), t));\n return {\n poolId: p.poolId,\n title: `${t.symbol} / ${labelOf(book, p.pairedWith)} · ${p.kind} pool`,\n foundBy: `Found through ${joinWords(p.origins.map((o) => ORIGIN_WORDS[o]))}.`,\n rows,\n };\n}\n\n/** The token-level creator tax: from the launch, then its legs. */\nfunction creatorTaxRow(t: TokenTrust): TrustRowView {\n const launch = t.launch;\n if (launch.status === \"not-configured\") {\n return row(\"tax\", \"Creator tax\", { headline: \"Coming soon\", detail: \"Latch launches are coming soon on this chain, so there is no creator tax to read.\", tone: \"missing\" }, [], t);\n }\n if (launch.status === \"error\") {\n return row(\"tax\", \"Creator tax\", { headline: \"Could not be read\", detail: `The launch read failed: ${launch.message}.`, tone: \"error\" }, sourcesOf(launch), t);\n }\n if (launch.launch === null) {\n return row(\"tax\", \"Creator tax\", { headline: \"Not a Latch launch\", detail: \"This token was not launched on Latch, so no Latch creator tax applies to it.\", tone: \"neutral\" }, sourcesOf(launch), t);\n }\n const legs = t.pools.filter((p) => p.origins.includes(\"launch-leg\") && p.tax.status !== \"not-a-launch-pool\");\n if (legs.length === 0) {\n return row(\"tax\", \"Creator tax\", { headline: \"Could not be read\", detail: \"No launch pool of this token could be described, so its tax was not read.\", tone: \"error\" }, sourcesOf(launch), t);\n }\n const lines = legs.map((p) => describeCreatorTax(p.tax, t.readAt.chainNow));\n const sources = legs.flatMap((p) => sourcesOf(p.tax)).filter((s, i, a) => a.findIndex((x) => x.address.toLowerCase() === s.address.toLowerCase()) === i);\n const first = lines[0]!;\n if (lines.every((l) => l.headline === first.headline && l.detail === first.detail)) {\n return row(\"tax\", \"Creator tax\", legs.length === 1 ? first : { ...first, detail: `${first.detail ?? \"\"} Same on all ${legs.length} launch pools.`.trim() }, sources, t);\n }\n return row(\"tax\", \"Creator tax\", { headline: \"Differs by pool\", detail: \"Each launch pool below carries its own terms.\", tone: lines.some((l) => l.tone === \"caution\") ? \"caution\" : \"neutral\" }, sources, t);\n}\n\n/** Pure: every row of the trust panel from one read. */\nexport function tokenTrustView(t: TokenTrust, book: SymbolBook = {}): TokenTrustView {\n const searched = t.discovery.searched.map((o) => ORIGIN_WORDS[o]);\n const discoveryNote =\n `Pools listed are those found through ${searched.length === 0 ? \"no source yet: these reads are coming soon on this chain\" : joinWords(searched)}` +\n `${t.discovery.truncated ? \", and only the first of them were read\" : \"\"}${t.discovery.positionLocksTruncated ? \" (newest position locks only)\" : \"\"}. ` +\n \"A pool of this token that no Latch launch or lock knows about is not listed.\";\n return {\n summary: summarizeTokenTrust(t),\n launch: row(\"launch\", \"Latch launch\", describeLaunch(t.launch, t.readAt), sourcesOf(t.launch), t),\n tokenLocks: {\n ...row(\"token-locks\", \"Token locks & vesting\", describeTokenLocks(t.tokenLocks, t.symbol, t.decimals), sourcesOf(t.tokenLocks), t),\n share: t.tokenLocks.status === \"read\" && t.tokenLocks.lockCount > 0 ? tokenShareBar(t.tokenLocks) : null,\n },\n creatorTax: creatorTaxRow(t),\n pools: t.pools.map((p) => poolView(p, t, book)),\n failedPools: t.failedPools.map((f) => `${f.kind} pool ${f.poolId.slice(0, 10)}… could not be described: ${f.message}.`),\n discoveryNote,\n readAtNote: \"Live from the chain. Token units, never priced. A registry listing is what the registry records, not an audit.\",\n };\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Headless reader for `TokenTrustPanel`: the SDK's `readTokenTrust` for one\n * token, plus the symbols of the currencies its pools pair it with, as a React\n * resource. No provider and no wallet: a viem `PublicClient` is enough.\n */\n\nimport { zeroAddress, type Address, type Hex, type PublicClient } from \"viem\";\nimport { readTokenMeta } from \"@latchprotocol/sdk\";\nimport { readTokenTrust, type PoolKind, type TokenTrust, type TrustContracts } from \"@latchprotocol/sdk/trust\";\n\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\nimport type { SymbolBook } from \"../trust/model.js\";\n\n/** What to read. `contracts: null` means the host gave no addresses for this chain: nothing is read, and surfaces say \"coming soon\". */\nexport interface TokenTrustTarget {\n readonly token: Address;\n readonly contracts: TrustContracts | null;\n /** Pools the host knows the token trades in, beyond the ones Latch's launches and locks reveal. */\n readonly pools?: readonly { readonly poolId: Hex; readonly kind: PoolKind }[];\n /** CL LP-locker position ids from a log scan the host already made. */\n readonly lpLockerTokenIds?: readonly bigint[];\n readonly native?: { readonly symbol: string; readonly decimals: number };\n}\n\nexport interface TokenTrustData {\n readonly trust: TokenTrust;\n readonly symbols: SymbolBook;\n}\n\n/** One read of a token's trust facts, with the paired currencies' symbols. */\nexport async function fetchTokenTrust(client: PublicClient, target: TokenTrustTarget & { readonly contracts: TrustContracts }): Promise<TokenTrustData> {\n const trust = await readTokenTrust(client, {\n token: target.token,\n contracts: target.contracts,\n ...(target.pools !== undefined ? { pools: target.pools } : {}),\n ...(target.lpLockerTokenIds !== undefined ? { lpLockerTokenIds: target.lpLockerTokenIds } : {}),\n ...(target.native !== undefined ? { native: target.native } : {}),\n });\n const paired = [...new Set(trust.pools.map((p) => p.pairedWith.toLowerCase()))] as Address[];\n const nativeSymbol = target.native?.symbol ?? \"ETH\";\n const metas = await Promise.all(paired.map((a) => (a === zeroAddress ? Promise.resolve({ symbol: nativeSymbol }) : readTokenMeta(client, a).catch(() => null))));\n const symbols: Record<string, string> = {};\n paired.forEach((a, i) => {\n const m = metas[i];\n if (m) symbols[a] = m.symbol;\n });\n return { trust, symbols };\n}\n\nexport interface UseTokenTrustOptions {\n /** Re-read interval in ms; default 60,000. 0 disables polling. */\n readonly refetchIntervalMs?: number;\n}\n\n/** {@link fetchTokenTrust} as a resource: `idle` when `contracts` is `null`. */\nexport function useTokenTrust(client: PublicClient, target: TokenTrustTarget, options: UseTokenTrustOptions = {}): AsyncResource<TokenTrustData> {\n const c = target.contracts;\n const contractsKey = c === null ? \"none\" : Object.entries(c).map(([k, v]) => `${k}:${String(v ?? \"\")}`).sort().join(\"|\");\n return useAsyncResource(\n () => fetchTokenTrust(client, { ...target, contracts: c as TrustContracts }),\n [\n client,\n target.token.toLowerCase(),\n contractsKey,\n (target.pools ?? []).map((p) => `${p.kind}${p.poolId}`).join(\",\"),\n (target.lpLockerTokenIds ?? []).join(\",\"),\n target.native?.symbol,\n target.native?.decimals,\n ],\n { enabled: c !== null, refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The locker widget: its pure half.\n *\n * Input parsing (exact decimals, UTC dates), the live fee in words, the\n * transaction plan for each action (approval only when the chain says it is\n * missing, and only for exactly what the lock takes), and which actions a\n * connected wallet may take on each of its locks. The contracts enforce all\n * of this; the widget checks first so a wallet is never asked to sign a call\n * that would revert.\n */\n\nimport { parseUnits, type Address } from \"viem\";\nimport type { FeeGateTerms, PositionLockRecord, TokenLockView, VestingSchedule } from \"@latchprotocol/sdk/lock\";\n\n/* ------------------------------------------------------------------ inputs --- */\n\n/** An exact decimal amount in base units, or `null` when it is not one (never rounded). */\nexport function parseLockAmount(text: string, decimals: number): bigint | null {\n const t = text.trim().replace(/_/g, \"\");\n if (!/^\\d+(\\.\\d+)?$/.test(t)) return null;\n const frac = t.split(\".\")[1] ?? \"\";\n if (frac.length > decimals) return null;\n try {\n return parseUnits(t, decimals);\n } catch {\n return null;\n }\n}\n\n/** A `datetime-local` value (\"2027-01-31T12:00\"), read as UTC, to unix seconds; `null` when malformed. */\nexport function parseUtcInput(text: string): bigint | null {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})$/.exec(text.trim());\n if (m === null) return null;\n const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]));\n return Number.isFinite(ms) ? BigInt(Math.floor(ms / 1000)) : null;\n}\n\n/** Unix seconds to a `datetime-local` value in UTC. */\nexport function toUtcInput(seconds: bigint): string {\n return new Date(Number(seconds) * 1000).toISOString().slice(0, 16);\n}\n\n/** A whole number of days as seconds, or `null`. */\nexport function parseDays(text: string): bigint | null {\n const t = text.trim();\n if (!/^\\d+$/.test(t)) return null;\n return BigInt(t) * 86_400n;\n}\n\nexport type VestingMode = \"timelock\" | \"vesting\";\n\n/**\n * The schedule for a token lock: a time lock releases everything at `unlockAt`;\n * vesting accrues linearly from `start` over `durationDays`, nothing claimable\n * before `start + cliffDays`.\n */\nexport function lockSchedule(\n mode: VestingMode,\n input: { readonly unlockAt: bigint | null; readonly start: bigint | null; readonly cliffDays: bigint | null; readonly durationDays: bigint | null },\n): VestingSchedule | null {\n if (mode === \"timelock\") return input.unlockAt === null ? null : { start: input.unlockAt, cliff: input.unlockAt, end: input.unlockAt };\n if (input.start === null || input.cliffDays === null || input.durationDays === null) return null;\n return { start: input.start, cliff: input.start + input.cliffDays, end: input.start + input.durationDays };\n}\n\n/* --------------------------------------------------------------------- fee --- */\n\nfunction units(v: bigint, decimals: number): string {\n if (v === 0n) return \"0\";\n const base = 10n ** BigInt(decimals);\n const whole = v / base;\n const frac = (v % base).toString().padStart(decimals, \"0\").replace(/0+$/, \"\");\n return frac === \"\" ? whole.toLocaleString(\"en-US\") : `${whole.toLocaleString(\"en-US\")}.${frac}`;\n}\n\nexport interface LockerFeeView {\n /** \"0.075 ETH per lock\". */\n readonly fee: string;\n /** What the lock transaction sends for the fee (the higher of the fee and an announced increase). */\n readonly sends: string;\n /** An announced increase, in words, or `null`. */\n readonly pending: string | null;\n readonly note: string;\n}\n\n/** The live fee in words. Native units only, never a dollar figure. */\nexport function lockerFeeView(terms: Pick<FeeGateTerms, \"feeWei\" | \"pendingFee\" | \"recipient\">, native: { readonly symbol: string; readonly decimals: number }): LockerFeeView {\n const fee = `${units(terms.feeWei, native.decimals)} ${native.symbol} per lock`;\n const p = terms.pendingFee;\n const rises = p !== null && p.feeWei > terms.feeWei;\n const sendsWei = rises ? p.feeWei : terms.feeWei;\n const pending =\n p === null\n ? null\n : `${p.feeWei > terms.feeWei ? \"An increase\" : \"A change\"} to ${units(p.feeWei, native.decimals)} ${native.symbol} applies from ${new Date(Number(p.effectiveAt) * 1000).toISOString().replace(\"T\", \" \").slice(0, 16)} UTC.`;\n return {\n fee,\n sends: `${units(sendsWei, native.decimals)} ${native.symbol}`,\n pending,\n note: `Charged by the lock contract itself and paid only to its fee recipient ${terms.recipient.slice(0, 6)}…${terms.recipient.slice(-4)}.${rises ? \" The transaction sends the announced higher fee in case it applies before it mines; the contract refunds any surplus in the same call.\" : \"\"}`,\n };\n}\n\n/* -------------------------------------------------------------------- plan --- */\n\nexport interface PlanStep {\n readonly key: \"approve\" | \"lock\";\n readonly label: string;\n}\n\n/** Lock a position: approve this ONE NFT to the lock (when not already approved), then lock. */\nexport function planPositionLock(args: { readonly tokenId: bigint; readonly approved: boolean; readonly unlockAt: bigint }): PlanStep[] {\n const steps: PlanStep[] = [];\n if (!args.approved) steps.push({ key: \"approve\", label: `Approve LatchPositionLock to move position #${args.tokenId} (this NFT only)` });\n steps.push({ key: \"lock\", label: `Lock position #${args.tokenId} until ${new Date(Number(args.unlockAt) * 1000).toISOString().replace(\"T\", \" \").slice(0, 16)} UTC, paying the fee` });\n return steps;\n}\n\n/** Lock tokens: an exact `approve(lock, amount)` when the allowance is short (never for native), then lock. */\nexport function planTokenLock(args: { readonly native: boolean; readonly allowance: bigint; readonly amount: bigint; readonly amountText: string; readonly symbol: string }): PlanStep[] {\n const steps: PlanStep[] = [];\n if (!args.native && args.allowance < args.amount) steps.push({ key: \"approve\", label: `Approve LatchTokenLock for exactly ${args.amountText} ${args.symbol}` });\n steps.push({ key: \"lock\", label: `Lock ${args.amountText} ${args.symbol}, paying the fee${args.native ? \" (the amount is sent with it)\" : \"\"}` });\n return steps;\n}\n\n/* ------------------------------------------------------------ my locks --- */\n\nexport type PositionLockAction = \"collect\" | \"extend\" | \"withdraw\" | \"accept\";\nexport type TokenLockAction = \"claim\" | \"accept\";\n\nconst same = (a: string | null | undefined, b: string | null | undefined): boolean => a !== null && a !== undefined && b !== null && b !== undefined && a.toLowerCase() === b.toLowerCase();\n\n/** What `account` may do with one position lock, as the contract allows it. */\nexport function positionLockActions(r: Pick<PositionLockRecord, \"owner\" | \"pendingOwner\" | \"withdrawn\" | \"unlockAt\">, account: Address | null, now: bigint): PositionLockAction[] {\n if (r.withdrawn) return [];\n const out: PositionLockAction[] = [\"collect\"]; // permissionless; fees always go to the lock owner\n if (same(r.owner, account)) {\n out.push(\"extend\");\n if (now >= r.unlockAt) out.push(\"withdraw\");\n }\n if (same(r.pendingOwner, account)) out.push(\"accept\");\n return out;\n}\n\n/** What `account` may do with one token lock. */\nexport function tokenLockActions(l: Pick<TokenLockView, \"beneficiary\" | \"pendingBeneficiary\" | \"claimable\">, account: Address | null): TokenLockAction[] {\n const out: TokenLockAction[] = [];\n if (same(l.beneficiary, account) && l.claimable > 0n) out.push(\"claim\");\n if (same(l.pendingBeneficiary, account)) out.push(\"accept\");\n return out;\n}\n\nexport const POSITION_ACTION_LABEL: Record<PositionLockAction, string> = {\n collect: \"Collect fees\",\n extend: \"Extend\",\n withdraw: \"Withdraw\",\n accept: \"Accept lock\",\n};\n\nexport const TOKEN_ACTION_LABEL: Record<TokenLockAction, string> = {\n claim: \"Claim vested\",\n accept: \"Accept lock\",\n};\n","// SPDX-License-Identifier: MIT\n/**\n * Headless controllers for `LockerWidget`: the wallet, the live fees, the\n * connected wallet's locks, and a step runner that simulates every call with\n * its exact bytes before the wallet sees it and checks every receipt.\n *\n * The wallet is the same minimal surface `createViemAdapter` takes\n * (`WidgetWallet`: `getAccount` + `sendTransaction`), or, when none is passed,\n * the mounted `WidgetProvider`'s adapter. Reads, simulations and receipts go\n * through the viem `PublicClient` the host passes, on the lock contracts'\n * chain.\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { Address, Hex, PublicClient } from \"viem\";\nimport {\n readBeneficiaryLocks,\n readChainNow,\n readFeeGate,\n readPositionLocksOf,\n type FeeGateTerms,\n type PositionLockRecord,\n type TokenLockView,\n type UtilityCall,\n} from \"@latchprotocol/sdk/lock\";\n\nimport type { WidgetWallet } from \"../adapters/viem.js\";\nimport { useOptionalWidgetContext } from \"../context/WidgetProvider.js\";\nimport { describeError } from \"../core/errors.js\";\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\n\n/** The two lock contracts, from the host's address book. `null` = the chain has no address for it; surfaces render \"coming soon\". */\nexport interface LockerContracts {\n readonly positionLock: Address | null;\n readonly tokenLock: Address | null;\n}\n\n/** The wallet a locker signs with: the prop, else the provider's adapter, else none. */\nexport function useLockerWallet(wallet: WidgetWallet | undefined): WidgetWallet | null {\n const ctx = useOptionalWidgetContext();\n return useMemo(() => {\n if (wallet !== undefined) return wallet;\n const adapter = ctx?.adapter;\n if (adapter === undefined || adapter.isMock) return null;\n return {\n getAccount: () => adapter.getAccount(),\n sendTransaction: (req) => adapter.sendTransaction({ ...req, summary: \"Latch lock\", source: \"live\" }),\n };\n }, [wallet, ctx?.adapter]);\n}\n\n/** The connected account, re-read every few seconds so a wallet switch shows. */\nexport function useLockerAccount(wallet: WidgetWallet | null): AsyncResource<Address | null> {\n return useAsyncResource(() => (wallet === null ? Promise.resolve(null) : wallet.getAccount()), [wallet], { refetchIntervalMs: 4_000 });\n}\n\nexport interface LockerFees {\n readonly position: FeeGateTerms | null;\n readonly token: FeeGateTerms | null;\n}\n\n/** Each lock contract's fee terms, read live (`feeWei`, `pendingFee`, cap, recipient). */\nexport function useLockerFees(client: PublicClient, contracts: LockerContracts): AsyncResource<LockerFees> {\n return useAsyncResource(\n async () => {\n const [position, token] = await Promise.all([\n contracts.positionLock === null ? Promise.resolve(null) : readFeeGate(client, contracts.positionLock),\n contracts.tokenLock === null ? Promise.resolve(null) : readFeeGate(client, contracts.tokenLock),\n ]);\n return { position, token };\n },\n [client, contracts.positionLock, contracts.tokenLock],\n { enabled: contracts.positionLock !== null || contracts.tokenLock !== null, refetchIntervalMs: 60_000 },\n );\n}\n\nexport interface MyLocks {\n readonly positions: readonly PositionLockRecord[];\n readonly tokens: readonly TokenLockView[];\n /** The chain's `block.timestamp` when read. */\n readonly now: bigint;\n}\n\n/** Locks `account` owns or has been offered, on both contracts. */\nexport function useMyLocks(client: PublicClient, contracts: LockerContracts, account: Address | null): AsyncResource<MyLocks> {\n return useAsyncResource(\n async () => {\n const a = account as Address;\n const [now, positions, tokens] = await Promise.all([\n readChainNow(client),\n contracts.positionLock === null ? Promise.resolve([]) : readPositionLocksOf(client, contracts.positionLock, a),\n contracts.tokenLock === null ? Promise.resolve({ locks: [] as TokenLockView[] }) : readBeneficiaryLocks(client, contracts.tokenLock, a),\n ]);\n return { positions, tokens: tokens.locks, now };\n },\n [client, contracts.positionLock, contracts.tokenLock, account],\n { enabled: account !== null && (contracts.positionLock !== null || contracts.tokenLock !== null), refetchIntervalMs: 60_000 },\n );\n}\n\n/** Thrown when a mined transaction reverted: the receipt, not the hash, is the proof. */\nexport class TransactionRevertedError extends Error {\n readonly hash: Hex;\n constructor(hash: Hex) {\n super(`The transaction ${hash.slice(0, 10)}… was mined and reverted.`);\n this.name = \"TransactionRevertedError\";\n this.hash = hash;\n }\n}\n\n/**\n * One call: simulate with the exact bytes and value from `account`, send\n * through the wallet, wait for the receipt, and throw unless it succeeded.\n */\nexport async function simulateSendConfirm(client: PublicClient, wallet: WidgetWallet, account: Address, call: UtilityCall): Promise<Hex> {\n await client.call({ account, to: call.to, data: call.data, value: call.value });\n const hash = await wallet.sendTransaction({ to: call.to, data: call.data, value: call.value });\n const receipt = await client.waitForTransactionReceipt({ hash });\n if (receipt.status !== \"success\") throw new TransactionRevertedError(hash);\n return hash;\n}\n\nexport interface RunnerStep {\n readonly label: string;\n /** Built when the step starts, so it reads the chain as it is after the previous step. */\n readonly build: () => Promise<UtilityCall>;\n}\n\nexport type RunnerState =\n | { readonly k: \"idle\" }\n | { readonly k: \"running\"; readonly labels: readonly string[]; readonly active: number; readonly phase: \"simulating\" | \"signing\" | \"confirming\" }\n | { readonly k: \"done\"; readonly labels: readonly string[]; readonly hashes: readonly Hex[] }\n | { readonly k: \"failed\"; readonly labels: readonly string[]; readonly active: number; readonly message: string };\n\n/** Runs steps in order; the first failure stops the run and is described in one sentence. */\nexport function useLockerRunner(client: PublicClient, wallet: WidgetWallet | null, account: Address | null, onDone?: () => void): { state: RunnerState; run(steps: readonly RunnerStep[]): Promise<void>; reset(): void } {\n const [state, setState] = useState<RunnerState>({ k: \"idle\" });\n const busy = useRef(false);\n const run = useCallback(\n async (steps: readonly RunnerStep[]) => {\n if (busy.current) return;\n const labels = steps.map((s) => s.label);\n if (wallet === null || account === null) {\n setState({ k: \"failed\", labels, active: 0, message: \"Connect a wallet first.\" });\n return;\n }\n busy.current = true;\n const hashes: Hex[] = [];\n let i = 0;\n try {\n for (; i < steps.length; i++) {\n setState({ k: \"running\", labels, active: i, phase: \"simulating\" });\n const call = await steps[i]!.build();\n await client.call({ account, to: call.to, data: call.data, value: call.value });\n setState({ k: \"running\", labels, active: i, phase: \"signing\" });\n const hash = await wallet.sendTransaction({ to: call.to, data: call.data, value: call.value });\n setState({ k: \"running\", labels, active: i, phase: \"confirming\" });\n const receipt = await client.waitForTransactionReceipt({ hash });\n if (receipt.status !== \"success\") throw new TransactionRevertedError(hash);\n hashes.push(hash);\n }\n setState({ k: \"done\", labels, hashes });\n onDone?.();\n } catch (error) {\n setState({ k: \"failed\", labels, active: i, message: error instanceof TransactionRevertedError ? error.message : describeError(error, \"transaction\") });\n } finally {\n busy.current = false;\n }\n },\n [client, wallet, account, onDone],\n );\n const reset = useCallback(() => setState({ k: \"idle\" }), []);\n return { state, run, reset };\n}\n"],"names":["buildUniformBinDistribution","binIdLower","binIdUpper","activeId","ids","id","xBins","yBins","lastX","lastY","shares","xAssigned","yAssigned","rawX","BIN_DISTRIBUTION_SCALE","rawY","distributionX","distributionY","NoSaleAdapterError","hasSaleAdapter","adapter","CL_MINT_PARAMS","POOL_KEY_COMPONENTS","CL_MODIFY_PARAMS","CURRENCY_PAIR","CURRENCY_PAIR_AND_ADDRESS","CURRENCY_AND_ADDRESS","sweepNativeStep","ACTIONS","encodeAbiParameters","NATIVE_CURRENCY","MSG_SENDER","BIN_ADD_LIQUIDITY_PARAMS","BIN_REMOVE_LIQUIDITY_PARAMS","poolKeyStruct","key","buildCLMintCall","args","assertTickRange","p","plan","encodeFunctionData","POSITION_MANAGER_ABI","buildCLDecreaseCall","recipient","buildBinAddCall","binCount","buildBinRemoveCall","tickLower","tickUpper","CL_SLOT0_ABI","BIN_SLOT0_ABI","Q192","CL_POOL_VIEWS_ABI","BIN_POOL_VIEWS_ABI","POOL_KEY_OUTPUT","CL_POSM_VIEWS_ABI","BIN_POSM_VIEWS_ABI","NATIVE","ViemProtocolAdapter","#options","options","#client","#overrides","wallet","address","known","token","isAddressEqual","symbol","name","decimals","ERC20_ABI","owner","pool","override","sqrtPriceX96","tick","liquidity","UnsupportedOperationError","amount","spender","permit2","requireContract","router","requirements","erc20Allowance","permit2Amount","expiration","PERMIT2_ABI","nowSeconds","expired","requirement","MAX_UINT256","MAX_UINT160","MAX_UINT48","request","contracts","candidates","quotable","results","quoter","result","quoterAbiFor","amountOut","gasEstimate","error","answered","r","first","best","a","b","lpFeePips","lpFeeUnknown","isDynamicLPFee","guardFee","#launchGuardFee","spotAmountOut","#spotAmountOut","guard","#guardFor","abi","launchGuardAbiFor","#launchClock","BIN_LAUNCH_GUARD_HOOK_ABI","fee","BaseError","x","ExecutionRevertedError","launchGuardHook","binLaunchGuardHook","tokenIn","amountIn","zeroForOne","afterFee","p2","binStep","readBinPoolKeyParameters","raw1per0","binRawPriceFromId","SCALE","scaled","account","WalletNotConnectedError","hops","#resolveHops","call","buildSwapCall","step","candidate","range","spacing","tickSpacingOf","state","getLiquidityForAmounts","getSqrtRatioAtTick","amounts","amountsForLiquidity","inRange","poolLiquidity","shareBps","distribution","takesX","share","takesY","amount0","amount1","binStepOf","y","price","quote","nativeValue","#nativeValueFor","positionManager","amount0Max","amount1Max","fromBlock","wanted","cl","bin","#listCLPositions","#listBinPositions","only","logs","log","out","tokenId","holder","feeGrowthInside0Last","feeGrowthInside1Last","poolInfo","#poolInfoFor","currentTick","feeGrowthGlobal0","feeGrowthGlobal1","lower","upper","fees","uncollectedFees","byPool","binId","poolKeyToId","entry","poolId","bins","sortedBins","reserveX","reserveY","totalShares","binShareAmounts","last","poolType","listed","token0","token1","granularity","readCLPoolKeyParameters","position","percentBps","held","binAmounts","#requireAnyGuard","usedFor","#readLaunch","launch","kit","poolIds","LAUNCHPAD_KIT_V2_ABI","missing","unguarded","hook","configured","deployment","getDeployment","clock","v2","data","CLOCK_MODE_CALLDATA","mode","decodeAbiParameters","TIMESTAMP_CLOCK_MODE","bound","durationClock","raw","decodeLaunchGuard","isLaunchConfigured","currentFeePips","readContractClock","readAt","launchToken","quoteToken","pending","latest","nextBlockClock","hash","receipt","createViemAdapter","usePoolLocks","client","positionLock","native","DEFAULT_NATIVE","lp","useAsyncResource","fetchPoolLocks","poolLocksEnabled","useTokenLocks","tokenLock","hasLp","fetchTokenLocks","useChainClock","chainNow","readAtMs","nowMs","setNowMs","useState","useEffect","advanceChainNow","sourcesOf","s","row","label","line","sources","t","formatTrustSource","ORIGIN_WORDS","joinWords","words","labelOf","book","poolView","rows","describeLiquidity","shareBarFromBps","describeLpFee","describeProtocolFee","describeCreatorTax","describeRegistry","o","creatorTaxRow","legs","lines","i","l","tokenTrustView","searched","discoveryNote","summarizeTokenTrust","describeLaunch","describeTokenLocks","tokenShareBar","f","fetchTokenTrust","target","trust","readTokenTrust","paired","nativeSymbol","metas","zeroAddress","readTokenMeta","symbols","m","useTokenTrust","c","contractsKey","k","v","parseLockAmount","text","parseUnits","parseUtcInput","ms","toUtcInput","seconds","parseDays","lockSchedule","input","units","base","whole","frac","lockerFeeView","terms","rises","sendsWei","planPositionLock","steps","planTokenLock","same","positionLockActions","now","tokenLockActions","POSITION_ACTION_LABEL","TOKEN_ACTION_LABEL","useLockerWallet","ctx","useOptionalWidgetContext","useMemo","req","useLockerAccount","useLockerFees","readFeeGate","useMyLocks","positions","tokens","readChainNow","readPositionLocksOf","readBeneficiaryLocks","TransactionRevertedError","simulateSendConfirm","useLockerRunner","onDone","setState","busy","useRef","run","useCallback","labels","hashes","describeError","reset"],"mappings":";;;;;;AAqBO,SAASA,GACdC,GACAC,GACAC,GACqB;AACrB,MAAIF,IAAaC;AACf,UAAM,IAAI,WAAW,cAAcD,CAAU,uBAAuBC,CAAU,EAAE;AAElF,QAAME,IAAgB,CAAA;AACtB,WAASC,IAAKJ,GAAYI,KAAMH,GAAYG,KAAM,EAAG,CAAAD,EAAI,KAAKC,CAAE;AAEhE,QAAMC,IAAQF,EAAI,OAAO,CAACC,MAAOA,KAAMF,CAAQ,EAAE,QAC3CI,IAAQH,EAAI,OAAO,CAACC,MAAOA,KAAMF,CAAQ,EAAE,QAE3CK,IAAQN,GACRO,IAAQ,KAAK,IAAIN,GAAUD,CAAU,GAErCQ,IAA8B,CAAA;AACpC,MAAIC,IAAY,IACZC,IAAY;AAChB,aAAWP,KAAMD,GAAK;AACpB,UAAMS,IAAOR,KAAMF,KAAYG,IAAQ,IAAIQ,IAAyB,OAAOR,CAAK,IAAI,IAC9ES,IAAOV,KAAMF,KAAYI,IAAQ,IAAIO,IAAyB,OAAOP,CAAK,IAAI,IAC9ES,IAAgBX,MAAOG,KAASK,IAAO,KAAKC,IAAyBH,IAAYE,GACjFI,IAAgBZ,MAAOI,KAASM,IAAO,KAAKD,IAAyBF,IAAYG;AACvF,IAAAJ,KAAaK,GACbJ,KAAaK,GACbP,EAAO,KAAK,EAAE,OAAOL,GAAI,SAASA,IAAKF,GAAU,eAAAa,GAAe,eAAAC,GAAe;AAAA,EACjF;AACA,SAAOP;AACT;AC6FO,MAAMQ,WAA2B,MAAM;AAAA,EAC5C,cAAc;AACZ;AAAA,MACE;AAAA,IAAA,GAIF,KAAK,OAAO;AAAA,EACd;AACF;AAGO,SAASC,GACdC,GACgD;AAChD,SAAOA,EAAQ,SAAS;AAC1B;ACnIA,MAA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,gBAAgB,EAAE,IAAImF,EAAK,IAAI,MAAMA,EAAK,MAAM,OAAOA,EAAK,OAAO;AAG7F,cAFAoO,EAAS,EAAE,GAAG,WAAW,QAAAK,GAAQ,QAAQ5E,GAAG,OAAO,cAAc,IACjD,MAAM7C,EAAO,0BAA0B,EAAE,MAAAJ,GAAM,GACnD,WAAW,UAAW,OAAM,IAAIoH,EAAyBpH,CAAI;AACzE,UAAA8H,EAAO,KAAK9H,CAAI;AAAA,QAClB;AACA,QAAAwH,EAAS,EAAE,GAAG,QAAQ,QAAAK,GAAQ,QAAAC,GAAQ,GACtCP,IAAA;AAAA,MACF,SAAS5Q,GAAO;AACd,QAAA6Q,EAAS,EAAE,GAAG,UAAU,QAAAK,GAAQ,QAAQ5E,GAAG,SAAStM,aAAiByQ,IAA2BzQ,EAAM,UAAUoR,GAAcpR,GAAO,aAAa,GAAG;AAAA,MACvJ,UAAA;AACE,QAAA8Q,EAAK,UAAU;AAAA,MACjB;AAAA,IACF;AAAA,IACA,CAACrH,GAAQnM,GAAQ+E,GAASuO,CAAM;AAAA,EAAA,GAE5BS,IAAQJ,GAAY,MAAMJ,EAAS,EAAE,GAAG,OAAA,CAAQ,GAAG,EAAE;AAC3D,SAAO,EAAE,OAAA7N,GAAO,KAAAgO,GAAK,OAAAK,EAAA;AACvB;"}
1
+ {"version":3,"file":"useLocker-m3WH-bQm.js","sources":["../../src/adapters/binDistribution.ts","../../src/adapters/sale.ts","../../src/callpath/liquidity.ts","../../src/adapters/viem.ts","../../src/hooks/useLocks.ts","../../src/trust/model.ts","../../src/hooks/useTokenTrust.ts","../../src/locker/model.ts","../../src/hooks/useLocker.ts"],"sourcesContent":["// SPDX-License-Identifier: MIT\n/**\n * How a bin mint spreads its two amounts across a span of bins.\n *\n * `BinPool.mint` takes, per bin, the share of `amount0` (X) and of `amount1`\n * (Y) it receives, each scaled to 1e18. Bins strictly below the active id can\n * only hold Y, bins strictly above it only X, and the active bin holds both.\n * A share that sums to more than 1e18 on either side reverts; one that sums to\n * less leaves part of the amount undeposited. The uniform spread here sums each\n * side to EXACTLY 1e18 by pushing the rounding dust into that side's last bin.\n *\n * The active bin's composition is the pool's, not the depositor's: a deposit\n * whose X:Y ratio differs from the active bin's reserves pays the pool's\n * composition fee on the difference. This helper does not fold that in; the\n * amounts a quote reports are what the position manager pulls.\n */\n\nimport type { BinLiquidityShare } from \"./protocol.js\";\nimport { BIN_DISTRIBUTION_SCALE } from \"../callpath/constants.js\";\n\n/** Spreads liquidity evenly across a bin span, as a bin mint requires. */\nexport function buildUniformBinDistribution(\n binIdLower: number,\n binIdUpper: number,\n activeId: number,\n): BinLiquidityShare[] {\n if (binIdLower > binIdUpper) {\n throw new RangeError(`binIdLower ${binIdLower} exceeds binIdUpper ${binIdUpper}`);\n }\n const ids: number[] = [];\n for (let id = binIdLower; id <= binIdUpper; id += 1) ids.push(id);\n\n const xBins = ids.filter((id) => id >= activeId).length;\n const yBins = ids.filter((id) => id <= activeId).length;\n // The last bin on each side takes the rounding dust so the side sums to 1e18.\n const lastX = binIdUpper;\n const lastY = Math.min(activeId, binIdUpper);\n\n const shares: BinLiquidityShare[] = [];\n let xAssigned = 0n;\n let yAssigned = 0n;\n for (const id of ids) {\n const rawX = id >= activeId && xBins > 0 ? BIN_DISTRIBUTION_SCALE / BigInt(xBins) : 0n;\n const rawY = id <= activeId && yBins > 0 ? BIN_DISTRIBUTION_SCALE / BigInt(yBins) : 0n;\n const distributionX = id === lastX && rawX > 0n ? BIN_DISTRIBUTION_SCALE - xAssigned : rawX;\n const distributionY = id === lastY && rawY > 0n ? BIN_DISTRIBUTION_SCALE - yAssigned : rawY;\n xAssigned += distributionX;\n yAssigned += distributionY;\n shares.push({ binId: id, deltaId: id - activeId, distributionX, distributionY });\n }\n return shares;\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Optional extension point: a third-party token sale.\n *\n * ## Nothing in Latch implements this, on purpose\n *\n * A Latch launch is a pool with `LaunchGuardHook` attached and a decaying LP\n * fee. Buying into one is an ordinary swap. There is no `buy`, no soft or hard\n * cap, no allocation, no claim, and no per-wallet limit anywhere in the\n * protocol — see {@link ../callpath/launch.js} for why a per-wallet limit is\n * not implementable at the hook layer at all.\n *\n * This package used to ship a `LAUNCHPAD_ABI` describing a sale contract with\n * all of those features. No deployed contract implemented it, so every byte of\n * calldata it produced was guaranteed to fail. It has been deleted.\n *\n * ## What replaces it\n *\n * The shape of an *answer*, not the shape of somebody's contract. If you run a\n * genuine sale contract, you implement {@link TokenSaleAdapter} against your own\n * ABI and hang it off `ProtocolAdapter.sale`. Your `buildBuy` returns a\n * {@link ../adapters/protocol.js | WidgetTransactionRequest} — the same\n * adapter-neutral `{to, data, value}` the rest of this package speaks — so this\n * package never has to guess at a function selector it cannot verify.\n *\n * That is the whole point of putting it here: an unverifiable ABI is a\n * liability wherever it lives, and the one place it is honest is behind an\n * interface the integrator fills in from a contract they actually deployed.\n *\n * Nothing in this package reads `ProtocolAdapter.sale`. The styled\n * `LaunchWidget` binds to `LaunchGuardHook` and to nothing else. Consuming\n * these types means building your own UI on top of them.\n */\n\nimport type { Address } from \"viem\";\nimport type { ResolvedIntegratorConfig } from \"../config/integrator.js\";\nimport type { DataSource, TokenInfo, WidgetTransactionRequest } from \"./protocol.js\";\n\n/** Lifecycle of a third-party token sale. */\nexport type TokenSaleStatus =\n | \"upcoming\"\n | \"live\"\n | \"paused\"\n | \"ended\"\n | \"sold-out\"\n | \"cancelled\";\n\n/** Shape of a sale's price curve, if it has one. */\nexport type TokenSalePriceCurve =\n | { readonly kind: \"fixed\"; readonly price: bigint }\n | { readonly kind: \"linear\"; readonly startPrice: bigint; readonly endPrice: bigint }\n | {\n readonly kind: \"exponential\";\n readonly startPrice: bigint;\n readonly endPrice: bigint;\n /** Curvature exponent, scaled to 1e18. */\n readonly exponent: bigint;\n };\n\n/**\n * A sale, as your adapter reports it.\n *\n * Every field is optional-by-nullability where a sale might not have the\n * concept. Return `null` rather than zero: a UI can say \"no cap\" from `null`,\n * but `0n` reads as \"cap reached\".\n */\nexport interface TokenSaleInfo {\n /** The sale contract. */\n readonly id: Address;\n readonly token: TokenInfo;\n /** Currency buyers pay in. */\n readonly paymentToken: TokenInfo;\n readonly status: TokenSaleStatus;\n readonly totalForSale: bigint;\n readonly sold: bigint;\n readonly raised: bigint;\n readonly softCap: bigint | null;\n readonly hardCap: bigint | null;\n /** Unix seconds. */\n readonly startTime: bigint;\n readonly endTime: bigint;\n /** Maximum a single wallet may spend, in the payment currency. */\n readonly perWalletCap: bigint | null;\n readonly minPurchase: bigint;\n readonly priceCurve: TokenSalePriceCurve | null;\n readonly source: DataSource;\n}\n\n/** One account's standing in a sale. */\nexport interface TokenSaleAccountState {\n readonly saleId: Address;\n readonly account: Address;\n readonly spent: bigint;\n readonly allocated: bigint;\n /** Remaining spend allowed under the per-wallet cap. `null` when uncapped. */\n readonly capRemaining: bigint | null;\n readonly eligible: boolean;\n readonly ineligibleReason: string | null;\n readonly source: DataSource;\n}\n\n/** Quote for a sale purchase. */\nexport interface TokenSaleQuote {\n readonly sale: TokenSaleInfo;\n readonly amountIn: bigint;\n readonly tokensOut: bigint;\n /** Effective price paid, in payment units per whole token. */\n readonly effectivePrice: bigint;\n readonly source: DataSource;\n}\n\n/** Request to build a sale purchase transaction. */\nexport interface TokenSaleBuyRequest {\n readonly quote: TokenSaleQuote;\n readonly minTokensOut: bigint;\n readonly recipient: Address;\n readonly deadline: bigint;\n /**\n * The validated integrator config from the provider.\n *\n * Whether a sale contract can pay a referrer at all is a property of that\n * contract. If yours cannot, ignore this and do not silently drop the fee\n * into a transfer the user does not see.\n */\n readonly integrator: ResolvedIntegratorConfig;\n}\n\n/**\n * The seam. Implement it against your own sale contract.\n *\n * Every method may throw; the headless layer surfaces the error rather than\n * substituting a default.\n */\nexport interface TokenSaleAdapter {\n /** Identifies the implementation in error messages, e.g. `\"acme-launchpad\"`. */\n readonly kind: string;\n listSales(): Promise<readonly TokenSaleInfo[]>;\n getSale(id: Address): Promise<TokenSaleInfo | null>;\n getSaleAccountState(id: Address, account: Address): Promise<TokenSaleAccountState>;\n quoteBuy(sale: TokenSaleInfo, amountIn: bigint): Promise<TokenSaleQuote>;\n buildBuy(request: TokenSaleBuyRequest): Promise<WidgetTransactionRequest>;\n}\n\n/** Thrown by a host that wires a sale UI without wiring a sale adapter. */\nexport class NoSaleAdapterError extends Error {\n constructor() {\n super(\n \"[@latchprotocol/widgets] no sale adapter is configured. Latch has no sale contract - \" +\n \"a launch is a pool with LaunchGuardHook attached, and buying into one is a swap. \" +\n \"Set ProtocolAdapter.sale only if you run your own sale contract.\",\n );\n this.name = \"NoSaleAdapterError\";\n }\n}\n\n/** Narrowing helper, so a host can branch without a cast. */\nexport function hasSaleAdapter(\n adapter: { readonly sale?: TokenSaleAdapter },\n): adapter is { readonly sale: TokenSaleAdapter } {\n return adapter.sale !== undefined;\n}\n","// SPDX-License-Identifier: MIT\r\n/**\r\n * Liquidity call-path construction for both pool types.\r\n *\r\n * Concentrated liquidity and the liquidity book differ in what a \"range\" is -\r\n * a tick pair versus a span of bins - and in the shape of their position\r\n * manager params. Everything above this file works with the single\r\n * {@link ../adapters/protocol.js | LiquidityRange} union; the divergence is\r\n * confined to the two encoders here.\r\n *\r\n * Both paths go through `PositionManager.modifyLiquidities(unlockData, deadline)`\r\n * with the same `abi.encode(actions, params)` transport the swap path uses.\r\n *\r\n * ## Why there is no integrator fee on this path\r\n *\r\n * `PAY_PORTION` and `TAKE_PORTION` split an output currency. Adding liquidity\r\n * has no output to split, and removing it returns the user's own principal -\r\n * skimming that is not a referral fee, it is a withdrawal charge. Integrator\r\n * revenue on liquidity, if it is ever added, belongs in a hook that earns from\r\n * the position, not in a router step that taxes the deposit. The `integrator`\r\n * config is still carried here so it can be recorded in analytics events.\r\n */\r\n\r\nimport { encodeAbiParameters, encodeFunctionData, type Address, type Hex } from \"viem\";\r\nimport { NATIVE_CURRENCY, type PoolKey } from \"@latchprotocol/sdk\";\r\nimport { ACTIONS, MSG_SENDER, POSITION_MANAGER_ABI } from \"./constants.js\";\r\nimport { plan } from \"./plan.js\";\r\nimport { POOL_KEY_COMPONENTS } from \"./swap.js\";\r\n\r\nconst CL_MINT_PARAMS = [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"tickLower\", type: \"int24\" },\r\n { name: \"tickUpper\", type: \"int24\" },\r\n { name: \"liquidity\", type: \"uint256\" },\r\n { name: \"amount0Max\", type: \"uint128\" },\r\n { name: \"amount1Max\", type: \"uint128\" },\r\n { name: \"owner\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n] as const;\r\n\r\nconst CL_MODIFY_PARAMS = [\r\n { name: \"tokenId\", type: \"uint256\" },\r\n { name: \"liquidity\", type: \"uint256\" },\r\n { name: \"amount0\", type: \"uint128\" },\r\n { name: \"amount1\", type: \"uint128\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n] as const;\r\n\r\nconst CURRENCY_PAIR = [\r\n { name: \"currency0\", type: \"address\" },\r\n { name: \"currency1\", type: \"address\" },\r\n] as const;\r\n\r\nconst CURRENCY_PAIR_AND_ADDRESS = [\r\n { name: \"currency0\", type: \"address\" },\r\n { name: \"currency1\", type: \"address\" },\r\n { name: \"recipient\", type: \"address\" },\r\n] as const;\r\n\r\nconst CURRENCY_AND_ADDRESS = [\r\n { name: \"currency\", type: \"address\" },\r\n { name: \"to\", type: \"address\" },\r\n] as const;\r\n\r\n/**\r\n * `SWEEP(native, MSG_SENDER)`, appended to a deposit that attaches native value.\r\n *\r\n * `SETTLE_PAIR` pays the vault exactly the native debt and leaves the rest of\r\n * `msg.value` - the slippage headroom between the amount pulled and\r\n * `amountMax` - sitting in the position manager, where anyone's next sweep\r\n * would take it. This returns it to the caller in the same transaction.\r\n */\r\nfunction sweepNativeStep(): readonly [number, Hex, string] {\r\n return [\r\n ACTIONS.SWEEP,\r\n encodeAbiParameters(CURRENCY_AND_ADDRESS, [NATIVE_CURRENCY, MSG_SENDER]),\r\n \"sweep unspent native value back to the caller\",\r\n ];\r\n}\r\n\r\nconst BIN_ADD_LIQUIDITY_PARAMS = [\r\n {\r\n name: \"params\",\r\n type: \"tuple\",\r\n components: [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"amount0\", type: \"uint128\" },\r\n { name: \"amount1\", type: \"uint128\" },\r\n { name: \"amount0Max\", type: \"uint128\" },\r\n { name: \"amount1Max\", type: \"uint128\" },\r\n { name: \"activeIdDesired\", type: \"uint256\" },\r\n { name: \"idSlippage\", type: \"uint256\" },\r\n { name: \"deltaIds\", type: \"int256[]\" },\r\n { name: \"distributionX\", type: \"uint256[]\" },\r\n { name: \"distributionY\", type: \"uint256[]\" },\r\n { name: \"minLiquidities\", type: \"uint256[]\" },\r\n { name: \"to\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n ],\r\n },\r\n] as const;\r\n\r\nconst BIN_REMOVE_LIQUIDITY_PARAMS = [\r\n {\r\n name: \"params\",\r\n type: \"tuple\",\r\n components: [\r\n { name: \"poolKey\", type: \"tuple\", components: POOL_KEY_COMPONENTS },\r\n { name: \"amount0Min\", type: \"uint128\" },\r\n { name: \"amount1Min\", type: \"uint128\" },\r\n { name: \"ids\", type: \"uint256[]\" },\r\n { name: \"amounts\", type: \"uint256[]\" },\r\n { name: \"from\", type: \"address\" },\r\n { name: \"hookData\", type: \"bytes\" },\r\n ],\r\n },\r\n] as const;\r\n\r\nfunction poolKeyStruct(key: PoolKey): {\r\n currency0: Address;\r\n currency1: Address;\r\n hooks: Address;\r\n poolManager: Address;\r\n fee: number;\r\n parameters: Hex;\r\n} {\r\n return {\r\n currency0: key.currency0,\r\n currency1: key.currency1,\r\n hooks: key.hooks,\r\n poolManager: key.poolManager,\r\n fee: key.fee,\r\n parameters: key.parameters,\r\n };\r\n}\r\n\r\n/** An encoded position-manager call. */\r\nexport interface EncodedLiquidityCall {\r\n readonly to: Address;\r\n readonly data: Hex;\r\n readonly value: bigint;\r\n readonly planTrace: string;\r\n}\r\n\r\n/** Arguments for minting a new concentrated-liquidity position. */\r\nexport interface BuildCLMintArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly tickLower: number;\r\n readonly tickUpper: number;\r\n readonly liquidity: bigint;\r\n readonly amount0Max: bigint;\r\n readonly amount1Max: bigint;\r\n readonly owner: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n /** Native value to attach, when one side of the pair is the native asset. */\r\n readonly value?: bigint;\r\n}\r\n\r\n/** Encodes `CL_MINT_POSITION` followed by `SETTLE_PAIR` (and `SWEEP` of the native side when value is attached). */\r\nexport function buildCLMintCall(args: BuildCLMintArgs): EncodedLiquidityCall {\r\n assertTickRange(args.tickLower, args.tickUpper);\r\n if (args.liquidity <= 0n) {\r\n throw new RangeError(`[@latchprotocol/widgets] liquidity must be positive: ${args.liquidity}`);\r\n }\r\n const p = plan()\r\n .add(\r\n ACTIONS.CL_MINT_POSITION,\r\n encodeAbiParameters(CL_MINT_PARAMS, [\r\n poolKeyStruct(args.poolKey),\r\n args.tickLower,\r\n args.tickUpper,\r\n args.liquidity,\r\n args.amount0Max,\r\n args.amount1Max,\r\n args.owner,\r\n args.hookData ?? \"0x\",\r\n ]),\r\n `mint CL position [${args.tickLower}, ${args.tickUpper}]`,\r\n )\r\n .add(\r\n ACTIONS.SETTLE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR, [args.poolKey.currency0, args.poolKey.currency1]),\r\n \"settle both currencies from the caller\",\r\n );\r\n if ((args.value ?? 0n) > 0n) p.add(...sweepNativeStep());\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: args.value ?? 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for decreasing or closing a concentrated-liquidity position. */\r\nexport interface BuildCLDecreaseArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly tokenId: bigint;\r\n readonly liquidity: bigint;\r\n readonly amount0Min: bigint;\r\n readonly amount1Min: bigint;\r\n readonly recipient: Address;\r\n readonly owner: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n}\r\n\r\n/** Encodes `CL_DECREASE_LIQUIDITY` followed by `TAKE_PAIR`. */\r\nexport function buildCLDecreaseCall(args: BuildCLDecreaseArgs): EncodedLiquidityCall {\r\n if (args.liquidity <= 0n) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] liquidity to remove must be positive: ${args.liquidity}`,\r\n );\r\n }\r\n const recipient = args.recipient === args.owner ? MSG_SENDER : args.recipient;\r\n const p = plan()\r\n .add(\r\n ACTIONS.CL_DECREASE_LIQUIDITY,\r\n encodeAbiParameters(CL_MODIFY_PARAMS, [\r\n args.tokenId,\r\n args.liquidity,\r\n args.amount0Min,\r\n args.amount1Min,\r\n args.hookData ?? \"0x\",\r\n ]),\r\n `decrease CL position #${args.tokenId} by ${args.liquidity}`,\r\n )\r\n .add(\r\n ACTIONS.TAKE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR_AND_ADDRESS, [\r\n args.poolKey.currency0,\r\n args.poolKey.currency1,\r\n recipient,\r\n ]),\r\n \"take both currencies to the recipient\",\r\n );\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for adding liquidity to a bin pool. */\r\nexport interface BuildBinAddArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly amount0: bigint;\r\n readonly amount1: bigint;\r\n readonly amount0Max: bigint;\r\n readonly amount1Max: bigint;\r\n readonly activeIdDesired: number;\r\n readonly idSlippage: number;\r\n /** Bin offsets relative to the active id, one entry per bin. */\r\n readonly deltaIds: readonly number[];\r\n /** Share of `amount0` per bin, scaled to 1e18. Must sum to <= 1e18. */\r\n readonly distributionX: readonly bigint[];\r\n /** Share of `amount1` per bin, scaled to 1e18. Must sum to <= 1e18. */\r\n readonly distributionY: readonly bigint[];\r\n readonly to: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n readonly value?: bigint;\r\n}\r\n\r\n/** Encodes `BIN_ADD_LIQUIDITY` followed by `SETTLE_PAIR` (and `SWEEP` of the native side when value is attached). */\r\nexport function buildBinAddCall(args: BuildBinAddArgs): EncodedLiquidityCall {\r\n const binCount = args.deltaIds.length;\r\n if (binCount === 0) {\r\n throw new RangeError(\"[@latchprotocol/widgets] a bin mint must target at least one bin\");\r\n }\r\n if (args.distributionX.length !== binCount || args.distributionY.length !== binCount) {\r\n throw new RangeError(\r\n \"[@latchprotocol/widgets] deltaIds, distributionX and distributionY must be the same length\",\r\n );\r\n }\r\n if (!Number.isInteger(args.activeIdDesired) || args.activeIdDesired < 0) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] activeIdDesired must be a non-negative integer: ${args.activeIdDesired}`,\r\n );\r\n }\r\n\r\n const p = plan()\r\n .add(\r\n ACTIONS.BIN_ADD_LIQUIDITY,\r\n encodeAbiParameters(BIN_ADD_LIQUIDITY_PARAMS, [\r\n {\r\n poolKey: poolKeyStruct(args.poolKey),\r\n amount0: args.amount0,\r\n amount1: args.amount1,\r\n amount0Max: args.amount0Max,\r\n amount1Max: args.amount1Max,\r\n activeIdDesired: BigInt(args.activeIdDesired),\r\n idSlippage: BigInt(args.idSlippage),\r\n deltaIds: args.deltaIds.map((id) => BigInt(id)),\r\n distributionX: [...args.distributionX],\r\n distributionY: [...args.distributionY],\r\n // One entry per bin. Zero means \"accept whatever the pool mints\"; the\r\n // real slippage guard for a bin mint is idSlippage plus amountNMax.\r\n minLiquidities: args.deltaIds.map(() => 0n),\r\n to: args.to,\r\n hookData: args.hookData ?? \"0x\",\r\n },\r\n ]),\r\n `add bin liquidity across ${binCount} bins around id ${args.activeIdDesired}`,\r\n )\r\n .add(\r\n ACTIONS.SETTLE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR, [args.poolKey.currency0, args.poolKey.currency1]),\r\n \"settle both currencies from the caller\",\r\n );\r\n if ((args.value ?? 0n) > 0n) p.add(...sweepNativeStep());\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: args.value ?? 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\n/** Arguments for removing liquidity from a bin pool. */\r\nexport interface BuildBinRemoveArgs {\r\n readonly positionManager: Address;\r\n readonly poolKey: PoolKey;\r\n readonly amount0Min: bigint;\r\n readonly amount1Min: bigint;\r\n /** Bin ids being burned. */\r\n readonly ids: readonly number[];\r\n /** Share amount burned per bin, aligned with `ids`. */\r\n readonly amounts: readonly bigint[];\r\n readonly from: Address;\r\n readonly recipient: Address;\r\n readonly deadline: bigint;\r\n readonly hookData?: Hex;\r\n}\r\n\r\n/** Encodes `BIN_REMOVE_LIQUIDITY` followed by `TAKE_PAIR`. */\r\nexport function buildBinRemoveCall(args: BuildBinRemoveArgs): EncodedLiquidityCall {\r\n if (args.ids.length === 0) {\r\n throw new RangeError(\"[@latchprotocol/widgets] a bin burn must target at least one bin\");\r\n }\r\n if (args.ids.length !== args.amounts.length) {\r\n throw new RangeError(\"[@latchprotocol/widgets] ids and amounts must be the same length\");\r\n }\r\n const recipient = args.recipient === args.from ? MSG_SENDER : args.recipient;\r\n const p = plan()\r\n .add(\r\n ACTIONS.BIN_REMOVE_LIQUIDITY,\r\n encodeAbiParameters(BIN_REMOVE_LIQUIDITY_PARAMS, [\r\n {\r\n poolKey: poolKeyStruct(args.poolKey),\r\n amount0Min: args.amount0Min,\r\n amount1Min: args.amount1Min,\r\n ids: args.ids.map((id) => BigInt(id)),\r\n amounts: [...args.amounts],\r\n from: args.from,\r\n hookData: args.hookData ?? \"0x\",\r\n },\r\n ]),\r\n `remove bin liquidity from ${args.ids.length} bins`,\r\n )\r\n .add(\r\n ACTIONS.TAKE_PAIR,\r\n encodeAbiParameters(CURRENCY_PAIR_AND_ADDRESS, [\r\n args.poolKey.currency0,\r\n args.poolKey.currency1,\r\n recipient,\r\n ]),\r\n \"take both currencies to the recipient\",\r\n );\r\n\r\n return {\r\n to: args.positionManager,\r\n data: encodeFunctionData({\r\n abi: POSITION_MANAGER_ABI,\r\n functionName: \"modifyLiquidities\",\r\n args: [p.encode(), args.deadline],\r\n }),\r\n value: 0n,\r\n planTrace: p.describe(),\r\n };\r\n}\r\n\r\nfunction assertTickRange(tickLower: number, tickUpper: number): void {\r\n if (!Number.isInteger(tickLower) || !Number.isInteger(tickUpper)) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] ticks must be integers: [${tickLower}, ${tickUpper}]`,\r\n );\r\n }\r\n if (tickLower >= tickUpper) {\r\n throw new RangeError(\r\n `[@latchprotocol/widgets] tickLower must be below tickUpper: [${tickLower}, ${tickUpper}]`,\r\n );\r\n }\r\n}\r\n","// SPDX-License-Identifier: MIT\n/**\n * Live protocol adapter, backed by viem.\n *\n * This is the implementation that produces **real calldata** and submits real\n * transactions. It is the swap and liquidity call paths from `src/callpath/`\n * wired to a viem `PublicClient` for reads and a wallet for writes.\n *\n * ## What it can and cannot do today\n *\n * Bounded honestly, feature by feature:\n *\n * - **Encoding** is complete and unit-tested. `buildSwap`, `buildAddLiquidity`\n * and `buildRemoveLiquidity` produce the exact calldata the router and\n * position managers decode, integrator fee step included.\n * - **Launches** are read from the launch guards, keyed by pool id: CL pools\n * from `contracts.launchGuardHook`, Bin pools from `contracts.binLaunchGuardHook`.\n * With neither configured every launch read throws\n * `ChainConfigError` rather than guessing an address. On a chain with no\n * `LaunchGuardHook` deployed, that is the correct and only answer.\n * - **Token, balance and allowance reads** are ordinary ERC-20 and Permit2\n * calls and will work against any chain that has them.\n * - **Pool discovery** is not on-chain: the singleton has no pool enumeration.\n * Pass the pools you support, or wire an indexer (`@latchprotocol/sdk/indexer`\n * describes the schema).\n * - **Quoting** requires either a deployed quoter or a host-supplied function.\n * Without one, `quoteSwap` throws {@link UnsupportedOperationError} rather\n * than inventing a number - a fabricated quote is worse than no quote.\n */\n\nimport {\n BaseError,\n ExecutionRevertedError,\n decodeAbiParameters,\n encodeFunctionData,\n isAddressEqual,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport {\n BIN_LAUNCH_GUARD_HOOK_ABI,\n CLOCK_MODE_CALLDATA,\n LAUNCHPAD_KIT_V2_ABI,\n TIMESTAMP_CLOCK_MODE,\n binRawPriceFromId,\n getDeployment,\n isDynamicLPFee,\n quoterAbiFor,\n poolKeyToId,\n readBinPoolKeyParameters,\n readCLPoolKeyParameters,\n readContractClock,\n type PoolId,\n type PoolKey,\n} from \"@latchprotocol/sdk\";\n\n/* getSlot0 on both pool managers: the pool's own price, for the no-impact output. */\nconst CL_SLOT0_ABI = [\n {\n type: \"function\",\n name: \"getSlot0\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"sqrtPriceX96\", type: \"uint160\" },\n { name: \"tick\", type: \"int24\" },\n { name: \"protocolFee\", type: \"uint24\" },\n { name: \"lpFee\", type: \"uint24\" },\n ],\n },\n] as const;\nconst BIN_SLOT0_ABI = [\n {\n type: \"function\",\n name: \"getSlot0\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"activeId\", type: \"uint24\" },\n { name: \"protocolFee\", type: \"uint24\" },\n { name: \"lpFee\", type: \"uint24\" },\n ],\n },\n] as const;\nconst Q192 = 2n ** 192n;\n\n/* The pool-manager views the liquidity paths read: pool liquidity and fee\n growth (CL, for a position's amounts and uncollected fees), bin reserves and\n share supply (Bin, for what a holder's shares are worth). */\nconst CL_POOL_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"getLiquidity\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [{ name: \"liquidity\", type: \"uint128\" }],\n },\n {\n type: \"function\",\n name: \"getFeeGrowthGlobals\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"bytes32\" }],\n outputs: [\n { name: \"feeGrowthGlobal0x128\", type: \"uint256\" },\n { name: \"feeGrowthGlobal1x128\", type: \"uint256\" },\n ],\n },\n {\n type: \"function\",\n name: \"getPoolTickInfo\",\n stateMutability: \"view\",\n inputs: [\n { name: \"id\", type: \"bytes32\" },\n { name: \"tick\", type: \"int24\" },\n ],\n outputs: [\n {\n name: \"info\",\n type: \"tuple\",\n components: [\n { name: \"liquidityGross\", type: \"uint128\" },\n { name: \"liquidityNet\", type: \"int128\" },\n { name: \"feeGrowthOutside0X128\", type: \"uint256\" },\n { name: \"feeGrowthOutside1X128\", type: \"uint256\" },\n ],\n },\n ],\n },\n] as const;\nconst BIN_POOL_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"getBin\",\n stateMutability: \"view\",\n inputs: [\n { name: \"id\", type: \"bytes32\" },\n { name: \"binId\", type: \"uint24\" },\n ],\n outputs: [\n { name: \"binReserveX\", type: \"uint128\" },\n { name: \"binReserveY\", type: \"uint128\" },\n { name: \"binLiquidity\", type: \"uint256\" },\n { name: \"totalShares\", type: \"uint256\" },\n ],\n },\n] as const;\nconst POOL_KEY_OUTPUT = {\n name: \"poolKey\",\n type: \"tuple\",\n components: [\n { name: \"currency0\", type: \"address\" },\n { name: \"currency1\", type: \"address\" },\n { name: \"hooks\", type: \"address\" },\n { name: \"poolManager\", type: \"address\" },\n { name: \"fee\", type: \"uint24\" },\n { name: \"parameters\", type: \"bytes32\" },\n ],\n} as const;\n/* CLPositionManager: a solmate ERC-721 with no owner enumeration, so a\n holder's tokens come from `Transfer(to)` logs confirmed by `ownerOf`. */\nconst CL_POSM_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"ownerOf\",\n stateMutability: \"view\",\n inputs: [{ name: \"id\", type: \"uint256\" }],\n outputs: [{ name: \"owner\", type: \"address\" }],\n },\n {\n type: \"function\",\n name: \"positions\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [\n POOL_KEY_OUTPUT,\n { name: \"tickLower\", type: \"int24\" },\n { name: \"tickUpper\", type: \"int24\" },\n { name: \"liquidity\", type: \"uint128\" },\n { name: \"feeGrowthInside0LastX128\", type: \"uint256\" },\n { name: \"feeGrowthInside1LastX128\", type: \"uint256\" },\n { name: \"subscriber\", type: \"address\" },\n ],\n },\n {\n type: \"event\",\n name: \"Transfer\",\n inputs: [\n { name: \"from\", type: \"address\", indexed: true },\n { name: \"to\", type: \"address\", indexed: true },\n { name: \"id\", type: \"uint256\", indexed: true },\n ],\n },\n] as const;\n/* BinPositionManager: ERC-1155-like shares per (pool, bin); the token ids a\n holder ever received come from `TransferBatch(to)` logs, the live balance from `balanceOf`. */\nconst BIN_POSM_VIEWS_ABI = [\n {\n type: \"function\",\n name: \"positions\",\n stateMutability: \"view\",\n inputs: [{ name: \"tokenId\", type: \"uint256\" }],\n outputs: [POOL_KEY_OUTPUT, { name: \"binId\", type: \"uint24\" }],\n },\n {\n type: \"function\",\n name: \"balanceOf\",\n stateMutability: \"view\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"id\", type: \"uint256\" },\n ],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n },\n {\n type: \"event\",\n name: \"TransferBatch\",\n inputs: [\n { name: \"sender\", type: \"address\", indexed: true },\n { name: \"from\", type: \"address\", indexed: true },\n { name: \"to\", type: \"address\", indexed: true },\n { name: \"ids\", type: \"uint256[]\", indexed: false },\n { name: \"amounts\", type: \"uint256[]\", indexed: false },\n ],\n },\n] as const;\nimport type { ChainConfig } from \"../config/chain.js\";\nimport { nextBlockClock, requireContract } from \"../config/chain.js\";\nimport {\n ERC20_ABI,\n MAX_UINT160,\n MAX_UINT256,\n MAX_UINT48,\n PERMIT2_ABI,\n} from \"../callpath/constants.js\";\nimport { buildSwapCall, type SwapHop } from \"../callpath/swap.js\";\nimport {\n buildBinAddCall,\n buildBinRemoveCall,\n buildCLDecreaseCall,\n buildCLMintCall,\n} from \"../callpath/liquidity.js\";\nimport {\n decodeLaunchGuard,\n isLaunchConfigured,\n launchGuardAbiFor,\n type DurationClock,\n type RawLaunchGuard,\n} from \"../callpath/launch.js\";\nimport {\n amountsForLiquidity,\n getLiquidityForAmounts,\n getSqrtRatioAtTick,\n uncollectedFees,\n} from \"../core/clMath.js\";\nimport { binShareAmounts, binStepOf, tickSpacingOf } from \"../core/pool.js\";\nimport { buildUniformBinDistribution } from \"./binDistribution.js\";\nimport {\n UnsupportedOperationError,\n WalletNotConnectedError,\n type AddLiquidityExecutionRequest,\n type AddLiquidityQuote,\n type AddLiquidityQuoteRequest,\n type ApprovalRequirement,\n type LaunchInfo,\n type PoolInfo,\n type PoolType,\n type PoolState,\n type PositionInfo,\n type ProtocolAdapter,\n type RemoveLiquidityExecutionRequest,\n type RemoveLiquidityQuote,\n type SwapExecutionRequest,\n type SwapQuoteRequest,\n type SwapQuoteResult,\n type TokenInfo,\n type TransactionOutcome,\n type WidgetTransactionRequest,\n} from \"./protocol.js\";\n\nconst NATIVE: Address = \"0x0000000000000000000000000000000000000000\";\n\n/** Minimal wallet surface. Any wallet stack that can sign satisfies this. */\nexport interface WidgetWallet {\n /** Currently selected account, or `null`. */\n getAccount(): Promise<Address | null>;\n /** Submits a transaction and returns its hash. */\n sendTransaction(request: {\n to: Address;\n data: Hex;\n value: bigint;\n }): Promise<Hex>;\n}\n\n/**\n * Host-supplied functions for the parts the protocol cannot answer on its own.\n *\n * Each one is optional. Omitting a function makes the corresponding widget\n * feature fail loudly with a named error instead of degrading to invented data.\n */\nexport interface ViemAdapterOverrides {\n quoteSwap?: (request: SwapQuoteRequest, pools: readonly PoolInfo[]) => Promise<SwapQuoteResult>;\n quoteAddLiquidity?: (request: AddLiquidityQuoteRequest) => Promise<AddLiquidityQuote>;\n quoteRemoveLiquidity?: (\n position: PositionInfo,\n percentBps: number,\n ) => Promise<RemoveLiquidityQuote>;\n listPositions?: (owner: Address, pool?: PoolInfo) => Promise<readonly PositionInfo[]>;\n getPoolState?: (pool: PoolInfo) => Promise<PoolState>;\n /** Resolves a route. Defaults to a direct pool match over `pools`. */\n findRoute?: (\n tokenIn: TokenInfo,\n tokenOut: TokenInfo,\n pools: readonly PoolInfo[],\n ) => readonly SwapHop[];\n}\n\n/** Options for {@link createViemAdapter}. */\nexport interface ViemAdapterOptions {\n readonly chain: ChainConfig;\n readonly publicClient: PublicClient;\n readonly wallet?: WidgetWallet;\n /** Tokens offered in the picker. There is no on-chain token registry. */\n readonly tokens: readonly TokenInfo[];\n /**\n * Pools this integrator supports. There is no on-chain pool enumeration.\n *\n * Launch pools live in this list too: a launch is a pool. `listLaunches`\n * selects the ones whose key names `contracts.launchGuardHook`, so there is\n * no separate launch list to keep in sync.\n */\n readonly pools: readonly PoolInfo[];\n /**\n * The block the position managers were deployed at (or any earlier one).\n *\n * Neither position manager enumerates a holder's positions, so\n * `listPositions` reconstructs them from `Transfer` / `TransferBatch` logs\n * addressed to the owner and confirms each against live state. The scan\n * starts here. Without it `listPositions` throws rather than scanning from\n * genesis, which public endpoints refuse and which would read as \"no\n * positions\" when it silently returned nothing.\n */\n readonly positionsFromBlock?: bigint;\n readonly overrides?: ViemAdapterOverrides;\n}\n\nclass ViemProtocolAdapter implements ProtocolAdapter {\n readonly kind = \"viem\";\n readonly isMock = false;\n readonly chain: ChainConfig;\n\n readonly #options: ViemAdapterOptions;\n\n constructor(options: ViemAdapterOptions) {\n this.#options = options;\n this.chain = options.chain;\n }\n\n get #client(): PublicClient {\n return this.#options.publicClient;\n }\n\n get #overrides(): ViemAdapterOverrides {\n return this.#options.overrides ?? {};\n }\n\n async getAccount(): Promise<Address | null> {\n const wallet = this.#options.wallet;\n if (wallet === undefined) return null;\n return wallet.getAccount();\n }\n\n async listTokens(): Promise<readonly TokenInfo[]> {\n return this.#options.tokens;\n }\n\n async getToken(address: Address): Promise<TokenInfo | null> {\n const known = this.#options.tokens.find((token) => isAddressEqual(token.address, address));\n if (known !== undefined) return known;\n if (isAddressEqual(address, NATIVE)) {\n return {\n address: NATIVE,\n symbol: this.chain.nativeCurrency.symbol,\n name: this.chain.nativeCurrency.name,\n decimals: this.chain.nativeCurrency.decimals,\n isNative: true,\n };\n }\n const [symbol, name, decimals] = await Promise.all([\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"symbol\" }),\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"name\" }),\n this.#client.readContract({ address, abi: ERC20_ABI, functionName: \"decimals\" }),\n ]);\n return { address, symbol, name, decimals: Number(decimals) };\n }\n\n async getBalance(token: TokenInfo, owner: Address): Promise<bigint> {\n if (token.isNative === true || isAddressEqual(token.address, NATIVE)) {\n return this.#client.getBalance({ address: owner });\n }\n return this.#client.readContract({\n address: token.address,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [owner],\n });\n }\n\n async listPools(): Promise<readonly PoolInfo[]> {\n return this.#options.pools;\n }\n\n /**\n * The pool's live state from its manager's `getSlot0` (plus `getLiquidity`\n * for a CL pool). An uninitialised pool answers a zero price, which is\n * reported as an error rather than as tick 0.\n */\n async getPoolState(pool: PoolInfo): Promise<PoolState> {\n const override = this.#overrides.getPoolState;\n if (override !== undefined) return override(pool);\n if (pool.poolType === \"CL\") {\n const [[sqrtPriceX96, tick], liquidity] = await Promise.all([\n this.#client.readContract({ address: pool.key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] }),\n this.#client.readContract({ address: pool.key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getLiquidity\", args: [pool.id] }),\n ]);\n if (sqrtPriceX96 === 0n) {\n throw new UnsupportedOperationError(\"getPoolState\", `pool ${pool.id} is not initialised on ${pool.key.poolManager}`);\n }\n return { poolId: pool.id, poolType: \"CL\", currentTick: tick, sqrtPriceX96, liquidity, source: \"live\" };\n }\n const [activeId] = await this.#client.readContract({ address: pool.key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n if (activeId === 0) {\n throw new UnsupportedOperationError(\"getPoolState\", `pool ${pool.id} is not initialised on ${pool.key.poolManager}`);\n }\n return { poolId: pool.id, poolType: \"BIN\", activeId, source: \"live\" };\n }\n\n /**\n * The two allowances `spender` needs before it can pull `token` through\n * Permit2: ERC-20 to Permit2, then Permit2 to the spender. The spender is\n * the router for a swap (the default) and a position manager for a\n * liquidity add; the liquidity hooks pass it, because an allowance to the\n * router does nothing for a mint.\n */\n async getApprovalRequirements(\n token: TokenInfo,\n owner: Address,\n amount: bigint,\n spender?: Address,\n ): Promise<readonly ApprovalRequirement[]> {\n if (token.isNative === true || isAddressEqual(token.address, NATIVE)) return [];\n const permit2 = requireContract(this.chain, \"permit2\", \"pull the input token for a swap\");\n const router = spender ?? requireContract(this.chain, \"universalRouter\", \"execute a swap\");\n\n const requirements: ApprovalRequirement[] = [];\n\n const erc20Allowance = await this.#client.readContract({\n address: token.address,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [owner, permit2],\n });\n if (erc20Allowance < amount) {\n requirements.push({\n kind: \"erc20-to-permit2\",\n token,\n spender: permit2,\n current: erc20Allowance,\n required: amount,\n });\n }\n\n const [permit2Amount, expiration] = await this.#client.readContract({\n address: permit2,\n abi: PERMIT2_ABI,\n functionName: \"allowance\",\n args: [owner, token.address, router],\n });\n const nowSeconds = BigInt(Math.floor(Date.now() / 1000));\n const expired = BigInt(expiration) !== 0n && BigInt(expiration) <= nowSeconds;\n if (BigInt(permit2Amount) < amount || expired) {\n requirements.push({\n kind: \"permit2-to-router\",\n token,\n spender: router,\n current: expired ? 0n : BigInt(permit2Amount),\n required: amount,\n });\n }\n\n return requirements;\n }\n\n async buildApproval(requirement: ApprovalRequirement): Promise<WidgetTransactionRequest> {\n if (requirement.kind === \"erc20-to-permit2\") {\n return {\n to: requirement.token.address,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [requirement.spender, MAX_UINT256],\n }),\n value: 0n,\n summary: `Approve ${requirement.token.symbol} for Permit2`,\n source: \"live\",\n };\n }\n const permit2 = requireContract(this.chain, \"permit2\", \"approve the router through Permit2\");\n return {\n to: permit2,\n data: encodeFunctionData({\n abi: PERMIT2_ABI,\n functionName: \"approve\",\n args: [requirement.token.address, requirement.spender, MAX_UINT160, Number(MAX_UINT48)],\n }),\n value: 0n,\n summary: `Approve ${requirement.spender} to spend ${requirement.token.symbol} via Permit2`,\n source: \"live\",\n };\n }\n\n /**\n * Quotes an exact-input swap.\n *\n * With `overrides.quoteSwap` the host answers. Otherwise every configured\n * pool holding both tokens is quoted DIRECTLY against the deployed quoter for\n * its type (`contracts.quoter` for CL, `contracts.binQuoter` for Bin) and the\n * best output wins. No multi-hop routing: a route this adapter did not quote\n * is a route it cannot vouch for. Throws when no quoter can answer.\n *\n * The LP fee shown beside the quote is the pool's static fee, or, for a\n * dynamic-fee pool whose hook is a launch guard, the guard's `currentFee`.\n * Any other dynamic pool is reported `lpFeeUnknown`, which the widget renders\n * as \"dynamic\" rather than as a rate it did not read.\n */\n async quoteSwap(request: SwapQuoteRequest): Promise<SwapQuoteResult> {\n const override = this.#overrides.quoteSwap;\n if (override !== undefined) return override(request, this.#options.pools);\n\n const contracts = this.chain.contracts;\n const candidates = this.#options.pools.filter(\n (pool) =>\n (request.poolId === undefined || pool.id === request.poolId) &&\n ((isAddressEqual(pool.token0.address, request.tokenIn.address) &&\n isAddressEqual(pool.token1.address, request.tokenOut.address)) ||\n (isAddressEqual(pool.token1.address, request.tokenIn.address) &&\n isAddressEqual(pool.token0.address, request.tokenOut.address))),\n );\n if (candidates.length === 0) {\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n request.poolId !== undefined\n ? `pool ${request.poolId} is not a configured pool holding both ${request.tokenIn.symbol} and ${request.tokenOut.symbol}.`\n : `no configured pool holds both ${request.tokenIn.symbol} and ${request.tokenOut.symbol}. ` +\n \"This adapter quotes direct pools only; supply `overrides.quoteSwap` for multi-hop routes.\",\n );\n }\n const quotable = candidates.filter((pool) =>\n pool.poolType === \"CL\" ? contracts.quoter !== undefined : contracts.binQuoter !== undefined,\n );\n if (quotable.length === 0) {\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n `a pool for this pair exists but no quoter is configured for its type (${candidates.map((p) => p.poolType).join(\", \")}). ` +\n \"Set `contracts.quoter` (CL) / `contracts.binQuoter` (Bin), or supply `overrides.quoteSwap`. \" +\n \"This adapter will not estimate a price it cannot verify.\",\n );\n }\n\n const results = await Promise.all(\n quotable.map(async (pool) => {\n const quoter = (pool.poolType === \"CL\" ? contracts.quoter : contracts.binQuoter) as Address;\n try {\n const { result } = await this.#client.simulateContract({\n address: quoter,\n abi: quoterAbiFor(pool.poolType),\n functionName: \"quoteExactInputSingle\",\n args: [\n {\n poolKey: pool.key,\n zeroForOne: isAddressEqual(pool.key.currency0, request.tokenIn.address),\n exactAmount: request.amountIn,\n hookData: \"0x\",\n },\n ],\n });\n const [amountOut, gasEstimate] = result as readonly [bigint, bigint];\n return { pool, amountOut, gasEstimate, error: null as Error | null };\n } catch (error) {\n return { pool, amountOut: 0n, gasEstimate: 0n, error: error instanceof Error ? error : new Error(String(error)) };\n }\n }),\n );\n const answered = results.filter((r) => r.error === null);\n if (answered.length === 0) {\n const first = results[0]?.error;\n throw new UnsupportedOperationError(\n \"quoteSwap\",\n `every direct pool for this pair failed to quote${first === null || first === undefined ? \"\" : `: ${first.message}`}`,\n );\n }\n const best = answered.reduce((a, b) => (b.amountOut > a.amountOut ? b : a));\n const pool = best.pool;\n\n let lpFeePips = pool.lpFeePips;\n let lpFeeUnknown = false;\n if (isDynamicLPFee(pool.lpFeePips)) {\n const guardFee = await this.#launchGuardFee(pool);\n if (guardFee === null) {\n lpFeePips = 0;\n lpFeeUnknown = true;\n } else {\n lpFeePips = guardFee;\n }\n }\n\n /* The output the same input would fetch at the pool's CURRENT price, net of\n the known LP fee, so the breakdown can isolate price impact from the fee.\n With a hook-set fee the adapter cannot separate the two and reports no\n spot rather than an impact that silently includes the fee. */\n const spotAmountOut = lpFeeUnknown ? null : await this.#spotAmountOut(pool, request.tokenIn.address, request.amountIn, lpFeePips);\n\n return {\n route: [\n {\n poolId: pool.id,\n poolType: pool.poolType,\n tokenIn: request.tokenIn,\n tokenOut: request.tokenOut,\n lpFeePips,\n hooks: pool.hooks,\n },\n ],\n amountIn: request.amountIn,\n grossAmountOut: best.amountOut,\n spotAmountOut,\n lpFeeAmount: (request.amountIn * BigInt(lpFeePips)) / 1_000_000n,\n lpFeePips,\n ...(lpFeeUnknown ? { lpFeeUnknown } : {}),\n estimatedGas: best.gasEstimate,\n source: \"live\",\n };\n }\n\n /**\n * `currentFee(poolId)` when the pool's hook is one of the configured launch\n * guards; `null` when the hook is not a guard (the fee is then genuinely\n * unreadable in advance). A guard that REVERTS `currentFee` — an unclaimed\n * pool id — is also `null`. Anything else (transport failure, an unknown\n * `CLOCK_MODE`) is thrown: an unreachable RPC is an error state, never a\n * quote annotated \"dynamic\".\n */\n async #launchGuardFee(pool: PoolInfo): Promise<number | null> {\n const guard = this.#guardFor(pool);\n if (guard === null) return null;\n const abi =\n guard.poolType === \"CL\" ? launchGuardAbiFor(await this.#launchClock(guard.hook, \"CL\")) : BIN_LAUNCH_GUARD_HOOK_ABI;\n try {\n const fee = await this.#client.readContract({ address: guard.hook, abi, functionName: \"currentFee\", args: [pool.id] });\n return Number(fee);\n } catch (error) {\n if (error instanceof BaseError && error.walk((x: unknown) => x instanceof ExecutionRevertedError) !== null) {\n return null;\n }\n throw error;\n }\n }\n\n /** The configured launch guard this pool names, if any, with the pool type it serves. */\n #guardFor(pool: PoolInfo): { readonly hook: Address; readonly poolType: PoolType } | null {\n const { launchGuardHook, binLaunchGuardHook } = this.chain.contracts;\n if (pool.poolType === \"CL\" && launchGuardHook !== undefined && isAddressEqual(pool.hooks, launchGuardHook)) {\n return { hook: launchGuardHook, poolType: \"CL\" };\n }\n if (pool.poolType === \"BIN\" && binLaunchGuardHook !== undefined && isAddressEqual(pool.hooks, binLaunchGuardHook)) {\n return { hook: binLaunchGuardHook, poolType: \"BIN\" };\n }\n return null;\n }\n\n /** `amountIn` priced at the pool's spot from `getSlot0`, less `lpFeePips`; `null` when the read fails. */\n async #spotAmountOut(pool: PoolInfo, tokenIn: Address, amountIn: bigint, lpFeePips: number): Promise<bigint | null> {\n const zeroForOne = isAddressEqual(pool.key.currency0, tokenIn);\n const afterFee = (amountIn * BigInt(1_000_000 - lpFeePips)) / 1_000_000n;\n try {\n if (pool.poolType === \"CL\") {\n const [sqrtPriceX96] = await this.#client.readContract({ address: pool.key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n if (sqrtPriceX96 === 0n) return null;\n const p2 = sqrtPriceX96 * sqrtPriceX96;\n return zeroForOne ? (afterFee * p2) / Q192 : (afterFee * Q192) / p2;\n }\n const [activeId] = await this.#client.readContract({ address: pool.key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [pool.id] });\n const { binStep } = readBinPoolKeyParameters(pool.key);\n const raw1per0 = binRawPriceFromId(Number(activeId), binStep);\n if (!Number.isFinite(raw1per0) || raw1per0 <= 0) return null;\n /* 1e18-scaled fixed point keeps the bigint arithmetic exact enough for an impact figure. */\n const SCALE = 10n ** 18n;\n const scaled = BigInt(Math.round(raw1per0 * 1e18));\n if (scaled === 0n) return null;\n return zeroForOne ? (afterFee * scaled) / SCALE : (afterFee * SCALE) / scaled;\n } catch {\n return null;\n }\n }\n\n async buildSwap(request: SwapExecutionRequest): Promise<WidgetTransactionRequest> {\n const router = requireContract(this.chain, \"universalRouter\", \"execute a swap\");\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"build a swap\");\n\n const hops = this.#resolveHops(request);\n const call = buildSwapCall({\n router,\n hops,\n amountIn: request.amountIn,\n minAmountOutGross: request.minAmountOutGross,\n minAmountOutNet: request.minAmountOutNet,\n expectedAmountOutGross: request.quote.grossAmountOut,\n integrator: request.integrator,\n recipient: request.recipient,\n sender: account,\n deadline: request.deadline,\n });\n\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Swap ${request.tokenIn.symbol} for ${request.tokenOut.symbol}`,\n ...(call.integratorFee\n ? {\n integratorFee: {\n referrer: call.integratorFee.referrer,\n feeBps: call.integratorFee.feeBps,\n currency: call.integratorFee.currency,\n expectedAmount: call.integratorFee.expectedAmount,\n },\n }\n : {}),\n source: \"live\",\n };\n }\n\n #resolveHops(request: SwapExecutionRequest): readonly SwapHop[] {\n const override = this.#overrides.findRoute;\n if (override !== undefined) {\n return override(request.tokenIn, request.tokenOut, this.#options.pools);\n }\n const hops: SwapHop[] = [];\n for (const step of request.quote.route) {\n const pool = this.#options.pools.find((candidate) => candidate.id === step.poolId);\n if (pool === undefined) {\n throw new UnsupportedOperationError(\n \"buildSwap\",\n `the quote routes through pool ${step.poolId}, which is not in the configured pool list`,\n );\n }\n hops.push({\n poolKey: pool.key,\n poolType: pool.poolType,\n currencyIn: step.tokenIn.address,\n currencyOut: step.tokenOut.address,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n }\n return hops;\n }\n\n /**\n * Turns desired amounts into the liquidity the pool will mint and the\n * amounts it will pull, from live state and the pool's own formulas\n * (`core/clMath.ts`; `adapters/binDistribution.ts`). The amounts reported\n * are what the position manager settles: an add rounds towards the pool.\n */\n async quoteAddLiquidity(request: AddLiquidityQuoteRequest): Promise<AddLiquidityQuote> {\n const override = this.#overrides.quoteAddLiquidity;\n if (override !== undefined) return override(request);\n const { pool, range } = request;\n if (range.type === \"CL\") {\n if (pool.poolType !== \"CL\") {\n throw new UnsupportedOperationError(\"quoteAddLiquidity\", \"tick range given for a bin pool\");\n }\n const spacing = tickSpacingOf(pool);\n if (range.tickLower % spacing !== 0 || range.tickUpper % spacing !== 0) {\n throw new RangeError(\n `[@latchprotocol/widgets] ticks must be multiples of the pool's spacing ${spacing}: [${range.tickLower}, ${range.tickUpper}]`,\n );\n }\n const state = await this.getPoolState(pool);\n const sqrtPriceX96 = state.sqrtPriceX96 as bigint;\n const liquidity = getLiquidityForAmounts(\n sqrtPriceX96,\n getSqrtRatioAtTick(range.tickLower),\n getSqrtRatioAtTick(range.tickUpper),\n request.amount0Desired,\n request.amount1Desired,\n );\n if (liquidity === 0n) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n \"these amounts mint no liquidity in this range: at the pool's price the range needs the other token, or the amounts are too small\",\n );\n }\n const amounts = amountsForLiquidity(sqrtPriceX96, range.tickLower, range.tickUpper, liquidity, true);\n const inRange = (state.currentTick as number) >= range.tickLower && (state.currentTick as number) < range.tickUpper;\n const poolLiquidity = state.liquidity ?? 0n;\n const shareBps = inRange ? Number((liquidity * 10_000n) / (poolLiquidity + liquidity)) : null;\n return { pool, range, amount0: amounts.amount0, amount1: amounts.amount1, liquidity, shareBps, source: \"live\" };\n }\n if (pool.poolType !== \"BIN\") {\n throw new UnsupportedOperationError(\"quoteAddLiquidity\", \"bin range given for a CL pool\");\n }\n const state = await this.getPoolState(pool);\n const activeId = state.activeId as number;\n if (Math.abs(activeId - range.activeIdDesired) > range.idSlippage) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n `the active bin is ${activeId}, more than ${range.idSlippage} bins from the ${range.activeIdDesired} the range was built around; rebuild the range`,\n );\n }\n const distribution = buildUniformBinDistribution(range.binIdLower, range.binIdUpper, range.activeIdDesired);\n const takesX = distribution.some((share) => share.distributionX > 0n);\n const takesY = distribution.some((share) => share.distributionY > 0n);\n const amount0 = takesX ? request.amount0Desired : 0n;\n const amount1 = takesY ? request.amount1Desired : 0n;\n if (amount0 + amount1 === 0n) {\n throw new UnsupportedOperationError(\n \"quoteAddLiquidity\",\n \"nothing to deposit: the chosen bins take only the token whose amount is zero\",\n );\n }\n /* Bin shares are minted per bin from the deposit's value in that bin; the\n total is not a single figure the way CL liquidity is. Reported as the\n sum of what the distribution places, in currency1 units at each bin's\n price, which is what `BinPool.mint` credits. */\n const binStep = binStepOf(pool);\n let liquidity = 0n;\n for (const share of distribution) {\n const x = (amount0 * share.distributionX) / 10n ** 18n;\n const y = (amount1 * share.distributionY) / 10n ** 18n;\n const price = binRawPriceFromId(share.binId, binStep);\n liquidity += BigInt(Math.floor(Number(x) * price)) + y;\n }\n return { pool, range, amount0, amount1, liquidity, shareBps: null, binDistribution: distribution, source: \"live\" };\n }\n\n async buildAddLiquidity(\n request: AddLiquidityExecutionRequest,\n ): Promise<WidgetTransactionRequest> {\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"add liquidity\");\n const { quote } = request;\n const nativeValue = this.#nativeValueFor(quote.pool, request.amount0Max, request.amount1Max);\n\n if (quote.range.type === \"CL\") {\n const positionManager = requireContract(\n this.chain,\n \"clPositionManager\",\n \"mint a concentrated-liquidity position\",\n );\n const call = buildCLMintCall({\n positionManager,\n poolKey: quote.pool.key,\n tickLower: quote.range.tickLower,\n tickUpper: quote.range.tickUpper,\n liquidity: quote.liquidity,\n amount0Max: request.amount0Max,\n amount1Max: request.amount1Max,\n owner: request.recipient,\n deadline: request.deadline,\n value: nativeValue,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Add liquidity to ${quote.pool.token0.symbol}/${quote.pool.token1.symbol}`,\n source: \"live\",\n };\n }\n\n const positionManager = requireContract(\n this.chain,\n \"binPositionManager\",\n \"add liquidity to a bin pool\",\n );\n const distribution = quote.binDistribution;\n if (distribution === undefined || distribution.length === 0) {\n throw new UnsupportedOperationError(\n \"buildAddLiquidity\",\n \"a bin mint needs a per-bin distribution; the quote did not supply one\",\n );\n }\n const call = buildBinAddCall({\n positionManager,\n poolKey: quote.pool.key,\n amount0: quote.amount0,\n amount1: quote.amount1,\n amount0Max: request.amount0Max,\n amount1Max: request.amount1Max,\n activeIdDesired: quote.range.activeIdDesired,\n idSlippage: quote.range.idSlippage,\n deltaIds: distribution.map((share) => share.deltaId),\n distributionX: distribution.map((share) => share.distributionX),\n distributionY: distribution.map((share) => share.distributionY),\n to: request.recipient,\n deadline: request.deadline,\n value: nativeValue,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Add liquidity to ${quote.pool.token0.symbol}/${quote.pool.token1.symbol}`,\n source: \"live\",\n };\n }\n\n #nativeValueFor(pool: PoolInfo, amount0Max: bigint, amount1Max: bigint): bigint {\n if (isAddressEqual(pool.token0.address, NATIVE)) return amount0Max;\n if (isAddressEqual(pool.token1.address, NATIVE)) return amount1Max;\n return 0n;\n }\n\n /**\n * A holder's positions, reconstructed from position-manager logs and\n * confirmed against live state. Needs `positionsFromBlock`.\n *\n * CL: `Transfer(to = owner)` candidates, each confirmed by `ownerOf`, then\n * `positions(tokenId)` for the key, ticks and liquidity; amounts and fees\n * from the pool's slot0, tick info and fee-growth globals, exactly as the\n * pool would credit them. Bin: `TransferBatch(to = owner)` candidates, each\n * confirmed by `balanceOf`, grouped by pool; amounts from each bin's\n * reserves and share supply. A position on a pool not in the configured\n * list still appears, with its tokens read off their contracts.\n */\n async listPositions(owner: Address, pool?: PoolInfo): Promise<readonly PositionInfo[]> {\n const override = this.#overrides.listPositions;\n if (override !== undefined) return override(owner, pool);\n const fromBlock = this.#options.positionsFromBlock;\n if (fromBlock === undefined) {\n throw new UnsupportedOperationError(\n \"listPositions\",\n \"position enumeration scans the position managers' transfer logs and needs \" +\n \"`positionsFromBlock` (the block they were deployed at) in the adapter options.\",\n );\n }\n const wanted = pool?.poolType;\n const [cl, bin] = await Promise.all([\n wanted === \"BIN\" ? Promise.resolve([]) : this.#listCLPositions(owner, fromBlock, pool),\n wanted === \"CL\" ? Promise.resolve([]) : this.#listBinPositions(owner, fromBlock, pool),\n ]);\n return [...cl, ...bin];\n }\n\n async #listCLPositions(owner: Address, fromBlock: bigint, only?: PoolInfo): Promise<readonly PositionInfo[]> {\n const positionManager = this.chain.contracts.clPositionManager;\n if (positionManager === undefined) return [];\n const logs = await this.#client.getLogs({\n address: positionManager,\n event: CL_POSM_VIEWS_ABI[2],\n args: { to: owner },\n fromBlock,\n toBlock: \"latest\",\n });\n const candidates = [...new Set(logs.map((log) => log.args.id as bigint))];\n const out: PositionInfo[] = [];\n for (const tokenId of candidates) {\n let holder: Address;\n try {\n holder = await this.#client.readContract({ address: positionManager, abi: CL_POSM_VIEWS_ABI, functionName: \"ownerOf\", args: [tokenId] });\n } catch {\n continue; // burned\n }\n if (!isAddressEqual(holder, owner)) continue;\n const [key, tickLower, tickUpper, liquidity, feeGrowthInside0Last, feeGrowthInside1Last] = await this.#client.readContract({\n address: positionManager,\n abi: CL_POSM_VIEWS_ABI,\n functionName: \"positions\",\n args: [tokenId],\n });\n const poolInfo = await this.#poolInfoFor(key, \"CL\", only);\n if (poolInfo === null) continue;\n const [[sqrtPriceX96, currentTick], [feeGrowthGlobal0, feeGrowthGlobal1], lower, upper] = await Promise.all([\n this.#client.readContract({ address: key.poolManager, abi: CL_SLOT0_ABI, functionName: \"getSlot0\", args: [poolInfo.id] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getFeeGrowthGlobals\", args: [poolInfo.id] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getPoolTickInfo\", args: [poolInfo.id, tickLower] }),\n this.#client.readContract({ address: key.poolManager, abi: CL_POOL_VIEWS_ABI, functionName: \"getPoolTickInfo\", args: [poolInfo.id, tickUpper] }),\n ]);\n const amounts = amountsForLiquidity(sqrtPriceX96, tickLower, tickUpper, liquidity, false);\n const fees = uncollectedFees({\n liquidity,\n tickLower,\n tickUpper,\n currentTick,\n feeGrowthGlobal0X128: feeGrowthGlobal0,\n feeGrowthGlobal1X128: feeGrowthGlobal1,\n lower,\n upper,\n feeGrowthInside0LastX128: feeGrowthInside0Last,\n feeGrowthInside1LastX128: feeGrowthInside1Last,\n });\n out.push({\n id: `cl:${tokenId}`,\n tokenId,\n pool: poolInfo,\n range: { type: \"CL\", tickLower, tickUpper },\n liquidity,\n amount0: amounts.amount0,\n amount1: amounts.amount1,\n feesOwed0: fees.fees0,\n feesOwed1: fees.fees1,\n inRange: currentTick >= tickLower && currentTick < tickUpper,\n source: \"live\",\n });\n }\n return out;\n }\n\n async #listBinPositions(owner: Address, fromBlock: bigint, only?: PoolInfo): Promise<readonly PositionInfo[]> {\n const positionManager = this.chain.contracts.binPositionManager;\n if (positionManager === undefined) return [];\n const logs = await this.#client.getLogs({\n address: positionManager,\n event: BIN_POSM_VIEWS_ABI[2],\n args: { to: owner },\n fromBlock,\n toBlock: \"latest\",\n });\n const candidates = [...new Set(logs.flatMap((log) => (log.args.ids ?? []) as readonly bigint[]))];\n /* Group the held bins by pool. */\n const byPool = new Map<string, { key: PoolKey; bins: { binId: number; shares: bigint }[] }>();\n for (const tokenId of candidates) {\n const shares = await this.#client.readContract({ address: positionManager, abi: BIN_POSM_VIEWS_ABI, functionName: \"balanceOf\", args: [owner, tokenId] });\n if (shares === 0n) continue;\n const [key, binId] = await this.#client.readContract({ address: positionManager, abi: BIN_POSM_VIEWS_ABI, functionName: \"positions\", args: [tokenId] });\n const id = poolKeyToId(key);\n const entry = byPool.get(id) ?? { key, bins: [] };\n entry.bins.push({ binId, shares });\n byPool.set(id, entry);\n }\n const out: PositionInfo[] = [];\n for (const [poolId, { key, bins }] of byPool) {\n const poolInfo = await this.#poolInfoFor(key, \"BIN\", only);\n if (poolInfo === null) continue;\n const [activeId] = await this.#client.readContract({ address: key.poolManager, abi: BIN_SLOT0_ABI, functionName: \"getSlot0\", args: [poolId as PoolId] });\n let amount0 = 0n;\n let amount1 = 0n;\n let liquidity = 0n;\n const sortedBins = [...bins].sort((a, b) => a.binId - b.binId);\n for (const bin of sortedBins) {\n const [reserveX, reserveY, , totalShares] = await this.#client.readContract({\n address: key.poolManager,\n abi: BIN_POOL_VIEWS_ABI,\n functionName: \"getBin\",\n args: [poolId as PoolId, bin.binId],\n });\n const amounts = binShareAmounts({ shares: bin.shares, totalShares, reserveX, reserveY });\n amount0 += amounts.amount0;\n amount1 += amounts.amount1;\n liquidity += bin.shares;\n }\n const first = sortedBins[0] as { binId: number };\n const last = sortedBins[sortedBins.length - 1] as { binId: number };\n out.push({\n id: `bin:${poolId}`,\n pool: poolInfo,\n range: { type: \"BIN\", activeIdDesired: activeId, binIdLower: first.binId, binIdUpper: last.binId, idSlippage: 0 },\n liquidity,\n amount0,\n amount1,\n /* Bin fees compound into the bins' reserves; they are inside amount0/amount1, never a separate figure. */\n feesOwed0: 0n,\n feesOwed1: 0n,\n binAmounts: sortedBins.map((bin) => ({ binId: bin.binId, amount: bin.shares })),\n inRange: sortedBins.some((bin) => bin.binId === activeId),\n source: \"live\",\n });\n }\n return out;\n }\n\n /**\n * The `PoolInfo` for a position's key: the configured one when the pool is\n * listed, else one built from the key with both tokens read off their\n * contracts. `null` when `only` names a different pool.\n */\n async #poolInfoFor(key: PoolKey, poolType: PoolType, only?: PoolInfo): Promise<PoolInfo | null> {\n const id = poolKeyToId(key);\n if (only !== undefined) return only.id.toLowerCase() === id.toLowerCase() ? only : null;\n const listed = this.#options.pools.find((candidate) => candidate.id.toLowerCase() === id.toLowerCase());\n if (listed !== undefined) return listed;\n const [token0, token1] = await Promise.all([this.getToken(key.currency0), this.getToken(key.currency1)]);\n if (token0 === null || token1 === null) return null;\n const granularity =\n poolType === \"CL\" ? { tickSpacing: readCLPoolKeyParameters(key).tickSpacing } : { binStep: readBinPoolKeyParameters(key).binStep };\n return { id, key, poolType, token0, token1, lpFeePips: key.fee, hooks: key.hooks, ...granularity };\n }\n\n /**\n * What withdrawing `percentBps` of a position returns as PRINCIPAL, rounded\n * down as the pool rounds a burn. A CL decrease also pays out the position's\n * uncollected fees (`feesOwed0/1` on the position); they are not in these\n * figures because the position manager's minimum-out check is on the\n * principal alone, and a floor that counted fees could revert an honest\n * withdrawal.\n */\n async quoteRemoveLiquidity(position: PositionInfo, percentBps: number): Promise<RemoveLiquidityQuote> {\n const override = this.#overrides.quoteRemoveLiquidity;\n if (override !== undefined) return override(position, percentBps);\n if (!Number.isInteger(percentBps) || percentBps <= 0 || percentBps > 10_000) {\n throw new RangeError(`[@latchprotocol/widgets] percentBps must be an integer in (0, 10000]: ${percentBps}`);\n }\n const { pool } = position;\n if (position.range.type === \"CL\") {\n const state = await this.getPoolState(pool);\n const liquidity = (position.liquidity * BigInt(percentBps)) / 10_000n;\n const amounts = amountsForLiquidity(state.sqrtPriceX96 as bigint, position.range.tickLower, position.range.tickUpper, liquidity, false);\n return { position, percentBps, amount0: amounts.amount0, amount1: amounts.amount1, source: \"live\" };\n }\n const held = position.binAmounts ?? [];\n let amount0 = 0n;\n let amount1 = 0n;\n for (const bin of held) {\n const [reserveX, reserveY, , totalShares] = await this.#client.readContract({\n address: pool.key.poolManager,\n abi: BIN_POOL_VIEWS_ABI,\n functionName: \"getBin\",\n args: [pool.id, bin.binId],\n });\n const amounts = binShareAmounts({ shares: (bin.amount * BigInt(percentBps)) / 10_000n, totalShares, reserveX, reserveY });\n amount0 += amounts.amount0;\n amount1 += amounts.amount1;\n }\n return { position, percentBps, amount0, amount1, source: \"live\" };\n }\n\n async buildRemoveLiquidity(\n request: RemoveLiquidityExecutionRequest,\n ): Promise<WidgetTransactionRequest> {\n const account = await this.getAccount();\n if (account === null) throw new WalletNotConnectedError(\"remove liquidity\");\n const { position } = request;\n\n if (position.range.type === \"CL\") {\n const positionManager = requireContract(\n this.chain,\n \"clPositionManager\",\n \"decrease a concentrated-liquidity position\",\n );\n if (position.tokenId === undefined) {\n throw new UnsupportedOperationError(\n \"buildRemoveLiquidity\",\n \"a CL position must carry its ERC-721 tokenId\",\n );\n }\n const liquidity = (position.liquidity * BigInt(request.percentBps)) / 10_000n;\n const call = buildCLDecreaseCall({\n positionManager,\n poolKey: position.pool.key,\n tokenId: position.tokenId,\n liquidity,\n amount0Min: request.amount0Min,\n amount1Min: request.amount1Min,\n recipient: request.recipient,\n owner: account,\n deadline: request.deadline,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Remove ${request.percentBps / 100}% of position #${position.tokenId}`,\n source: \"live\",\n };\n }\n\n const positionManager = requireContract(\n this.chain,\n \"binPositionManager\",\n \"remove liquidity from a bin pool\",\n );\n const binAmounts = position.binAmounts;\n if (binAmounts === undefined || binAmounts.length === 0) {\n throw new UnsupportedOperationError(\n \"buildRemoveLiquidity\",\n \"a bin burn needs the per-bin share amounts held by the position\",\n );\n }\n const call = buildBinRemoveCall({\n positionManager,\n poolKey: position.pool.key,\n amount0Min: request.amount0Min,\n amount1Min: request.amount1Min,\n ids: binAmounts.map((entry) => entry.binId),\n amounts: binAmounts.map(\n (entry) => (entry.amount * BigInt(request.percentBps)) / 10_000n,\n ),\n from: account,\n recipient: request.recipient,\n deadline: request.deadline,\n ...(request.hookData ? { hookData: request.hookData } : {}),\n });\n return {\n to: call.to,\n data: call.data,\n value: call.value,\n summary: `Remove ${request.percentBps / 100}% of a bin position`,\n source: \"live\",\n };\n }\n\n /**\n * Requires at least one launch guard. A chain with neither is \"no launchpad\n * here\", signalled the way every missing contract is: `ChainConfigError`\n * naming `launchGuardHook`, which `isLaunchpadNotConfigured` recognises.\n */\n #requireAnyGuard(usedFor: string): void {\n const { launchGuardHook, binLaunchGuardHook } = this.chain.contracts;\n if (launchGuardHook === undefined && binLaunchGuardHook === undefined) {\n requireContract(this.chain, \"launchGuardHook\", usedFor);\n }\n }\n\n /**\n * Every configured pool whose key names one of the chain's launch guards:\n * CL pools naming `launchGuardHook`, Bin pools naming `binLaunchGuardHook`.\n *\n * There is no on-chain enumeration of launches any more than there is of\n * pools, so the candidate set is the pool list the host supplied. Throws\n * `ChainConfigError` when no guard address is configured, which is how a\n * caller distinguishes \"no launchpad on this chain\" from \"no launches yet\".\n */\n async listLaunches(): Promise<readonly LaunchInfo[]> {\n this.#requireAnyGuard(\"read a launch schedule\");\n const candidates = this.#options.pools.filter((pool) => this.#guardFor(pool) !== null);\n const launches = await Promise.all(candidates.map((pool) => this.#readLaunch(pool)));\n return launches.filter((launch): launch is LaunchInfo => launch !== null);\n }\n\n async getLaunch(poolId: PoolId): Promise<LaunchInfo | null> {\n this.#requireAnyGuard(\"read a launch schedule\");\n const pool = this.#options.pools.find((candidate) => candidate.id === poolId);\n if (pool === undefined) {\n throw new UnsupportedOperationError(\n \"getLaunch\",\n `pool ${poolId} is not in the configured pool list. The singleton has no pool ` +\n \"enumeration, so the widget can only read pools the host declared.\",\n );\n }\n if (this.#guardFor(pool) === null) return null;\n return this.#readLaunch(pool);\n }\n\n /**\n * The pools a `LaunchpadKitV2` launch opened for `token`, read from the kit's\n * `legsOf(token)` and then from the guards, in leg order.\n *\n * Every leg's pool must be in the host's pool list — the kit knows the ids,\n * not the keys, and a pool the host has not declared cannot be quoted or\n * swapped through anyway. A missing one is an error naming the id, not a\n * shorter list.\n */\n async getLaunchesForToken(token: Address): Promise<readonly LaunchInfo[]> {\n const kit = requireContract(this.chain, \"launchpadKitV2\", \"look a launch up by its token\");\n const poolIds = await this.#client.readContract({\n address: kit,\n abi: LAUNCHPAD_KIT_V2_ABI,\n functionName: \"legsOf\",\n args: [token],\n });\n if (poolIds.length === 0) return [];\n const missing = poolIds.filter((id) => this.#options.pools.every((pool) => pool.id !== id));\n if (missing.length > 0) {\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `the kit lists ${poolIds.length} pool(s) for ${token} but ${missing.length} of them ` +\n `(${missing.join(\", \")}) are not in the configured pool list. Declare them (the pool ` +\n \"manager's Initialize log carries the key) so the widget can read and route through them.\",\n );\n }\n const unguarded = poolIds.filter((id) => {\n const pool = this.#options.pools.find((candidate) => candidate.id === id) as PoolInfo;\n return this.#guardFor(pool) === null;\n });\n if (unguarded.length > 0) {\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `${unguarded.length} of the kit's pools for ${token} (${unguarded.join(\", \")}) name a launch guard ` +\n \"this chain config does not declare. Set `contracts.launchGuardHook` (CL) and \" +\n \"`contracts.binLaunchGuardHook` (Bin) to the kit's guards; a launch cannot be shown with a leg missing.\",\n );\n }\n const launches = await Promise.all(\n poolIds.map(async (id) => {\n const pool = this.#options.pools.find((candidate) => candidate.id === id) as PoolInfo;\n const launch = await this.#readLaunch(pool);\n if (launch === null) {\n // The kit only records legs it configured itself, so an unclaimed guard record here\n // means the guard and the kit disagree - say so rather than drop the leg.\n throw new UnsupportedOperationError(\n \"getLaunchesForToken\",\n `the kit lists pool ${id} for ${token} but its guard has no launch record for it`,\n );\n }\n return launch;\n }),\n );\n return launches;\n }\n\n /**\n * Which generation a launch hook is, by configuration first, then the SDK\n * address book, then the hook's own `CLOCK_MODE()` (a revert means the\n * block-numbered build). A transport failure throws; it is never a revert.\n */\n async #launchClock(hook: Address, poolType: PoolType = \"CL\"): Promise<DurationClock> {\n if (poolType === \"CL\") {\n const configured = this.chain.contracts.launchGuardHookClock;\n if (configured !== undefined) return configured;\n }\n const deployment = getDeployment(this.chain.chainId);\n if (poolType === \"CL\" && deployment?.launchGuardHook && isAddressEqual(deployment.launchGuardHook, hook)) {\n const clock = deployment.durationClocks.launchGuardHook;\n if (clock !== null) return clock;\n }\n const v2 = deployment?.launchpadV2;\n if (v2 !== undefined) {\n const known = poolType === \"CL\" ? v2.clLaunchGuardHook : v2.binLaunchGuardHook;\n if (known !== null && isAddressEqual(known, hook)) return \"timestamp\";\n }\n try {\n const { data } = await this.#client.call({ to: hook, data: CLOCK_MODE_CALLDATA });\n if (data === undefined || data === \"0x\") return \"contract-block\";\n const [mode] = decodeAbiParameters([{ type: \"string\" }], data);\n if (mode === TIMESTAMP_CLOCK_MODE) return \"timestamp\";\n throw new UnsupportedOperationError(\"getLaunch\", `hook ${hook} reports an unknown CLOCK_MODE \"${mode}\"`);\n } catch (error) {\n if (error instanceof BaseError && error.walk((x: unknown) => x instanceof ExecutionRevertedError) !== null) {\n return \"contract-block\";\n }\n throw error;\n }\n }\n\n async #readLaunch(pool: PoolInfo): Promise<LaunchInfo | null> {\n const bound = this.#guardFor(pool);\n if (bound === null) return null;\n const hook = bound.hook;\n const durationClock = await this.#launchClock(hook, bound.poolType);\n if (bound.poolType === \"BIN\" && durationClock !== \"timestamp\") {\n throw new UnsupportedOperationError(\n \"getLaunch\",\n `BinLaunchGuardHook ${hook} answers as a block-numbered build; no such build exists, so this is not a Bin launch guard.`,\n );\n }\n /* Both guards return the same `Launch` struct; the Bin ABI is the timestamp shape. */\n const abi = bound.poolType === \"CL\" ? launchGuardAbiFor(durationClock) : BIN_LAUNCH_GUARD_HOOK_ABI;\n const raw = await this.#client.readContract({\n address: hook,\n abi,\n functionName: \"getLaunch\",\n args: [pool.id],\n });\n const guard = decodeLaunchGuard(raw as unknown as RawLaunchGuard, durationClock);\n if (!isLaunchConfigured(guard)) return null;\n\n const [currentFeePips, clock] = await Promise.all([\n this.#client.readContract({\n address: hook,\n abi,\n functionName: \"currentFee\",\n args: [pool.id],\n }),\n /* \"Now\" on the HOOK's clock. The timestamp build compares with\n block.timestamp. The block-numbered build compares with the EVM's\n block.number, which on an Arbitrum chain (Robinhood, 4663) is\n Ethereum's block number while the RPC head is the L2 block; against\n the RPC head every unopened launch rendered as settled. */\n readContractClock(this.#client, this.chain.chainId),\n ]);\n const readAt = durationClock === \"timestamp\" ? clock.timestamp : clock.contractBlockNumber;\n\n const [launchToken, quoteToken] = guard.launchTokenIsCurrency0\n ? [pool.token0, pool.token1]\n : [pool.token1, pool.token0];\n\n return {\n poolId: pool.id,\n pool,\n hook,\n launchToken,\n quoteToken,\n guard,\n currentFeePips: Number(currentFeePips),\n readAt,\n source: \"live\",\n };\n }\n\n async sendTransaction(request: WidgetTransactionRequest): Promise<Hex> {\n const wallet = this.#options.wallet;\n if (wallet === undefined) throw new WalletNotConnectedError(\"send a transaction\");\n return wallet.sendTransaction({\n to: request.to,\n data: request.data,\n value: request.value,\n });\n }\n\n /**\n * The clock the next block will carry, as closely as the RPC can say: the\n * later of the PENDING block's timestamp (anvil and geth-style nodes compute\n * the next block's; an RPC without one refuses or echoes the latest) and the\n * latest block's. See `nextBlockClock` for why the pending read matters.\n */\n async getBlockTimestamp(): Promise<bigint> {\n const [pending, latest] = await Promise.allSettled([\n this.#client.getBlock({ blockTag: \"pending\" }),\n this.#client.getBlock({ blockTag: \"latest\" }),\n ]);\n const clock = nextBlockClock(\n pending.status === \"fulfilled\" ? pending.value.timestamp : null,\n latest.status === \"fulfilled\" ? latest.value.timestamp : null,\n );\n if (clock === null) throw latest.status === \"rejected\" ? latest.reason : new Error(\"no block timestamp could be read\");\n return clock;\n }\n\n async waitForTransaction(hash: Hex): Promise<TransactionOutcome> {\n const receipt = await this.#client.waitForTransactionReceipt({ hash });\n return {\n hash,\n status: receipt.status === \"success\" ? \"success\" : \"reverted\",\n blockNumber: receipt.blockNumber,\n source: \"live\",\n };\n }\n}\n\n/** Creates the live, viem-backed adapter. */\nexport function createViemAdapter(options: ViemAdapterOptions): ProtocolAdapter {\n return new ViemProtocolAdapter(options);\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Headless readers for the lock widgets: one pool's position locks or one\n * token's locks, read through the MIT SDK (`@latchprotocol/sdk/lock`), plus\n * the chain clock their countdowns run on.\n *\n * No provider is required: a lock badge is read-only and takes a viem\n * `PublicClient` directly, so a host can drop it beside any pool without the\n * swap stack. A `null` lock address (the chain has no address for it) leaves the\n * resource `idle`; the component says \"coming soon\" rather than reading.\n * The loaders themselves live in `../locks/fetch.ts`, React-free.\n */\n\nimport { useEffect, useState } from \"react\";\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { advanceChainNow, type LpLockerSource } from \"../locks/model.js\";\nimport {\n DEFAULT_NATIVE,\n fetchPoolLocks,\n fetchTokenLocks,\n poolLocksEnabled,\n type NativeCurrencyMeta,\n type PoolLocksData,\n type TokenLocksData,\n} from \"../locks/fetch.js\";\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\n\nexport { fetchPoolLocks, fetchTokenLocks, poolLocksEnabled, type LocksReadOptions, type NativeCurrencyMeta, type PoolLocksData, type TokenLocksData } from \"../locks/fetch.js\";\n\nexport interface UseLocksOptions {\n readonly native?: NativeCurrencyMeta;\n /** Re-read interval; default 60 s. 0 disables polling. */\n readonly refetchIntervalMs?: number;\n /** The protocol's LP lockers: their permanent liquidity is read and counted. */\n readonly lp?: LpLockerSource;\n}\n\n/** Every lock in one pool, as a React resource. See {@link fetchPoolLocks}. */\nexport function usePoolLocks(\n client: PublicClient,\n positionLock: Address | null,\n poolId: Hex,\n options: UseLocksOptions = {},\n): AsyncResource<PoolLocksData> {\n const native = options.native ?? DEFAULT_NATIVE;\n const lp = options.lp ?? {};\n return useAsyncResource(\n () => fetchPoolLocks(client, positionLock, poolId, { native, lp }),\n [client, positionLock, poolId, native.symbol, native.decimals, lp.lpLocker, lp.binLpLocker, lp.poolType, lp.lpLockerFromBlock, (lp.lpLockerTokenIds ?? []).join(\",\")],\n { enabled: poolLocksEnabled(positionLock, lp), refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n\n/** Every lock of one token, as a React resource. See {@link fetchTokenLocks}. */\nexport function useTokenLocks(\n client: PublicClient,\n tokenLock: Address | null,\n token: Address,\n options: UseLocksOptions = {},\n): AsyncResource<TokenLocksData> {\n const native = options.native ?? DEFAULT_NATIVE;\n const lp = options.lp ?? {};\n const hasLp = !!lp.lpLocker || !!lp.binLpLocker;\n return useAsyncResource(\n () => fetchTokenLocks(client, tokenLock, token, { native, lp }),\n [client, tokenLock, token, native.symbol, native.decimals, lp.lpLocker, lp.binLpLocker, lp.lpLockerFromBlock, (lp.lpLockerTokenIds ?? []).join(\",\")],\n { enabled: tokenLock !== null || hasLp, refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n\n/**\n * The chain's `block.timestamp` now: `chainNow` as read, advanced by the\n * local clock once a second. `null` until there is a read.\n */\nexport function useChainClock(chainNow: bigint | null, readAtMs: number | null): bigint | null {\n const [nowMs, setNowMs] = useState(() => Date.now());\n useEffect(() => {\n if (chainNow === null) return;\n const id = setInterval(() => setNowMs(Date.now()), 1000);\n return () => clearInterval(id);\n }, [chainNow]);\n if (chainNow === null || readAtMs === null) return null;\n return advanceChainNow(chainNow, readAtMs, nowMs);\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Token trust: the pure half of `TokenTrustPanel`.\n *\n * Turns the SDK's `readTokenTrust` result into labelled rows, each carrying\n * the words (from `@latchprotocol/sdk/trust`'s formatters, so every surface\n * says the same thing) and the contract each figure came from (name and\n * address, linkable; no view names or block numbers in user copy — owner rule\n * 2026-09-27). Nothing is added that was not read; nothing says \"safe\".\n */\n\nimport type { Address, Hex } from \"viem\";\nimport {\n describeCreatorTax,\n describeLaunch,\n describeLiquidity,\n describeLpFee,\n describeProtocolFee,\n describeRegistry,\n describeTokenLocks,\n formatTrustSource,\n summarizeTokenTrust,\n type PoolTrust,\n type TokenTrust,\n type TokenTrustSummary,\n type TrustLine,\n type TrustSource,\n type TrustTone,\n} from \"@latchprotocol/sdk/trust\";\nimport { shareBarFromBps, tokenShareBar, type ShareBarView } from \"../locks/model.js\";\n\nexport interface TrustRowView {\n readonly key: string;\n readonly label: string;\n readonly headline: string;\n readonly detail: string | null;\n readonly tone: TrustTone;\n /** One line per source: \"LatchTokenLock 0x12ab…cdef\". */\n readonly provenance: readonly string[];\n /** The same sources, for linking each contract to an explorer. */\n readonly sources: readonly TrustSource[];\n /** A locked-share bar for the rows that measure one (liquidity, token locks); `null` otherwise. */\n readonly share?: ShareBarView | null;\n}\n\nexport interface TrustPoolView {\n readonly poolId: Hex;\n readonly title: string;\n /** How the pool was found, in words. */\n readonly foundBy: string;\n readonly rows: readonly TrustRowView[];\n}\n\nexport interface TokenTrustView {\n readonly summary: TokenTrustSummary;\n readonly launch: TrustRowView;\n readonly tokenLocks: TrustRowView;\n readonly creatorTax: TrustRowView;\n readonly pools: readonly TrustPoolView[];\n /** Pools found but not described, one sentence each. */\n readonly failedPools: readonly string[];\n /** Which pools are listed, and that the list is not every pool of the token. */\n readonly discoveryNote: string;\n readonly readAtNote: string;\n}\n\ntype Sectionish = { readonly status: string; readonly sources?: readonly TrustSource[]; readonly source?: TrustSource | null };\n\nfunction sourcesOf(s: Sectionish): readonly TrustSource[] {\n if (s.status === \"read\") return s.sources ?? [];\n if (s.status === \"error\" && s.source) return [s.source];\n return [];\n}\n\nfunction row(key: string, label: string, line: TrustLine, sources: readonly TrustSource[], t: Pick<TokenTrust, \"readAt\">): TrustRowView {\n return { key, label, headline: line.headline, detail: line.detail, tone: line.tone, provenance: sources.map((s) => formatTrustSource(s, t.readAt).split(\" · \")[0] ?? s.contract), sources };\n}\n\nconst ORIGIN_WORDS: Record<PoolTrust[\"origins\"][number], string> = {\n \"launch-leg\": \"a Kit v2 launch leg\",\n \"lp-locker\": \"an LP-locker lock\",\n \"position-lock\": \"a LatchPositionLock time lock\",\n given: \"this page's pool list\",\n};\n\nfunction joinWords(words: readonly string[]): string {\n if (words.length <= 1) return words[0] ?? \"\";\n return `${words.slice(0, -1).join(\", \")} and ${words[words.length - 1]}`;\n}\n\n/** Symbols the host resolved, by lowercase address; the short address otherwise. */\nexport type SymbolBook = Readonly<Record<string, string>>;\n\nconst labelOf = (book: SymbolBook, a: Address): string => book[a.toLowerCase()] ?? `${a.slice(0, 6)}…${a.slice(-4)}`;\n\nfunction poolView(p: PoolTrust, t: TokenTrust, book: SymbolBook): TrustPoolView {\n const rows: TrustRowView[] = [\n {\n ...row(\"liquidity\", \"Liquidity locks\", describeLiquidity(p.liquidity, p.kind), sourcesOf(p.liquidity), t),\n share:\n p.liquidity.status !== \"read\" || !p.liquidity.measurable\n ? null\n : p.kind === \"Bin\"\n ? shareBarFromBps([{ key: \"permanent\", label: \"Locked permanently (LP locker)\", bps: p.liquidity.lockedActiveBps }], \"of the active bin\")\n : shareBarFromBps(\n [\n { key: \"permanent\", label: \"Locked permanently (LP locker)\", bps: p.liquidity.permanentActiveBps },\n { key: \"time\", label: \"Time-locked until a date\", bps: p.liquidity.timeLockedActiveBps },\n ],\n \"of active liquidity\",\n ),\n },\n row(\"lp-fee\", \"LP fee\", describeLpFee(p.lpFee), p.lpFee.kind === \"error\" ? [] : p.lpFee.source === null ? [] : [p.lpFee.source], t),\n row(\"protocol-fee\", \"Protocol fee\", describeProtocolFee(p.protocolFee), sourcesOf(p.protocolFee), t),\n ];\n if (p.tax.status !== \"not-a-launch-pool\") rows.push(row(\"tax\", \"Creator tax\", describeCreatorTax(p.tax, t.readAt.chainNow), sourcesOf(p.tax), t));\n rows.push(row(\"registry\", \"Hook in LatchRegistry\", describeRegistry(p.registry), p.registry.status === \"no-hook\" ? [] : sourcesOf(p.registry), t));\n return {\n poolId: p.poolId,\n title: `${t.symbol} / ${labelOf(book, p.pairedWith)} · ${p.kind} pool`,\n foundBy: `Found through ${joinWords(p.origins.map((o) => ORIGIN_WORDS[o]))}.`,\n rows,\n };\n}\n\n/** The token-level creator tax: from the launch, then its legs. */\nfunction creatorTaxRow(t: TokenTrust): TrustRowView {\n const launch = t.launch;\n if (launch.status === \"not-configured\") {\n return row(\"tax\", \"Creator tax\", { headline: \"Coming soon\", detail: \"Latch launches are coming soon on this chain, so there is no creator tax to read.\", tone: \"missing\" }, [], t);\n }\n if (launch.status === \"error\") {\n return row(\"tax\", \"Creator tax\", { headline: \"Could not be read\", detail: `The launch read failed: ${launch.message}.`, tone: \"error\" }, sourcesOf(launch), t);\n }\n if (launch.launch === null) {\n return row(\"tax\", \"Creator tax\", { headline: \"Not a Latch launch\", detail: \"This token was not launched on Latch, so no Latch creator tax applies to it.\", tone: \"neutral\" }, sourcesOf(launch), t);\n }\n const legs = t.pools.filter((p) => p.origins.includes(\"launch-leg\") && p.tax.status !== \"not-a-launch-pool\");\n if (legs.length === 0) {\n return row(\"tax\", \"Creator tax\", { headline: \"Could not be read\", detail: \"No launch pool of this token could be described, so its tax was not read.\", tone: \"error\" }, sourcesOf(launch), t);\n }\n const lines = legs.map((p) => describeCreatorTax(p.tax, t.readAt.chainNow));\n const sources = legs.flatMap((p) => sourcesOf(p.tax)).filter((s, i, a) => a.findIndex((x) => x.address.toLowerCase() === s.address.toLowerCase()) === i);\n const first = lines[0]!;\n if (lines.every((l) => l.headline === first.headline && l.detail === first.detail)) {\n return row(\"tax\", \"Creator tax\", legs.length === 1 ? first : { ...first, detail: `${first.detail ?? \"\"} Same on all ${legs.length} launch pools.`.trim() }, sources, t);\n }\n return row(\"tax\", \"Creator tax\", { headline: \"Differs by pool\", detail: \"Each launch pool below carries its own terms.\", tone: lines.some((l) => l.tone === \"caution\") ? \"caution\" : \"neutral\" }, sources, t);\n}\n\n/** Pure: every row of the trust panel from one read. */\nexport function tokenTrustView(t: TokenTrust, book: SymbolBook = {}): TokenTrustView {\n const searched = t.discovery.searched.map((o) => ORIGIN_WORDS[o]);\n const discoveryNote =\n `Pools listed are those found through ${searched.length === 0 ? \"no source yet: these reads are coming soon on this chain\" : joinWords(searched)}` +\n `${t.discovery.truncated ? \", and only the first of them were read\" : \"\"}${t.discovery.positionLocksTruncated ? \" (newest position locks only)\" : \"\"}. ` +\n \"A pool of this token that no Latch launch or lock knows about is not listed.\";\n return {\n summary: summarizeTokenTrust(t),\n launch: row(\"launch\", \"Latch launch\", describeLaunch(t.launch, t.readAt), sourcesOf(t.launch), t),\n tokenLocks: {\n ...row(\"token-locks\", \"Token locks & vesting\", describeTokenLocks(t.tokenLocks, t.symbol, t.decimals), sourcesOf(t.tokenLocks), t),\n share: t.tokenLocks.status === \"read\" && t.tokenLocks.lockCount > 0 ? tokenShareBar(t.tokenLocks) : null,\n },\n creatorTax: creatorTaxRow(t),\n pools: t.pools.map((p) => poolView(p, t, book)),\n failedPools: t.failedPools.map((f) => `${f.kind} pool ${f.poolId.slice(0, 10)}… could not be described: ${f.message}.`),\n discoveryNote,\n readAtNote: \"Live from the chain. Token units, never priced. A registry listing is what the registry records, not an audit.\",\n };\n}\n","// SPDX-License-Identifier: MIT\n/**\n * Headless reader for `TokenTrustPanel`: the SDK's `readTokenTrust` for one\n * token, plus the symbols of the currencies its pools pair it with, as a React\n * resource. No provider and no wallet: a viem `PublicClient` is enough.\n */\n\nimport { zeroAddress, type Address, type Hex, type PublicClient } from \"viem\";\nimport { readTokenMeta } from \"@latchprotocol/sdk\";\nimport { readTokenTrust, type PoolKind, type TokenTrust, type TrustContracts } from \"@latchprotocol/sdk/trust\";\n\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\nimport type { SymbolBook } from \"../trust/model.js\";\n\n/** What to read. `contracts: null` means the host gave no addresses for this chain: nothing is read, and surfaces say \"coming soon\". */\nexport interface TokenTrustTarget {\n readonly token: Address;\n readonly contracts: TrustContracts | null;\n /** Pools the host knows the token trades in, beyond the ones Latch's launches and locks reveal. */\n readonly pools?: readonly { readonly poolId: Hex; readonly kind: PoolKind }[];\n /** CL LP-locker position ids from a log scan the host already made. */\n readonly lpLockerTokenIds?: readonly bigint[];\n readonly native?: { readonly symbol: string; readonly decimals: number };\n}\n\nexport interface TokenTrustData {\n readonly trust: TokenTrust;\n readonly symbols: SymbolBook;\n}\n\n/** One read of a token's trust facts, with the paired currencies' symbols. */\nexport async function fetchTokenTrust(client: PublicClient, target: TokenTrustTarget & { readonly contracts: TrustContracts }): Promise<TokenTrustData> {\n const trust = await readTokenTrust(client, {\n token: target.token,\n contracts: target.contracts,\n ...(target.pools !== undefined ? { pools: target.pools } : {}),\n ...(target.lpLockerTokenIds !== undefined ? { lpLockerTokenIds: target.lpLockerTokenIds } : {}),\n ...(target.native !== undefined ? { native: target.native } : {}),\n });\n const paired = [...new Set(trust.pools.map((p) => p.pairedWith.toLowerCase()))] as Address[];\n const nativeSymbol = target.native?.symbol ?? \"ETH\";\n const metas = await Promise.all(paired.map((a) => (a === zeroAddress ? Promise.resolve({ symbol: nativeSymbol }) : readTokenMeta(client, a).catch(() => null))));\n const symbols: Record<string, string> = {};\n paired.forEach((a, i) => {\n const m = metas[i];\n if (m) symbols[a] = m.symbol;\n });\n return { trust, symbols };\n}\n\nexport interface UseTokenTrustOptions {\n /** Re-read interval in ms; default 60,000. 0 disables polling. */\n readonly refetchIntervalMs?: number;\n}\n\n/** {@link fetchTokenTrust} as a resource: `idle` when `contracts` is `null`. */\nexport function useTokenTrust(client: PublicClient, target: TokenTrustTarget, options: UseTokenTrustOptions = {}): AsyncResource<TokenTrustData> {\n const c = target.contracts;\n const contractsKey = c === null ? \"none\" : Object.entries(c).map(([k, v]) => `${k}:${String(v ?? \"\")}`).sort().join(\"|\");\n return useAsyncResource(\n () => fetchTokenTrust(client, { ...target, contracts: c as TrustContracts }),\n [\n client,\n target.token.toLowerCase(),\n contractsKey,\n (target.pools ?? []).map((p) => `${p.kind}${p.poolId}`).join(\",\"),\n (target.lpLockerTokenIds ?? []).join(\",\"),\n target.native?.symbol,\n target.native?.decimals,\n ],\n { enabled: c !== null, refetchIntervalMs: options.refetchIntervalMs ?? 60_000 },\n );\n}\n","// SPDX-License-Identifier: MIT\n/**\n * The locker widget: its pure half.\n *\n * Input parsing (exact decimals, UTC dates), the live fee in words, the\n * transaction plan for each action (approval only when the chain says it is\n * missing, and only for exactly what the lock takes), and which actions a\n * connected wallet may take on each of its locks. The contracts enforce all\n * of this; the widget checks first so a wallet is never asked to sign a call\n * that would revert.\n */\n\nimport { parseUnits, type Address } from \"viem\";\nimport type { FeeGateTerms, PositionLockRecord, TokenLockView, VestingSchedule } from \"@latchprotocol/sdk/lock\";\n\n/* ------------------------------------------------------------------ inputs --- */\n\n/** An exact decimal amount in base units, or `null` when it is not one (never rounded). */\nexport function parseLockAmount(text: string, decimals: number): bigint | null {\n const t = text.trim().replace(/_/g, \"\");\n if (!/^\\d+(\\.\\d+)?$/.test(t)) return null;\n const frac = t.split(\".\")[1] ?? \"\";\n if (frac.length > decimals) return null;\n try {\n return parseUnits(t, decimals);\n } catch {\n return null;\n }\n}\n\n/** A `datetime-local` value (\"2027-01-31T12:00\"), read as UTC, to unix seconds; `null` when malformed. */\nexport function parseUtcInput(text: string): bigint | null {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})$/.exec(text.trim());\n if (m === null) return null;\n const ms = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]));\n return Number.isFinite(ms) ? BigInt(Math.floor(ms / 1000)) : null;\n}\n\n/** Unix seconds to a `datetime-local` value in UTC. */\nexport function toUtcInput(seconds: bigint): string {\n return new Date(Number(seconds) * 1000).toISOString().slice(0, 16);\n}\n\n/** A whole number of days as seconds, or `null`. */\nexport function parseDays(text: string): bigint | null {\n const t = text.trim();\n if (!/^\\d+$/.test(t)) return null;\n return BigInt(t) * 86_400n;\n}\n\nexport type VestingMode = \"timelock\" | \"vesting\";\n\n/**\n * The schedule for a token lock: a time lock releases everything at `unlockAt`;\n * vesting accrues linearly from `start` over `durationDays`, nothing claimable\n * before `start + cliffDays`.\n */\nexport function lockSchedule(\n mode: VestingMode,\n input: { readonly unlockAt: bigint | null; readonly start: bigint | null; readonly cliffDays: bigint | null; readonly durationDays: bigint | null },\n): VestingSchedule | null {\n if (mode === \"timelock\") return input.unlockAt === null ? null : { start: input.unlockAt, cliff: input.unlockAt, end: input.unlockAt };\n if (input.start === null || input.cliffDays === null || input.durationDays === null) return null;\n return { start: input.start, cliff: input.start + input.cliffDays, end: input.start + input.durationDays };\n}\n\n/* --------------------------------------------------------------------- fee --- */\n\nfunction units(v: bigint, decimals: number): string {\n if (v === 0n) return \"0\";\n const base = 10n ** BigInt(decimals);\n const whole = v / base;\n const frac = (v % base).toString().padStart(decimals, \"0\").replace(/0+$/, \"\");\n return frac === \"\" ? whole.toLocaleString(\"en-US\") : `${whole.toLocaleString(\"en-US\")}.${frac}`;\n}\n\nexport interface LockerFeeView {\n /** \"0.075 ETH per lock\". */\n readonly fee: string;\n /** What the lock transaction sends for the fee (the higher of the fee and an announced increase). */\n readonly sends: string;\n /** An announced increase, in words, or `null`. */\n readonly pending: string | null;\n readonly note: string;\n}\n\n/** The live fee in words. Native units only, never a dollar figure. */\nexport function lockerFeeView(terms: Pick<FeeGateTerms, \"feeWei\" | \"pendingFee\" | \"recipient\">, native: { readonly symbol: string; readonly decimals: number }): LockerFeeView {\n const fee = `${units(terms.feeWei, native.decimals)} ${native.symbol} per lock`;\n const p = terms.pendingFee;\n const rises = p !== null && p.feeWei > terms.feeWei;\n const sendsWei = rises ? p.feeWei : terms.feeWei;\n const pending =\n p === null\n ? null\n : `${p.feeWei > terms.feeWei ? \"An increase\" : \"A change\"} to ${units(p.feeWei, native.decimals)} ${native.symbol} applies from ${new Date(Number(p.effectiveAt) * 1000).toISOString().replace(\"T\", \" \").slice(0, 16)} UTC.`;\n return {\n fee,\n sends: `${units(sendsWei, native.decimals)} ${native.symbol}`,\n pending,\n note: `Charged by the lock contract itself and paid only to its fee recipient ${terms.recipient.slice(0, 6)}…${terms.recipient.slice(-4)}.${rises ? \" The transaction sends the announced higher fee in case it applies before it mines; the contract refunds any surplus in the same call.\" : \"\"}`,\n };\n}\n\n/* -------------------------------------------------------------------- plan --- */\n\nexport interface PlanStep {\n readonly key: \"approve\" | \"lock\";\n readonly label: string;\n}\n\n/** Lock a position: approve this ONE NFT to the lock (when not already approved), then lock. */\nexport function planPositionLock(args: { readonly tokenId: bigint; readonly approved: boolean; readonly unlockAt: bigint }): PlanStep[] {\n const steps: PlanStep[] = [];\n if (!args.approved) steps.push({ key: \"approve\", label: `Approve LatchPositionLock to move position #${args.tokenId} (this NFT only)` });\n steps.push({ key: \"lock\", label: `Lock position #${args.tokenId} until ${new Date(Number(args.unlockAt) * 1000).toISOString().replace(\"T\", \" \").slice(0, 16)} UTC, paying the fee` });\n return steps;\n}\n\n/** Lock tokens: an exact `approve(lock, amount)` when the allowance is short (never for native), then lock. */\nexport function planTokenLock(args: { readonly native: boolean; readonly allowance: bigint; readonly amount: bigint; readonly amountText: string; readonly symbol: string }): PlanStep[] {\n const steps: PlanStep[] = [];\n if (!args.native && args.allowance < args.amount) steps.push({ key: \"approve\", label: `Approve LatchTokenLock for exactly ${args.amountText} ${args.symbol}` });\n steps.push({ key: \"lock\", label: `Lock ${args.amountText} ${args.symbol}, paying the fee${args.native ? \" (the amount is sent with it)\" : \"\"}` });\n return steps;\n}\n\n/* ------------------------------------------------------------ my locks --- */\n\nexport type PositionLockAction = \"collect\" | \"extend\" | \"withdraw\" | \"accept\";\nexport type TokenLockAction = \"claim\" | \"accept\";\n\nconst same = (a: string | null | undefined, b: string | null | undefined): boolean => a !== null && a !== undefined && b !== null && b !== undefined && a.toLowerCase() === b.toLowerCase();\n\n/** What `account` may do with one position lock, as the contract allows it. */\nexport function positionLockActions(r: Pick<PositionLockRecord, \"owner\" | \"pendingOwner\" | \"withdrawn\" | \"unlockAt\">, account: Address | null, now: bigint): PositionLockAction[] {\n if (r.withdrawn) return [];\n const out: PositionLockAction[] = [\"collect\"]; // permissionless; fees always go to the lock owner\n if (same(r.owner, account)) {\n out.push(\"extend\");\n if (now >= r.unlockAt) out.push(\"withdraw\");\n }\n if (same(r.pendingOwner, account)) out.push(\"accept\");\n return out;\n}\n\n/** What `account` may do with one token lock. */\nexport function tokenLockActions(l: Pick<TokenLockView, \"beneficiary\" | \"pendingBeneficiary\" | \"claimable\">, account: Address | null): TokenLockAction[] {\n const out: TokenLockAction[] = [];\n if (same(l.beneficiary, account) && l.claimable > 0n) out.push(\"claim\");\n if (same(l.pendingBeneficiary, account)) out.push(\"accept\");\n return out;\n}\n\nexport const POSITION_ACTION_LABEL: Record<PositionLockAction, string> = {\n collect: \"Collect fees\",\n extend: \"Extend\",\n withdraw: \"Withdraw\",\n accept: \"Accept lock\",\n};\n\nexport const TOKEN_ACTION_LABEL: Record<TokenLockAction, string> = {\n claim: \"Claim vested\",\n accept: \"Accept lock\",\n};\n","// SPDX-License-Identifier: MIT\n/**\n * Headless controllers for `LockerWidget`: the wallet, the live fees, the\n * connected wallet's locks, and a step runner that simulates every call with\n * its exact bytes before the wallet sees it and checks every receipt.\n *\n * The wallet is the same minimal surface `createViemAdapter` takes\n * (`WidgetWallet`: `getAccount` + `sendTransaction`), or, when none is passed,\n * the mounted `WidgetProvider`'s adapter. Reads, simulations and receipts go\n * through the viem `PublicClient` the host passes, on the lock contracts'\n * chain.\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { Address, Hex, PublicClient } from \"viem\";\nimport {\n readBeneficiaryLocks,\n readChainNow,\n readFeeGate,\n readPositionLocksOf,\n type FeeGateTerms,\n type PositionLockRecord,\n type TokenLockView,\n type UtilityCall,\n} from \"@latchprotocol/sdk/lock\";\n\nimport type { WidgetWallet } from \"../adapters/viem.js\";\nimport { useOptionalWidgetContext } from \"../context/WidgetProvider.js\";\nimport { describeError } from \"../core/errors.js\";\nimport { useAsyncResource, type AsyncResource } from \"./useAsyncResource.js\";\n\n/** The two lock contracts, from the host's address book. `null` = the chain has no address for it; surfaces render \"coming soon\". */\nexport interface LockerContracts {\n readonly positionLock: Address | null;\n readonly tokenLock: Address | null;\n}\n\n/** The wallet a locker signs with: the prop, else the provider's adapter, else none. */\nexport function useLockerWallet(wallet: WidgetWallet | undefined): WidgetWallet | null {\n const ctx = useOptionalWidgetContext();\n return useMemo(() => {\n if (wallet !== undefined) return wallet;\n const adapter = ctx?.adapter;\n if (adapter === undefined || adapter.isMock) return null;\n return {\n getAccount: () => adapter.getAccount(),\n sendTransaction: (req) => adapter.sendTransaction({ ...req, summary: \"Latch lock\", source: \"live\" }),\n };\n }, [wallet, ctx?.adapter]);\n}\n\n/** The connected account, re-read every few seconds so a wallet switch shows. */\nexport function useLockerAccount(wallet: WidgetWallet | null): AsyncResource<Address | null> {\n return useAsyncResource(() => (wallet === null ? Promise.resolve(null) : wallet.getAccount()), [wallet], { refetchIntervalMs: 4_000 });\n}\n\nexport interface LockerFees {\n readonly position: FeeGateTerms | null;\n readonly token: FeeGateTerms | null;\n}\n\n/** Each lock contract's fee terms, read live (`feeWei`, `pendingFee`, cap, recipient). */\nexport function useLockerFees(client: PublicClient, contracts: LockerContracts): AsyncResource<LockerFees> {\n return useAsyncResource(\n async () => {\n const [position, token] = await Promise.all([\n contracts.positionLock === null ? Promise.resolve(null) : readFeeGate(client, contracts.positionLock),\n contracts.tokenLock === null ? Promise.resolve(null) : readFeeGate(client, contracts.tokenLock),\n ]);\n return { position, token };\n },\n [client, contracts.positionLock, contracts.tokenLock],\n { enabled: contracts.positionLock !== null || contracts.tokenLock !== null, refetchIntervalMs: 60_000 },\n );\n}\n\nexport interface MyLocks {\n readonly positions: readonly PositionLockRecord[];\n readonly tokens: readonly TokenLockView[];\n /** The chain's `block.timestamp` when read. */\n readonly now: bigint;\n}\n\n/** Locks `account` owns or has been offered, on both contracts. */\nexport function useMyLocks(client: PublicClient, contracts: LockerContracts, account: Address | null): AsyncResource<MyLocks> {\n return useAsyncResource(\n async () => {\n const a = account as Address;\n const [now, positions, tokens] = await Promise.all([\n readChainNow(client),\n contracts.positionLock === null ? Promise.resolve([]) : readPositionLocksOf(client, contracts.positionLock, a),\n contracts.tokenLock === null ? Promise.resolve({ locks: [] as TokenLockView[] }) : readBeneficiaryLocks(client, contracts.tokenLock, a),\n ]);\n return { positions, tokens: tokens.locks, now };\n },\n [client, contracts.positionLock, contracts.tokenLock, account],\n { enabled: account !== null && (contracts.positionLock !== null || contracts.tokenLock !== null), refetchIntervalMs: 60_000 },\n );\n}\n\n/** Thrown when a mined transaction reverted: the receipt, not the hash, is the proof. */\nexport class TransactionRevertedError extends Error {\n readonly hash: Hex;\n constructor(hash: Hex) {\n super(`The transaction ${hash.slice(0, 10)}… was mined and reverted.`);\n this.name = \"TransactionRevertedError\";\n this.hash = hash;\n }\n}\n\n/**\n * One call: simulate with the exact bytes and value from `account`, send\n * through the wallet, wait for the receipt, and throw unless it succeeded.\n */\nexport async function simulateSendConfirm(client: PublicClient, wallet: WidgetWallet, account: Address, call: UtilityCall): Promise<Hex> {\n await client.call({ account, to: call.to, data: call.data, value: call.value });\n const hash = await wallet.sendTransaction({ to: call.to, data: call.data, value: call.value });\n const receipt = await client.waitForTransactionReceipt({ hash });\n if (receipt.status !== \"success\") throw new TransactionRevertedError(hash);\n return hash;\n}\n\nexport interface RunnerStep {\n readonly label: string;\n /** Built when the step starts, so it reads the chain as it is after the previous step. */\n readonly build: () => Promise<UtilityCall>;\n}\n\nexport type RunnerState =\n | { readonly k: \"idle\" }\n | { readonly k: \"running\"; readonly labels: readonly string[]; readonly active: number; readonly phase: \"simulating\" | \"signing\" | \"confirming\" }\n | { readonly k: \"done\"; readonly labels: readonly string[]; readonly hashes: readonly Hex[] }\n | { readonly k: \"failed\"; readonly labels: readonly string[]; readonly active: number; readonly message: string };\n\n/** Runs steps in order; the first failure stops the run and is described in one sentence. */\nexport function useLockerRunner(client: PublicClient, wallet: WidgetWallet | null, account: Address | null, onDone?: () => void): { state: RunnerState; run(steps: readonly RunnerStep[]): Promise<void>; reset(): void } {\n const [state, setState] = useState<RunnerState>({ k: \"idle\" });\n const busy = useRef(false);\n const run = useCallback(\n async (steps: readonly RunnerStep[]) => {\n if (busy.current) return;\n const labels = steps.map((s) => s.label);\n if (wallet === null || account === null) {\n setState({ k: \"failed\", labels, active: 0, message: \"Connect a wallet first.\" });\n return;\n }\n busy.current = true;\n const hashes: Hex[] = [];\n let i = 0;\n try {\n for (; i < steps.length; i++) {\n setState({ k: \"running\", labels, active: i, phase: \"simulating\" });\n const call = await steps[i]!.build();\n await client.call({ account, to: call.to, data: call.data, value: call.value });\n setState({ k: \"running\", labels, active: i, phase: \"signing\" });\n const hash = await wallet.sendTransaction({ to: call.to, data: call.data, value: call.value });\n setState({ k: \"running\", labels, active: i, phase: \"confirming\" });\n const receipt = await client.waitForTransactionReceipt({ hash });\n if (receipt.status !== \"success\") throw new TransactionRevertedError(hash);\n hashes.push(hash);\n }\n setState({ k: \"done\", labels, hashes });\n onDone?.();\n } catch (error) {\n setState({ k: \"failed\", labels, active: i, message: error instanceof TransactionRevertedError ? error.message : describeError(error, \"transaction\") });\n } finally {\n busy.current = false;\n }\n },\n [client, wallet, account, onDone],\n );\n const reset = useCallback(() => setState({ k: \"idle\" }), []);\n return { state, run, reset };\n}\n"],"names":["buildUniformBinDistribution","binIdLower","binIdUpper","activeId","ids","id","xBins","yBins","lastX","lastY","shares","xAssigned","yAssigned","rawX","BIN_DISTRIBUTION_SCALE","rawY","distributionX","distributionY","NoSaleAdapterError","hasSaleAdapter","adapter","CL_MINT_PARAMS","POOL_KEY_COMPONENTS","CL_MODIFY_PARAMS","CURRENCY_PAIR","CURRENCY_PAIR_AND_ADDRESS","CURRENCY_AND_ADDRESS","sweepNativeStep","ACTIONS","encodeAbiParameters","NATIVE_CURRENCY","MSG_SENDER","BIN_ADD_LIQUIDITY_PARAMS","BIN_REMOVE_LIQUIDITY_PARAMS","poolKeyStruct","key","buildCLMintCall","args","assertTickRange","p","plan","encodeFunctionData","POSITION_MANAGER_ABI","buildCLDecreaseCall","recipient","buildBinAddCall","binCount","buildBinRemoveCall","tickLower","tickUpper","CL_SLOT0_ABI","BIN_SLOT0_ABI","Q192","CL_POOL_VIEWS_ABI","BIN_POOL_VIEWS_ABI","POOL_KEY_OUTPUT","CL_POSM_VIEWS_ABI","BIN_POSM_VIEWS_ABI","NATIVE","ViemProtocolAdapter","#options","options","#client","#overrides","wallet","address","known","token","isAddressEqual","symbol","name","decimals","ERC20_ABI","owner","pool","override","sqrtPriceX96","tick","liquidity","UnsupportedOperationError","amount","spender","permit2","requireContract","router","requirements","erc20Allowance","permit2Amount","expiration","PERMIT2_ABI","nowSeconds","expired","requirement","MAX_UINT256","MAX_UINT160","MAX_UINT48","request","contracts","candidates","quotable","results","quoter","result","quoterAbiFor","amountOut","gasEstimate","error","answered","r","first","best","a","b","lpFeePips","lpFeeUnknown","isDynamicLPFee","guardFee","#launchGuardFee","spotAmountOut","#spotAmountOut","guard","#guardFor","abi","launchGuardAbiFor","#launchClock","BIN_LAUNCH_GUARD_HOOK_ABI","fee","BaseError","x","ExecutionRevertedError","launchGuardHook","binLaunchGuardHook","tokenIn","amountIn","zeroForOne","afterFee","p2","binStep","readBinPoolKeyParameters","raw1per0","binRawPriceFromId","SCALE","scaled","account","WalletNotConnectedError","hops","#resolveHops","call","buildSwapCall","step","candidate","range","spacing","tickSpacingOf","state","getLiquidityForAmounts","getSqrtRatioAtTick","amounts","amountsForLiquidity","inRange","poolLiquidity","shareBps","distribution","takesX","share","takesY","amount0","amount1","binStepOf","y","price","quote","nativeValue","#nativeValueFor","positionManager","amount0Max","amount1Max","fromBlock","wanted","cl","bin","#listCLPositions","#listBinPositions","only","logs","log","out","tokenId","holder","feeGrowthInside0Last","feeGrowthInside1Last","poolInfo","#poolInfoFor","currentTick","feeGrowthGlobal0","feeGrowthGlobal1","lower","upper","fees","uncollectedFees","byPool","binId","poolKeyToId","entry","poolId","bins","sortedBins","reserveX","reserveY","totalShares","binShareAmounts","last","poolType","listed","token0","token1","granularity","readCLPoolKeyParameters","position","percentBps","held","binAmounts","#requireAnyGuard","usedFor","#readLaunch","launch","kit","poolIds","LAUNCHPAD_KIT_V2_ABI","missing","unguarded","hook","configured","deployment","getDeployment","clock","v2","data","CLOCK_MODE_CALLDATA","mode","decodeAbiParameters","TIMESTAMP_CLOCK_MODE","bound","durationClock","raw","decodeLaunchGuard","isLaunchConfigured","currentFeePips","readContractClock","readAt","launchToken","quoteToken","pending","latest","nextBlockClock","hash","receipt","createViemAdapter","usePoolLocks","client","positionLock","native","DEFAULT_NATIVE","lp","useAsyncResource","fetchPoolLocks","poolLocksEnabled","useTokenLocks","tokenLock","hasLp","fetchTokenLocks","useChainClock","chainNow","readAtMs","nowMs","setNowMs","useState","useEffect","advanceChainNow","sourcesOf","s","row","label","line","sources","t","formatTrustSource","ORIGIN_WORDS","joinWords","words","labelOf","book","poolView","rows","describeLiquidity","shareBarFromBps","describeLpFee","describeProtocolFee","describeCreatorTax","describeRegistry","o","creatorTaxRow","legs","lines","i","l","tokenTrustView","searched","discoveryNote","summarizeTokenTrust","describeLaunch","describeTokenLocks","tokenShareBar","f","fetchTokenTrust","target","trust","readTokenTrust","paired","nativeSymbol","metas","zeroAddress","readTokenMeta","symbols","m","useTokenTrust","c","contractsKey","k","v","parseLockAmount","text","parseUnits","parseUtcInput","ms","toUtcInput","seconds","parseDays","lockSchedule","input","units","base","whole","frac","lockerFeeView","terms","rises","sendsWei","planPositionLock","steps","planTokenLock","same","positionLockActions","now","tokenLockActions","POSITION_ACTION_LABEL","TOKEN_ACTION_LABEL","useLockerWallet","ctx","useOptionalWidgetContext","useMemo","req","useLockerAccount","useLockerFees","readFeeGate","useMyLocks","positions","tokens","readChainNow","readPositionLocksOf","readBeneficiaryLocks","TransactionRevertedError","simulateSendConfirm","useLockerRunner","onDone","setState","busy","useRef","run","useCallback","labels","hashes","describeError","reset"],"mappings":";;;;;;AAqBO,SAASA,GACdC,GACAC,GACAC,GACqB;AACrB,MAAIF,IAAaC;AACf,UAAM,IAAI,WAAW,cAAcD,CAAU,uBAAuBC,CAAU,EAAE;AAElF,QAAME,IAAgB,CAAA;AACtB,WAASC,IAAKJ,GAAYI,KAAMH,GAAYG,KAAM,EAAG,CAAAD,EAAI,KAAKC,CAAE;AAEhE,QAAMC,IAAQF,EAAI,OAAO,CAACC,MAAOA,KAAMF,CAAQ,EAAE,QAC3CI,IAAQH,EAAI,OAAO,CAACC,MAAOA,KAAMF,CAAQ,EAAE,QAE3CK,IAAQN,GACRO,IAAQ,KAAK,IAAIN,GAAUD,CAAU,GAErCQ,IAA8B,CAAA;AACpC,MAAIC,IAAY,IACZC,IAAY;AAChB,aAAWP,KAAMD,GAAK;AACpB,UAAMS,IAAOR,KAAMF,KAAYG,IAAQ,IAAIQ,IAAyB,OAAOR,CAAK,IAAI,IAC9ES,IAAOV,KAAMF,KAAYI,IAAQ,IAAIO,IAA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