@kronsdk/kron-sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/dist/index.d.ts +96 -9
- package/dist/index.js +154 -48
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/curve/cpCurve.ts","../src/native/sigscript.ts","../src/native/genesis.ts","../src/native/spend.ts","../src/native/kcc20Tx.ts","../src/native/curveCpTx.ts","../src/native/poolCpTx.ts","../src/native/poolCpV3Tx.ts","../src/native/vestingTx.ts","../src/wallet/index.ts","../src/wallet/types.ts","../src/wallet/example.ts","../src/client/index.ts","../src/client/indexerClient.ts","../src/client/registryClient.ts","../src/client/sequencerClient.ts","../src/verify/index.ts","../src/verify/tokenList.ts"],"sourcesContent":["// Virtual-reserve constant-product bonding-curve math — mirrors the curve_cp.sil covenant EXACTLY (BigInt,\n// same SCALE / ceil rules) so quotes match what the covenant enforces. The inventory model: a fixed\n// inventory is sold/bought at a constant-product price using a virtual KAS reserve; nothing is minted or burned.\nexport const SCALE = 1_000_000n; // 1e6 sompi = 0.01 KAS — the KAS step used in the CP invariant\n// Fee/payment outputs can't be sub-dust (KIP-9 storage mass ≈ C/value), so on-chain fee outputs are padded to\n// this floor; quotes reflect the padded amount so the displayed total/net matches what's actually paid.\nexport const FEE_OUT_MIN = 20_000_000n; // 0.2 TKAS\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\n// int64-safety ceiling on the curve UTXO value (sompi) — mirrors curve_cp.sil MAX_KAS. A buy may overbuy PAST\n// graduationKas (excess → LP at graduation); this is the only upper bound on a single buy. 9e14 is essentially\n// the int64 ceiling: the covenant's graduation `gradFee·10000` peaks at ~9e18 (~2.5% under 2^63).\nexport const MAX_KAS = 900_000_000_000_000n; // 9e14 sompi = 9,000,000 TKAS\n\n/** Live curve state for quoting. realKas/graduationKas are sompi; vKas is in SCALE units; tokenReserve whole. */\nexport type CpState = {\n realKas: bigint; // curve UTXO value (sompi) = KAS raised so far\n tokenReserve: bigint; // curve inventory remaining (whole tokens)\n vKas: bigint; // virtual KAS reserve (SCALE units) — sets the opening price\n graduationKas: bigint; // raised-KAS target (sompi) that unlocks graduation\n creatorFeeBps: bigint; // e.g. 70n\n platformFeeBps: bigint; // e.g. 30n\n};\n\nconst ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\n\n// --- slippage protection ---------------------------------------------------------------------------\n// The covenant fixes the trade's output amount into the signed tx and only enforces the constant-product\n// FLOOR (it won't let you take MORE than fair), so it does NOT stop the app from baking a WORSE-than-shown\n// amount if the curve/pool state moved (another trade landed first) or a node fed stale/bad reserves. Fetch\n// fresh state at build time and abort if the achievable output drops below the user-agreed minimum =\n// (quote they saw) − tolerance. Default 1%.\nexport const DEFAULT_SLIPPAGE_BPS = 100;\n/** Minimum acceptable output after a slippage tolerance (bps). `out` is tokenOut (buy) or net KAS (sell). */\nexport const minOutWithSlippage = (out: bigint, bps: number): bigint => out - (out * BigInt(Math.max(0, Math.round(bps)))) / 10000n;\n\nexport type CpBuyQuote = { kasIn: bigint; tokenOut: bigint; creatorFee: bigint; platformFee: bigint; fee: bigint; total: bigint; newRealKas: bigint; newTokenReserve: bigint };\nexport type CpSellQuote = { tokenIn: bigint; kasOut: bigint; creatorFee: bigint; platformFee: bigint; fee: bigint; net: bigint; newRealKas: bigint; newTokenReserve: bigint };\n\n/** Buy: spend `kasInSompi` into the reserve (floored to a SCALE step) → tokenOut, plus the fee on top. */\nexport function quoteCpBuy(s: CpState, kasInSompi: bigint): CpBuyQuote | null {\n const ki = kasInSompi / SCALE; // floor to a whole SCALE step (the covenant requires kasIn % SCALE == 0)\n const kasIn = ki * SCALE;\n if (kasIn <= 0n) return null;\n const newRealKas = s.realKas + kasIn;\n if (newRealKas > MAX_KAS) return null; // overbuy past graduationKas is allowed; only the int64 ceiling caps a buy\n const ru = s.realKas / SCALE;\n const K = (s.vKas + ru) * s.tokenReserve;\n const newToken = ceilDiv(K, s.vKas + ru + ki); // pool keeps ≥ the CP tokens (floor check passes)\n const tokenOut = s.tokenReserve - newToken;\n if (tokenOut <= 0n) return null;\n const creatorFee = padFee((kasIn * s.creatorFeeBps) / 10000n);\n const platformFee = padFee((kasIn * s.platformFeeBps) / 10000n);\n const fee = creatorFee + platformFee;\n return { kasIn, tokenOut, creatorFee, platformFee, fee, total: kasIn + fee, newRealKas, newTokenReserve: newToken };\n}\n\n/** Sell: return `tokenIn` tokens to inventory → kasOut sompi (a SCALE step), minus the fee. */\nexport function quoteCpSell(s: CpState, tokenIn: bigint): CpSellQuote | null {\n if (tokenIn <= 0n) return null;\n const ru = s.realKas / SCALE;\n const K = (s.vKas + ru) * s.tokenReserve;\n const newToken = s.tokenReserve + tokenIn;\n const minKasUnits = ceilDiv(K, newToken) - s.vKas; // min units the pool must keep so it isn't drained\n const newKasUnits = minKasUnits < 0n ? 0n : minKasUnits;\n const kasOutUnits = ru - newKasUnits;\n if (kasOutUnits <= 0n) return null; // sell too small to refund a whole SCALE step\n const kasOut = kasOutUnits * SCALE;\n const creatorFee = padFee((kasOut * s.creatorFeeBps) / 10000n);\n const platformFee = padFee((kasOut * s.platformFeeBps) / 10000n);\n const fee = creatorFee + platformFee;\n return { tokenIn, kasOut, creatorFee, platformFee, fee, net: kasOut - fee, newRealKas: s.realKas - kasOut, newTokenReserve: newToken };\n}\n\n/** Marginal price in sompi per token: (vKas + realKas/SCALE) · SCALE / tokenReserve. */\nexport function cpPrice(s: CpState): number {\n if (s.tokenReserve <= 0n) return 0;\n const ru = s.realKas / SCALE;\n return Number((s.vKas + ru) * SCALE) / Number(s.tokenReserve);\n}\n\n/** Progress to graduation (0..100), measured by KAS raised vs the target. */\nexport function cpProgress(s: CpState): number {\n return s.graduationKas > 0n ? Math.min(100, (Number(s.realKas) / Number(s.graduationKas)) * 100) : 0;\n}\n\n/** Tokens sold so far (circulating from the curve) = initial inventory − current inventory. */\nexport const cpSold = (initialInventory: bigint, tokenReserve: bigint): bigint => initialInventory - tokenReserve;\n","// SilverScript signature-script argument ABI — a faithful TS port of the compiler's `build_sig_script`. A\n// covenant is spent with a P2SH input whose signature script is:\n// <encoded entrypoint args...> [<selector>] <redeemScript>\n// This module encodes the entrypoint args exactly as the compiler does, so the bytes the VM sees match what\n// `silverc` would build.\n//\n// The encoding rules (from build_sig_script / push_typed_sigscript_arg / encode_array_literal):\n// • Scalar arg / single-struct field — pushed individually (push_sigscript_arg):\n// int → addI64 (minimal CScriptNum) bool → addI64(0|1)\n// byte → addData([b]) byte[N]/pubkey/sig → addData(raw bytes)\n// A STRUCT arg pushes each field in declared order using these scalar rules.\n// • Struct-array arg (e.g. kcc20 `transfer`'s `State[]`) — COLUMN-MAJOR: for each struct field, the\n// field's value across all elements is gathered into a dynamic array and pushed as ONE item, using the\n// FIXED-WIDTH element encoding (encode_fixed_size_value): int → 8-byte LE, bool → 1 byte, byte → 1 byte,\n// byte[N] → N raw bytes. (Note the asymmetry: a scalar int field uses minimal addI64, but an int inside\n// an array column is fixed 8-byte LE.)\n// • Plain dynamic arrays — byte[] → addData(bytes); int[]/bool[]/sig[] → fixed-width-concat → addData.\n// • Selector — the entrypoint's branch index (declaration order among entrypoints) is appended via addI64,\n// UNLESS the contract has a single entrypoint (then it is omitted).\n//\n// No top-level SDK import (only `import type`) — the caller passes the loaded WASM namespace `k`, so this\n// runs unchanged in the browser and under Node.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\n\n/** 8-byte little-endian encoding of a non-negative int (encode_fixed_size_value for `int`, width 8). */\nexport function int8LE(v: bigint): Uint8Array {\n const out = new Uint8Array(8);\n let x = BigInt.asUintN(64, v);\n for (let i = 0; i < 8; i++) {\n out[i] = Number(x & 0xffn);\n x >>= 8n;\n }\n return out;\n}\n\nconst concat = (parts: Uint8Array[]): Uint8Array => {\n const len = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(len);\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n};\n\n/**\n * A SilverScript ScriptBuilder wrapper that records pushes in the compiler's order, then drains to hex.\n * Use the scalar push helpers for struct fields / scalar args and the column helpers for struct arrays,\n * then `selector()` (if multi-entrypoint) and `redeem()` last (the standard P2SH spend layout).\n */\nexport class SigScriptBuilder {\n sb: any;\n constructor(k: K) {\n this.sb = new (k as any).ScriptBuilder({ flags: { covenantsEnabled: true } });\n }\n /** int scalar (minimal CScriptNum). */\n int(v: bigint): this {\n this.sb.addI64(v);\n return this;\n }\n /** bool scalar → 1|0 via addI64 (matches push_sigscript_arg Bool). */\n bool(b: boolean): this {\n this.sb.addI64(b ? 1n : 0n);\n return this;\n }\n /** single byte → addData([b]). */\n byte(b: number): this {\n this.sb.addData(Uint8Array.of(b & 0xff));\n return this;\n }\n /** raw bytes (byte[N], pubkey, sig, byte[]) → addData. */\n data(bytes: Uint8Array): this {\n this.sb.addData(bytes);\n return this;\n }\n /** a column of N values pushed as one fixed-width-concatenated array item (encode_array_literal). */\n column(items: Uint8Array[]): this {\n this.sb.addData(concat(items));\n return this;\n }\n /** the entrypoint selector (branch index). Omit for single-entrypoint contracts. */\n selector(index: number): this {\n this.sb.addI64(BigInt(index));\n return this;\n }\n /** the P2SH redeem script (pushed last; the VM pops it, hash-checks, then runs it on the arg stack). */\n redeem(script: Uint8Array): this {\n this.sb.addData(script);\n return this;\n }\n /** finalize → signature-script hex. */\n drain(): string {\n return this.sb.drain();\n }\n}\n","// KIP-20 genesis covenant-id (the native track's identity primitive). A covenant-id `A` is assigned by\n// consensus when a covenant UTXO is first created (\"genesis\"): it is a CovenantID-keyed blake2b-256 over\n// the spending tx's first-input outpoint and the set of authorized outputs (see\n// rusty-kaspa/consensus/core/src/hashing/covenant_id.rs). A forged id raises WrongGenesisCovenantId.\n//\n// The vendored Kaspa WASM SDK already ships the consensus implementation as `covenantId(...)`, so we wrap\n// it rather than re-deriving the keyed blake2b. ONE non-obvious gotcha (cost real time to find upstream):\n// the SDK's `covenantId` only matches consensus when each authorized output's `scriptPublicKey` is passed\n// as a {version, script} object (or a ScriptPublicKey instance) — a BARE HEX STRING silently produces a\n// wrong id. `payToScriptHashScript()` returns a ScriptPublicKey instance, so pass that straight through.\n//\n// No top-level SDK import (only `import type`) so this runs in the browser (caller passes the loaded `k`)\n// and under Node. Returns/consumes covenant-ids as 32-byte big-endian hex (no 0x), the shape used across the\n// native builders and the indexer API.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\n/** SDK ScriptPublicKey instance, or a plain {version, script-hex} object. Kept loose, matching SDK style. */\ntype Spk = any;\n\n/** The genesis outpoint = the spending tx's FIRST input outpoint (`tx.inputs[0]`). */\nexport type GenesisOutpoint = { transactionId: string; index: number };\n\n/** An output the genesis outpoint authorizes for covenant-id derivation (its index + the output itself). */\nexport type AuthOutput = { index: number; value: bigint; scriptPublicKey: Spk };\n\nconst hexToBytes = (h: string): Uint8Array =>\n Uint8Array.from((h.replace(/^0x/, '').match(/../g) ?? []).map((b) => parseInt(b, 16)));\nconst bytesToHex = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * Compute the KIP-20 genesis covenant-id (32-byte hex, no 0x) for a covenant UTXO created by a tx whose\n * first input is `genesisOutpoint` and whose authorized outputs are `authOutputs`. Byte-exact with\n * consensus. Used to:\n * - bind the curve `C` ↔ its token `A` (curve_cp `init`),\n * - pre-compute the pool covenant-id `P` a graduation will assign,\n * - derive a freshly-created covenant's own id client-side before broadcast.\n */\nexport function genesisCovenantId(k: K, genesisOutpoint: GenesisOutpoint, authOutputs: AuthOutput[]): string {\n const auth = authOutputs.map((o) => ({\n index: o.index,\n // Normalize to a plain { version, script-hex } object — the form the SDK serializes to match consensus.\n // A bare hex string OR a ScriptPublicKey *instance* both yield a (different) wrong id; only this works.\n output: { value: o.value, scriptPublicKey: { version: o.scriptPublicKey.version ?? 0, script: o.scriptPublicKey.script ?? o.scriptPublicKey } },\n }));\n return (k as any).covenantId(genesisOutpoint, auth).toString();\n}\n\n/** Covenant-ids are byte[32] in the covenants; convert between the hex form and bytes for state encoding. */\nexport const covidToBytes = (covidHex: string): Uint8Array => hexToBytes(covidHex);\nexport const bytesToCovid = (u8: Uint8Array): string => bytesToHex(u8);\n\n/** The all-zero covenant-id placeholder (a curve's `tokenCovid` before `init` binds it; ZERO_COVID). */\nexport const ZERO_COVID = '00'.repeat(32);\n","// Native covenant-spend assembly — shared types + the tx-assembly layer for the native (KCC-20) builders.\n// A native action (init/buy/sell/graduate/swap) yields a `CovenantSpend`: the covenant INPUTS it spends\n// (each pre-scripted — the covenant's own transition rules authorize the spend, so no key signature) and\n// the covenant-required OUTPUTS (continuation, minted/moved token balances, fee). This module bolts on the\n// trader's funding inputs + change to make a complete Kaspa transaction.\n//\n// Production signing path: the app builds the tx here, the wallet signs only the trader's P2PK funding\n// inputs via its signPskt-equivalent bridge (see ../wallet/types.ts), and the app broadcasts — covenant\n// inputs never need a wallet signature. `toPsktJson` shapes the tx + the funding-input indices for that\n// bridge.\n//\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** A covenant UTXO being spent, already carrying its signature script (no wallet signature needed). */\nexport type CovInput = {\n transactionId: string;\n index: number;\n value: bigint;\n scriptPublicKey: Spk;\n /** the covenant signature script (hex): <args> [selector] <redeem>, or kcc20 <transfer args> <redeem>. */\n signatureScript: string;\n /** redeem script bytes (kept so a caller can re-derive / inspect the spend). */\n redeem: Uint8Array;\n /** what this input is, for assembly/debugging: 'curve' | 'minterBranch' | 'burn' | 'pool' | 'poolToken'. */\n role: string;\n};\n\n/** A covenant-required output (value + scriptPublicKey). */\nexport type CovOutput = { value: bigint; scriptPublicKey: Spk; role: string };\n\n/** A complete covenant action: the inputs it spends + the outputs it must create + computed economics. */\nexport type CovenantSpend = {\n kind: 'init' | 'initVested' | 'buy' | 'sell' | 'graduate' | 'swapKasForToken' | 'swapTokenForKas' | 'addLiquidity' | 'removeLiquidity' | 'bindLp' | 'claim' | 'claimFinal';\n inputs: CovInput[];\n outputs: CovOutput[];\n economics: Record<string, bigint>;\n /** covenant-ids this action establishes/uses (hex): the bound token `A`, a new pool `P`, the curve `C`. */\n covids?: { tokenCovid?: string; poolCovid?: string; curveCovid?: string };\n};\n\n/** A funding UTXO entry (SDK UtxoEntryReference from rpc.getUtxosByAddresses, or a plain IUtxoEntry). */\nexport type FundingEntry = any;\n\nconst SUBNET_ZERO = '0000000000000000000000000000000000000000';\n\nexport type AssembledNativeTx = {\n transaction: any;\n /** indices of inputs the trader/wallet must sign (the covenant inputs come first and are pre-scripted). */\n fundingInputIndexes: number[];\n totalIn: bigint;\n covenantOut: bigint;\n change: bigint;\n};\n\n/**\n * Assemble a complete tx: the spend's covenant inputs (pre-scripted) + the trader's funding inputs + a\n * change output. `networkFee` is caller-provided (derive from the node; KIP-9 storage mass depends on\n * output values, so the node confirms the exact fee/change at broadcast). Covenant inputs carry sigOpCount\n * 0 (no checkSig on the accept path used here); funding inputs are signed via signFundingInputs.\n */\nexport function assembleNativeTx(\n k: K,\n opts: { spend: CovenantSpend; fundingEntries: FundingEntry[]; changeAddress: string; networkFee: bigint },\n): AssembledNativeTx {\n const { spend, fundingEntries, changeAddress, networkFee } = opts;\n const kk = k as any;\n\n const covInputs = spend.inputs.map(\n (ci) =>\n new kk.TransactionInput({\n previousOutpoint: { transactionId: ci.transactionId, index: ci.index },\n signatureScript: ci.signatureScript,\n sequence: 0n,\n sigOpCount: 0,\n utxo: {\n outpoint: { transactionId: ci.transactionId, index: ci.index },\n amount: ci.value,\n scriptPublicKey: ci.scriptPublicKey,\n blockDaaScore: 0n,\n isCoinbase: false,\n },\n }),\n );\n const fundingInputs = fundingEntries.map(\n (e) => new kk.TransactionInput({ previousOutpoint: e.outpoint, signatureScript: '', sequence: 0n, sigOpCount: 1, utxo: e }),\n );\n\n const covInValue = spend.inputs.reduce((s, ci) => s + ci.value, 0n);\n const fundingTotal = fundingEntries.reduce((s, e) => s + BigInt(e.amount), 0n);\n const totalIn = covInValue + fundingTotal;\n const covenantOut = spend.outputs.reduce((s, o) => s + o.value, 0n);\n const change = totalIn - covenantOut - networkFee;\n if (change < 0n) throw new Error(`insufficient funding: need ${covenantOut + networkFee} sompi, have ${totalIn}`);\n\n const outputs = spend.outputs.map((o) => new kk.TransactionOutput(o.value, o.scriptPublicKey));\n outputs.push(new kk.TransactionOutput(change, kk.payToAddressScript(changeAddress)));\n\n const transaction = new kk.Transaction({\n version: 0,\n inputs: [...covInputs, ...fundingInputs],\n outputs,\n lockTime: 0n,\n gas: 0n,\n payload: '',\n subnetworkId: SUBNET_ZERO,\n });\n return {\n transaction,\n fundingInputIndexes: fundingInputs.map((_, i) => i + covInputs.length),\n totalIn,\n covenantOut,\n change,\n };\n}\n\n/** Sign the trader's funding inputs (P2PK) in place; covenant inputs are left untouched (pre-scripted). */\nexport function signFundingInputs(k: K, tx: any, privKey: any, fundingInputIndexes: number[]): any {\n const inputs = tx.inputs;\n for (const idx of fundingInputIndexes) {\n const sig = (k as any).createInputSignature(tx, idx, privKey);\n inputs[idx].signatureScript = new (k as any).ScriptBuilder().addData(sig).drain();\n }\n tx.inputs = inputs;\n return tx;\n}\n\n/**\n * Shape the assembled tx for a signPskt-style wallet bridge. Returns the tx JSON the wallet deserializes\n * plus the inputs it should sign (the trader's P2PK funding inputs only).\n */\nexport function toPsktJson(asm: AssembledNativeTx, sighashType = 1): { txJsonString: string; signInputs: { index: number; sighashType: number }[] } {\n return {\n txJsonString: asm.transaction.serializeToSafeJSON(),\n signInputs: asm.fundingInputIndexes.map((index) => ({ index, sighashType })),\n };\n}\n\n/**\n * The local side of a signPskt-style wallet bridge: deserialize a tx (Safe JSON), sign ONLY the listed\n * inputs with `privKey` (the user's P2PK inputs — funding, or the co-present presence input that authorizes\n * a sell/transfer of an address-owned token), reserialize to Safe JSON. Covenant inputs (not listed) are\n * left untouched: their transition rules — or the presence-based ownership check against a co-present\n * signed P2PK input — authorize them, so the wallet never signs a covenant P2SH input directly. This is\n * exactly what an extension wallet's native `signPskt({ txJsonString, options: { signInputs } })` does; use\n * this function to emulate that bridge with a raw key (e.g. for a backend bot holding its own key).\n */\nexport function signPsktWithKey(k: K, txJsonString: string, signInputs: { index: number }[], privKey: any): string {\n const kk = k as any;\n const tx = kk.Transaction.deserializeFromSafeJSON(txJsonString);\n const inputs = tx.inputs;\n for (const { index } of signInputs) {\n const sig = kk.createInputSignature(tx, index, privKey);\n inputs[index].signatureScript = new kk.ScriptBuilder().addData(sig).drain();\n }\n tx.inputs = inputs;\n return tx.serializeToSafeJSON();\n}\n","// KCC-20 native covenant-token transaction builder — wires kcc20.sil into Kaspa transactions. NO rollup.\n//\n// A token balance is a covenant P2SH UTXO whose redeem script carries a fixed-width 46-byte state region:\n// off 0 : 0x20 <ownerIdentifier:32> off 33: 0x01 <identifierType:1>\n// off 35: 0x08 <amount: 8-byte LE> off 44: 0x01 <isMinter:1>\n// Everything outside the region is identical for a given (maxIns,maxOuts), so a new-balance redeem script\n// is produced by SPLICING — no recompile at spend time.\n//\n// `transfer(State[] newStates, sig[] sigs, byte[] witnesses)` is the single entrypoint (no selector). It\n// authorizes each covenant input by its ownership mode, validates each output's state via the covenant-id\n// group, and enforces conservation unless the active branch isMinter (mint/burn). The curve & pool own\n// token balances by COVENANT-ID (mode 0x02, no signature), which is what makes atomic mint/swap possible.\n//\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** kcc20 identifierType (ownership mode) values — dispatched by `transfer`'s checkSigs. */\nexport const IDENTIFIER = { PUBKEY: 0, SCRIPT_HASH: 1, COVENANT_ID: 2, ADDRESS: 3 } as const;\nexport type IdentifierType = (typeof IDENTIFIER)[keyof typeof IDENTIFIER];\n\n/** A kcc20 token balance's full state (the 4 reference fields). `ownerIdentifier` is 32 bytes. */\nexport type Kcc20State = {\n ownerIdentifier: Uint8Array;\n identifierType: IdentifierType;\n amount: bigint;\n isMinter: boolean;\n};\n\n/** Compiled token template: silverc output at the genesis state + the (maxIns,maxOuts) it was built for. */\nexport type Kcc20Template = { script: Uint8Array; stateStart: number; maxIns: number; maxOuts: number };\n\nconst STATE_LEN = 46;\n\n// --- redeem-script materialization (the 46-byte state splice) -----------------------------------\n\n/** Produce the kcc20 redeem script for `state` by splicing the 46-byte region. Byte-identical to silverc. */\nexport function materializeKcc20Script(tpl: Kcc20Template, state: Kcc20State): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x20 || t[s + 33] !== 0x01 || t[s + 35] !== 0x08 || t[s + 44] !== 0x01) {\n throw new Error('kcc20 template has an unexpected state layout (expected push32 owner / push1 type / push8 amount / push1 isMinter)');\n }\n if (state.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n if (state.amount < 0n) throw new Error('amount must be non-negative');\n const out = t.slice();\n out[s] = 0x20;\n out.set(state.ownerIdentifier, s + 1);\n out[s + 33] = 0x01;\n out[s + 34] = state.identifierType;\n out[s + 35] = 0x08;\n out.set(int8LE(state.amount), s + 36);\n out[s + 44] = 0x01;\n out[s + 45] = state.isMinter ? 1 : 0;\n return out;\n}\n\n// --- scriptPublicKeys + address ----------------------------------------------------------------\n\n/** Token P2SH scriptPublicKey for a redeem script. */\nexport const kcc20Spk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\n\n/** Token P2SH scriptPublicKey for a balance state (materialize → P2SH). */\nexport const kcc20SpkForState = (k: K, tpl: Kcc20Template, state: Kcc20State): Spk =>\n kcc20Spk(k, materializeKcc20Script(tpl, state));\n\n/** Token P2SH address (where this balance lives) for a balance state. */\nexport function kcc20Address(k: K, tpl: Kcc20Template, state: Kcc20State, network: string): string {\n return (k as any).addressFromScriptPublicKey(kcc20SpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\n// --- ownership-mode constructors ---------------------------------------------------------------\n\n/** A balance owned by a covenant-id `C` (mode 0x02): spendable only in a tx that also spends an input\n * carrying `C`. This is how the curve owns its minter branch and the pool owns its token UTXO. */\nexport const covenantIdOwned = (covid32: Uint8Array, amount: bigint, isMinter = false): Kcc20State => ({\n ownerIdentifier: covid32,\n identifierType: IDENTIFIER.COVENANT_ID,\n amount,\n isMinter,\n});\n\n/** A balance owned by a 32-byte x-only pubkey (mode 0x00): a user's normal holding (needs a signature). */\nexport const pubkeyOwned = (pubkey32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: pubkey32,\n identifierType: IDENTIFIER.PUBKEY,\n amount,\n isMinter: false,\n});\n\n/** A balance owned by a 32-byte P2SH script-hash (mode 0x01): needs a matching P2SH input in the tx. */\nexport const scriptHashOwned = (hash32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: hash32,\n identifierType: IDENTIFIER.SCRIPT_HASH,\n amount,\n isMinter: false,\n});\n\n/** A balance owned by a normal ADDRESS (mode 0x03, presence-based): spendable when the tx carries a\n * co-present input at the owner's P2PK address (a wallet-signed input). The token UTXO itself carries NO\n * signature, so sell/transfer work with existing wallets via a signPskt-style bridge. owner = x-only pubkey. */\nexport const addressPresenceOwned = (pubkey32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: pubkey32,\n identifierType: IDENTIFIER.ADDRESS,\n amount,\n isMinter: false,\n});\n\n// --- transfer signature script (the column-major State[] ABI) -----------------------------------\n\n/** Push a SINGLE `State`/`TokenState` struct arg field-by-field (declared order, scalar rules) — used by\n * entrypoints whose covenant takes individual structs (e.g. curve buy/sell/graduate, pool swap). */\nexport function pushKcc20StateScalar(b: SigScriptBuilder, st: Kcc20State): void {\n if (st.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n b.data(st.ownerIdentifier).byte(st.identifierType).int(st.amount).bool(st.isMinter);\n}\n\n/** Push a `State[]` arg column-major (owners ‖ types ‖ amounts ‖ isMinters), per build_sig_script. */\nexport function pushKcc20States(b: SigScriptBuilder, states: Kcc20State[]): void {\n for (const st of states) if (st.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n b.column(states.map((s) => s.ownerIdentifier)); // byte[32][] column\n b.column(states.map((s) => Uint8Array.of(s.identifierType))); // byte[] column\n b.column(states.map((s) => int8LE(s.amount))); // int[] column (8-byte LE each)\n b.column(states.map((s) => Uint8Array.of(s.isMinter ? 1 : 0))); // bool[] column\n}\n\n/**\n * Build the kcc20 `transfer` signature script for a token covenant input:\n * <newStates column-major> <sigs> <witnesses> <redeem> (single entrypoint → no selector)\n * `witnesses[i]` is the tx-input index that authorizes input i (for covenant-id ownership, the input\n * carrying that covenant id). `sigs` are 65-byte Schnorr sigs (empty for covenant-id-only ownership).\n */\nexport function transferSigScript(\n k: K,\n redeem: Uint8Array,\n newStates: Kcc20State[],\n witnesses: number[],\n sigs: Uint8Array[] = [],\n): string {\n if (newStates.length < 1) throw new Error('transfer requires at least one output state');\n const b = new SigScriptBuilder(k);\n pushKcc20States(b, newStates);\n b.column(sigs); // sig[] — fixed-width concat (empty → empty push)\n b.data(Uint8Array.from(witnesses, (w) => w & 0xff)); // byte[] witnesses\n b.redeem(redeem);\n return b.drain();\n}\n","// Virtual-reserve constant-product curve builder — builds transactions against an ALREADY-DEPLOYED curve_cp\n// covenant instance (buy/sell/graduate). Curve state is {graduated, tokenCovid, tokenReserve} (realKas = the\n// curve UTXO value; tokenReserve = the committed token inventory, authoritative in state and kept in sync with\n// the C-owned inventory UTXO the curve also holds).\n//\n// buy — kasIn into the reserve, tokenOut from inventory to the buyer (presence-owned), fee split. The\n// bought tokens MERGE with any existing buyer holdings passed in `mergeTokens` into ONE output.\n// sell — the seller folds `tokenIn` from their piece(s) into inventory, refund kasOut; the unsold\n// remainder returns as ONE presence-owned change output (fractional; no pre-split needed).\n// graduate — lock the curve, seed amm_pool_cp_v3 with the post-fee reserve + leftover inventory.\n//\n// State region (verify: silverc state_layout {start:1,len:44}): off 1: 0x01 <graduated:1> 0x20 <tokenCovid:32>\n// 0x08 <tokenReserve:8 LE>. tokenReserve is the AUTHORITATIVE token inventory committed to state (this is the\n// reserve-spoof hardening: buy/sell/graduate read the reserve from state, not from an attacker-chosen input).\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`. Callers need\n// the target curve's compiled script bytes (`CpTemplate.script`) — read them from your indexer's live UTXO\n// data (e.g. the `redeemScriptHex` field), not compiled locally; this package doesn't ship a covenant\n// compiler (see README).\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20State,\n type Kcc20Template,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport { genesisCovenantId, covidToBytes } from './genesis.js';\nimport { materializePoolCpScript, type PoolCpTemplate } from './poolCpTx.js';\nimport { FEE_OUT_MIN, MAX_KAS } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\nexport const SCALE = 1_000_000n; // 1e6 sompi = 0.01 KAS (matches curve_cp.sil)\n// Fee outputs padded to FEE_OUT_MIN (cpCurve) — a sub-dust output blows KIP-9 storage mass past the 500k cap.\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\nexport const SELECTOR = { init: 0, buy: 1, sell: 2, graduate: 3, initVested: 4 } as const;\nconst ZERO32 = new Uint8Array(32);\n\n/** Fixed per-token curve parameters (baked into the redeem script by silverc). */\nexport type CpParams = {\n creatorFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK)\n platformFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK)\n vKas: bigint; // virtual KAS reserve, SCALE units\n graduationKas: bigint; // raised-KAS target (sompi)\n creatorFeeBps: bigint;\n platformFeeBps: bigint;\n graduationFeeBps: bigint;\n};\nexport type CpTemplate = { script: Uint8Array; stateStart: number; params: CpParams };\nexport type CpCurveState = { graduated: boolean; tokenCovid: Uint8Array; tokenReserve: bigint };\n/** The live curve UTXO. `realKas` (sompi) = its value = KAS raised. */\nexport type CpCurveUtxo = { transactionId: string; index: number; realKas: bigint; state: CpCurveState };\n/** The curve's C-owned token inventory UTXO (covid A). `amount` = tokens remaining. */\nexport type CpInventoryUtxo = { transactionId: string; index: number; value: bigint; amount: bigint };\n\n// --- state splice (off 1, 44 bytes: graduated + tokenCovid + tokenReserve) ---------------------\nexport function materializeCpScript(tpl: CpTemplate, state: CpCurveState): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x01 || t[s + 2] !== 0x20 || t[s + 35] !== 0x08) {\n throw new Error('curve_cp template has an unexpected state layout (expected push1 graduated / push32 tokenCovid / push8 tokenReserve)');\n }\n if (state.tokenCovid.length !== 32) throw new Error('tokenCovid must be 32 bytes');\n if (state.tokenReserve < 0n) throw new Error('tokenReserve must be non-negative');\n const out = t.slice();\n out[s] = 0x01;\n out[s + 1] = state.graduated ? 1 : 0;\n out[s + 2] = 0x20;\n out.set(state.tokenCovid, s + 3);\n out[s + 35] = 0x08;\n out.set(int8LE(state.tokenReserve), s + 36);\n return out;\n}\n\nexport const cpSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const cpSpkForState = (k: K, tpl: CpTemplate, state: CpCurveState): Spk => cpSpk(k, materializeCpScript(tpl, state));\nexport function cpAddress(k: K, tpl: CpTemplate, state: CpCurveState, network: string): string {\n return (k as any).addressFromScriptPublicKey(cpSpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\n/** Fee output scriptPublicKey: P2PK (`<32-byte pubkey> OP_CHECKSIG`). */\nexport function p2pkSpk(k: K, pubkey: Uint8Array): Spk {\n const sb = new (k as any).ScriptBuilder();\n sb.addData(pubkey).addOp(172);\n return new (k as any).ScriptPublicKey(0, sb.drain());\n}\n\n// --- curve-input signature scripts -------------------------------------------------------------\nfunction buySig(k: K, redeem: Uint8Array, kasIn: bigint, tokenOut: bigint, inventoryOut: Kcc20State, buyerOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasIn).int(tokenOut);\n pushKcc20StateScalar(b, inventoryOut);\n pushKcc20StateScalar(b, buyerOut);\n return b.selector(SELECTOR.buy).redeem(redeem).drain();\n}\n// single-token sell: pushes traderChangeOut too (even on a full sell — the covenant only validates it when a\n// 2nd covid-A output exists; otherwise it's an ignored placeholder).\nfunction sellSig(k: K, redeem: Uint8Array, tokenIn: bigint, kasOut: bigint, inventoryOut: Kcc20State, traderChangeOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(tokenIn).int(kasOut);\n pushKcc20StateScalar(b, inventoryOut);\n pushKcc20StateScalar(b, traderChangeOut);\n return b.selector(SELECTOR.sell).redeem(redeem).drain();\n}\n// graduate: the PoolState struct has five fields (kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid)\n// — push all five in declared order.\nfunction graduateSigV2(k: K, redeem: Uint8Array, pool: { kasReserve: bigint; tokenReserve: bigint; tokenCovid: Uint8Array; totalShares: bigint; lpCovid: Uint8Array }, poolTokens: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(pool.kasReserve).int(pool.tokenReserve).data(pool.tokenCovid).int(pool.totalShares).data(pool.lpCovid);\n pushKcc20StateScalar(b, poolTokens);\n return b.selector(SELECTOR.graduate).redeem(redeem).drain();\n}\n\n// --- buy (MERGE): kasIn into reserve, tokenOut from inventory; the bought tokens MERGE with any EXISTING holdings\n// the buyer passes in `mergeTokens` into ONE presence-owned output — so a buy never fragments. `presenceWitnessIdx`\n// = the tx input index of a co-present P2PK input at the buyer's address (only needed when merging).\nexport function buildCpBuy(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n utxo: CpCurveUtxo,\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n buyerPubkey: Uint8Array,\n kasIn: bigint,\n tokenOut: bigint,\n mergeTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[] = [],\n presenceWitnessIdx = 0,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('curve has graduated — buys are locked');\n if (kasIn <= 0n || kasIn % SCALE !== 0n) throw new Error('kasIn must be a positive multiple of SCALE (0.01 KAS)');\n if (tokenOut <= 0n || tokenOut >= inventory.amount) throw new Error('invalid tokenOut');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const dust = opts.tokenDust ?? 1000n;\n const newKas = utxo.realKas + kasIn;\n // Overbuy allowed: a buy may exceed graduationKas (excess seeds the LP at graduation). Only MAX_KAS caps it.\n if (newKas > MAX_KAS) throw new Error('buy exceeds the curve max raise (9,000,000 TKAS)');\n const newToken = inventory.amount - tokenOut;\n const creatorFee = (kasIn * tpl.params.creatorFeeBps) / 10000n;\n const platformFee = (kasIn * tpl.params.platformFeeBps) / 10000n;\n const mergeSum = mergeTokens.reduce((s, t) => s + t.state.amount, 0n);\n\n const inventoryOut = covenantIdOwned(curveCovid, newToken, false);\n const buyerOut = addressPresenceOwned(buyerPubkey, tokenOut + mergeSum); // bought + merged existing → ONE UTXO\n const curRedeem = materializeCpScript(tpl, utxo.state);\n const newCurveRedeem = materializeCpScript(tpl, { graduated: false, tokenCovid: utxo.state.tokenCovid, tokenReserve: newToken });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n const invOutRedeem = materializeKcc20Script(tokenTpl, inventoryOut);\n const buyerRedeem = materializeKcc20Script(tokenTpl, buyerOut);\n // covid-A inputs in tx order: inventory (witness = curve input 0), then each merged existing token (presence → P2PK).\n const witnesses = [0, ...mergeTokens.map(() => presenceWitnessIdx)];\n const newStates = [inventoryOut, buyerOut];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: buySig(k, curRedeem, kasIn, tokenOut, inventoryOut, buyerOut), redeem: curRedeem, role: 'curve' },\n // inventory (covid A, C-owned) spent via kcc20 transfer; the C-owned input is authorized by the curve (input 0)\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, newStates, witnesses), redeem: invRedeem, role: 'inventory' },\n ...mergeTokens.map((mt) => {\n const r = materializeKcc20Script(tokenTpl, mt.state);\n return { transactionId: mt.transactionId, index: mt.index, value: mt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'buyerToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: newKas, scriptPublicKey: cpSpk(k, newCurveRedeem), role: 'curve' },\n { value: dust, scriptPublicKey: kcc20Spk(k, invOutRedeem), role: 'inventory' },\n { value: dust, scriptPublicKey: kcc20Spk(k, buyerRedeem), role: 'recipient' },\n { value: padFee(creatorFee), scriptPublicKey: p2pkSpk(k, tpl.params.creatorFeeOwner), role: 'creatorFee' },\n { value: padFee(platformFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'platformFee' },\n ];\n return { kind: 'buy', inputs, outputs, economics: { kasIn, tokenOut, creatorFee, platformFee, newRealKas: newKas, newTokenReserve: newToken, merged: mergeSum }, covids: { tokenCovid: hexOf(utxo.state.tokenCovid) } };\n}\n\n// --- sell (single-token, FRACTIONAL): fold `tokenIn` from the seller's piece(s), refund kasOut, return the\n// unsold remainder as ONE presence-owned change output (LAST) — no pre-split. Inputs: [curve(0), inventory(1),\n// seller1(2)…sellerN]. `presenceWitnessIdx` = the tx index of a co-present P2PK input at the seller's address the\n// wallet signs (also the presence witness that authorizes the address-owned seller tokens). covid-A outputs:\n// [inventory(0), OPTIONAL change(1)]. kcc20 conservation forces change == Σ(seller inputs) − tokenIn.\nexport function buildCpSell(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n utxo: CpCurveUtxo,\n sellerTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n traderPubkey: Uint8Array,\n tokenIn: bigint,\n kasOut: bigint,\n presenceWitnessIdx: number,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('curve has graduated — sells are locked');\n if (sellerTokens.length < 1) throw new Error('need at least one seller token');\n if (tokenIn <= 0n) throw new Error('tokenIn must be positive');\n if (kasOut <= 0n || kasOut % SCALE !== 0n || kasOut > utxo.realKas) throw new Error('invalid kasOut');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const dust = opts.tokenDust ?? 1000n;\n const sellerIn = sellerTokens.reduce((s, t) => s + t.state.amount, 0n);\n const change = sellerIn - tokenIn; // the unsold remainder (kcc20 conservation pins it on-chain)\n if (change < 0n) throw new Error('seller inputs are less than the sell amount');\n const hasChange = change > 0n;\n const newToken = inventory.amount + tokenIn;\n const creatorFee = (kasOut * tpl.params.creatorFeeBps) / 10000n;\n const platformFee = (kasOut * tpl.params.platformFeeBps) / 10000n;\n\n const inventoryOut = covenantIdOwned(curveCovid, newToken, false);\n const traderChangeOut = addressPresenceOwned(traderPubkey, hasChange ? change : 1n); // dummy(1) on a full sell — covenant ignores it\n const curRedeem = materializeCpScript(tpl, utxo.state);\n const newCurveRedeem = materializeCpScript(tpl, { graduated: false, tokenCovid: utxo.state.tokenCovid, tokenReserve: newToken });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n const invOutRedeem = materializeKcc20Script(tokenTpl, inventoryOut);\n // covid-A inputs in tx order: inventory (witness = curve input 0), then each seller (presence → its P2PK witness).\n const witnesses = [0, ...sellerTokens.map(() => presenceWitnessIdx)];\n const newStates = hasChange ? [inventoryOut, traderChangeOut] : [inventoryOut];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: sellSig(k, curRedeem, tokenIn, kasOut, inventoryOut, traderChangeOut), redeem: curRedeem, role: 'curve' },\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, newStates, witnesses), redeem: invRedeem, role: 'inventory' },\n ...sellerTokens.map((st) => {\n const r = materializeKcc20Script(tokenTpl, st.state);\n return { transactionId: st.transactionId, index: st.index, value: st.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'sellerToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: utxo.realKas - kasOut, scriptPublicKey: cpSpk(k, newCurveRedeem), role: 'curve' },\n { value: dust, scriptPublicKey: kcc20Spk(k, invOutRedeem), role: 'inventory' },\n { value: padFee(creatorFee), scriptPublicKey: p2pkSpk(k, tpl.params.creatorFeeOwner), role: 'creatorFee' },\n { value: padFee(platformFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'platformFee' },\n ];\n if (hasChange) outputs.push({ value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderChangeOut)), role: 'seller' });\n return { kind: 'sell', inputs, outputs, economics: { tokenIn, kasOut, change, creatorFee, platformFee, newRealKas: utxo.realKas - kasOut, newTokenReserve: newToken }, covids: { tokenCovid: hexOf(utxo.state.tokenCovid) } };\n}\n\n// --- graduate: lock curve, seed the CP pool (amm_pool_cp_v3) with the 5-field PoolState (locked floor, L unbound) ---\n// The curve must have been compiled with the CP pool template + `poolLockedShares` (curve_cp.sil graduate\n// requires pool.totalShares == poolLockedShares and pool.lpCovid == ZERO_COVID). The pool's LP-share token L\n// is NOT minted here — it's bound post-graduation by the pool's bindLp (buildBindLp), which needs the pool\n// live first.\nexport function buildCpGraduate(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n poolTemplate: PoolCpTemplate,\n utxo: CpCurveUtxo,\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n poolLockedShares: bigint,\n opts: { lockedCurveValue?: bigint; tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('already graduated');\n if (utxo.realKas < tpl.params.graduationKas) throw new Error('reserve has not reached the graduation target');\n if (poolLockedShares < 1n) throw new Error('poolLockedShares must be >= 1');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const lockedValue = opts.lockedCurveValue ?? 1000n;\n const dust = opts.tokenDust ?? 1000n;\n // poolKas ≈ (1 − gradFeeBps) of the reserve, floored to a whole SCALE step; platform takes the remainder.\n const targetPoolKas = (utxo.realKas * (10000n - tpl.params.graduationFeeBps)) / 10000n;\n const poolKasUnits = targetPoolKas / SCALE;\n const poolKas = poolKasUnits * SCALE;\n const gradFee = utxo.realKas - poolKas;\n const leftover = inventory.amount;\n\n const A = utxo.state.tokenCovid;\n // pool genesis state: locked floor seeded (totalShares == poolLockedShares), L unbound (lpCovid == ZERO).\n const poolState = { kasReserve: poolKasUnits, tokenReserve: leftover, tokenCovid: A, totalShares: poolLockedShares, lpCovid: ZERO32 };\n const poolRedeem = materializePoolCpScript(poolTemplate, poolState);\n const poolSpkV = (k as any).payToScriptHashScript(poolRedeem);\n const poolCovidHex = genesisCovenantId(k, { transactionId: utxo.transactionId, index: utxo.index }, [\n { index: 1, value: poolKas, scriptPublicKey: poolSpkV },\n ]);\n const poolCovid = covidToBytes(poolCovidHex);\n const poolTokens = covenantIdOwned(poolCovid, leftover, false);\n const poolTokenRedeem = materializeKcc20Script(tokenTpl, poolTokens);\n\n const curRedeem = materializeCpScript(tpl, utxo.state);\n // graduated husk carries the reserve unchanged (== inventory.amount == the committed reserve at lock time).\n const lockedRedeem = materializeCpScript(tpl, { graduated: true, tokenCovid: A, tokenReserve: inventory.amount });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: graduateSigV2(k, curRedeem, poolState, poolTokens), redeem: curRedeem, role: 'curve' },\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, [poolTokens], [0]), redeem: invRedeem, role: 'inventory' },\n ];\n const outputs: CovOutput[] = [\n { value: lockedValue, scriptPublicKey: cpSpk(k, lockedRedeem), role: 'curve' },\n { value: poolKas, scriptPublicKey: poolSpkV, role: 'pool' },\n { value: dust, scriptPublicKey: kcc20Spk(k, poolTokenRedeem), role: 'poolToken' },\n { value: padFee(gradFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'gradFee' },\n ];\n return { kind: 'graduate', inputs, outputs, economics: { poolKas, gradFee, leftover, poolLockedShares }, covids: { tokenCovid: hexOf(A), poolCovid: poolCovidHex } };\n}\n\n/**\n * Split a presence-owned token UTXO into [sellAmount, change], both still presence-owned by the same holder —\n * a plain conserving kcc20 transfer authorized by a co-present P2PK input at `presenceWitnessIdx`. Lets a\n * holder sell an ARBITRARY amount on covenants that require full-UTXO sells (curve/pool): split, then sell the\n * `sellAmount` piece. No curve/pool involved — just the token covenant.\n */\nexport function buildSplitToken(\n k: K, tokenTpl: Kcc20Template,\n sellerToken: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n sellAmount: bigint, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n const change = sellerToken.state.amount - sellAmount;\n if (sellAmount <= 0n || change <= 0n) throw new Error('split requires 0 < sellAmount < the UTXO amount');\n const dust = opts.tokenDust ?? 1000n;\n const owner = sellerToken.state.ownerIdentifier;\n const out1 = addressPresenceOwned(owner, sellAmount); // the piece to sell (output 0)\n const out2 = addressPresenceOwned(owner, change); // the change (output 1)\n const redeem = materializeKcc20Script(tokenTpl, sellerToken.state);\n const inputs: CovInput[] = [\n { transactionId: sellerToken.transactionId, index: sellerToken.index, value: sellerToken.value, scriptPublicKey: kcc20Spk(k, redeem), signatureScript: transferSigScript(k, redeem, [out1, out2], [presenceWitnessIdx]), redeem, role: 'sellerToken' },\n ];\n const outputs: CovOutput[] = [\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, out1)), role: 'split' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, out2)), role: 'change' },\n ];\n return { kind: 'sell', inputs, outputs, economics: { sellAmount, change }, covids: { tokenCovid: hexOf(owner) } };\n}\n\n/**\n * Consolidate several presence-owned token UTXOs (same owner) into ONE — a conserving kcc20 transfer (N covid-A\n * inputs → 1 output) authorized by a single co-present P2PK input at `presenceWitnessIdx`. Lets a holder merge\n * many small buys into one piece so a later sell needs just one (or two) inputs. No curve/pool involved.\n */\nexport function buildConsolidate(\n k: K, tokenTpl: Kcc20Template,\n tokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (tokens.length < 2) throw new Error('consolidate needs at least 2 UTXOs');\n const dust = opts.tokenDust ?? 1000n;\n const owner = tokens[0].state.ownerIdentifier;\n const total = tokens.reduce((s, t) => s + t.state.amount, 0n);\n const merged = addressPresenceOwned(owner, total);\n const newStates = [merged];\n const witnesses = tokens.map(() => presenceWitnessIdx); // every covid-A input authorized by the one P2PK\n const inputs: CovInput[] = tokens.map((t) => {\n const r = materializeKcc20Script(tokenTpl, t.state);\n return { transactionId: t.transactionId, index: t.index, value: t.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'token' };\n });\n const outputs: CovOutput[] = [\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, merged)), role: 'merged' },\n ];\n return { kind: 'sell', inputs, outputs, economics: { total }, covids: { tokenCovid: hexOf(owner) } };\n}\n\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n","// amm_pool_cp transaction builder — the graduated DEX pool with TWO-TIER liquidity. SHARED core: pool state\n// layout, P2SH/address derivation, CP quotes, and the LP entrypoints (bindLp / addLiquidity / removeLiquidity),\n// which are byte-identical across the pool covenant versions. The LIVE deployed covenant is amm_pool_cp_v3.sil\n// (single-token swaps); its swap builders live in poolCpV3Tx.ts and reuse everything here.\n//\n// MODEL (see docs/lp-provision-design.md + amm_pool_cp_v3.sil):\n// • Graduation seeds a PERMANENTLY-LOCKED floor (`lockedShares`); on top, anyone can add/remove VOLUNTARY\n// liquidity and earn swap fees. LP shares follow KRON's INVENTORY model (a pre-minted kcc20 token `L`,\n// pool holds the unissued shares; add/remove MOVE shares, never mint/burn).\n// • 5-field pool state {kasReserve(SCALE units), tokenReserve, tokenCovid, totalShares, lpCovid}.\n// • Post-grad fee (option ii): creator base + the floor's share of the LP fee paid OUT to the creator\n// (creatorFloorRent = lpFee·lockedShares/totalShares); the voluntary share stays in-pool (k grows).\n//\n// SECURITY: the pool owns TWO covenant tokens (A reserve + L inventory), both covenant-id-owned. Every\n// entrypoint fully constrains BOTH groups — swaps forbid any L movement; add/remove validate the exact moves.\n//\n// Reuses the kcc20 template/helpers (token A AND the LP-share token L share the SAME kcc20 contract — only\n// the covid differs). No top-level SDK import — caller passes the loaded WASM `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20State,\n type Kcc20Template,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport { genesisCovenantId, covidToBytes } from './genesis.js';\nimport { FEE_OUT_MIN, SCALE } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** pool entrypoint selectors (declaration order in amm_pool_cp_v3.sil). */\nexport const POOL_CP_SELECTOR = { swapKasForToken: 0, swapTokenForKas: 1, addLiquidity: 2, removeLiquidity: 3, bindLp: 4 } as const;\n/** the LP-share token's FIXED total supply S_MAX (== MAX_SHARES in amm_pool_cp_v3.sil). */\nexport const MAX_SHARES = 10_000_000n;\n/** the all-zero covenant id — the bindLp floor owner (unspendable) and the unbound `lpCovid` placeholder. */\nconst ZERO32 = new Uint8Array(32);\n\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\nconst ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n\n// --- pool state (5 fields) + redeem-script splice -------------------------------------------\n// silverc state_layout {start, len:93}:\n// off 0: 0x08 <kasReserve:8 LE> off 9: 0x08 <tokenReserve:8 LE> off 18: 0x20 <tokenCovid:32>\n// off 51: 0x08 <totalShares:8 LE> off 60: 0x20 <lpCovid:32>\n\n/** Compiled pool template (silverc output; one template per (lockedShares,bps...) — only state varies). */\nexport type PoolCpTemplate = { script: Uint8Array; stateStart: number };\n\n/** Pool state: KAS reserve (SCALE units; pool UTXO value == kasReserve·SCALE), token reserve, the token\n * covid A, issued LP shares, and the LP-share token covid L (ZERO until bindLp). */\nexport type PoolCpState = {\n kasReserve: bigint;\n tokenReserve: bigint;\n tokenCovid: Uint8Array;\n totalShares: bigint;\n lpCovid: Uint8Array;\n};\n\n/** Produce the pool redeem script for `state` by splicing the 93-byte region. Byte-identical to silverc. */\nexport function materializePoolCpScript(tpl: PoolCpTemplate, state: PoolCpState): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x08 || t[s + 9] !== 0x08 || t[s + 18] !== 0x20 || t[s + 51] !== 0x08 || t[s + 60] !== 0x20) {\n throw new Error('pool template has an unexpected state layout (expected kasReserve/tokenReserve/tokenCovid/totalShares/lpCovid)');\n }\n if (state.kasReserve < 0n || state.tokenReserve < 0n || state.totalShares < 0n) throw new Error('reserves/shares must be non-negative');\n if (state.tokenCovid.length !== 32) throw new Error('tokenCovid must be 32 bytes');\n if (state.lpCovid.length !== 32) throw new Error('lpCovid must be 32 bytes');\n const out = t.slice();\n out[s] = 0x08;\n out.set(int8LE(state.kasReserve), s + 1);\n out[s + 9] = 0x08;\n out.set(int8LE(state.tokenReserve), s + 10);\n out[s + 18] = 0x20;\n out.set(state.tokenCovid, s + 19);\n out[s + 51] = 0x08;\n out.set(int8LE(state.totalShares), s + 52);\n out[s + 60] = 0x20;\n out.set(state.lpCovid, s + 61);\n return out;\n}\n\nexport const poolCpSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const poolCpSpkForState = (k: K, tpl: PoolCpTemplate, state: PoolCpState): Spk => poolCpSpk(k, materializePoolCpScript(tpl, state));\nexport function poolCpAddress(k: K, tpl: PoolCpTemplate, state: PoolCpState, network: string): string {\n return (k as any).addressFromScriptPublicKey(poolCpSpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\nconst p2pkSpk = (k: any, pubkey: Uint8Array) => { const sb = new k.ScriptBuilder(); sb.addData(pubkey).addOp(172); return new k.ScriptPublicKey(0, sb.drain()); };\n\n/** Fixed per-pool fee schedule (baked into the redeem script by silverc; the builder needs them for quotes). */\nexport type PoolCpParams = {\n creatorFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK): creator base fee + the floor's LP-fee share\n platformFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK): platform fee\n creatorFeeBps: bigint; // e.g. 10 = 0.10%\n platformFeeBps: bigint; // e.g. 5 = 0.05%\n lpFeeBps: bigint; // e.g. 20 = 0.20%\n lockedShares: bigint; // the permanently-locked floor shares (baked; == graduation totalShares)\n};\n\n/** The live pool UTXO (value = kasReserve·SCALE) + its P-owned token-A reserve UTXO. */\nexport type PoolCpUtxo = {\n transactionId: string;\n index: number;\n state: PoolCpState;\n /** the pool's token-A reserve UTXO (kcc20 owned by the pool covid P, amount = tokenReserve). */\n tokenUtxo: { transactionId: string; index: number; value: bigint };\n};\n\n/** The pool's P-owned LP-share (L) inventory UTXO (amount = the unissued shares the pool holds). */\nexport type PoolLpInventoryUtxo = { transactionId: string; index: number; value: bigint; amount: bigint };\n\n// =================================================================================================\n// swaps (with the option-ii floor-rent fee + voluntary-yield k-growth)\n// =================================================================================================\n\nexport type PoolCpBuyQuote = {\n kasInUnits: bigint; kasIn: bigint; tokenOut: bigint;\n creatorFee: bigint; creatorFloorRent: bigint; platformFee: bigint; lpFee: bigint;\n creatorOut: bigint; platformOut: bigint; total: bigint; newKas: bigint; newToken: bigint;\n};\nexport type PoolCpSellQuote = {\n tokenIn: bigint; kasOutUnits: bigint; kasOut: bigint;\n creatorFee: bigint; creatorFloorRent: bigint; platformFee: bigint; lpFee: bigint;\n creatorOut: bigint; platformOut: bigint; net: bigint; newKas: bigint; newToken: bigint;\n};\n\n/** The voluntary share of the LP fee, in bps, that must stay in the pool (k-growth) — matches the covenant. */\nfunction lpRetainBps(state: PoolCpState, p: PoolCpParams): bigint {\n return (p.lpFeeBps * (state.totalShares - p.lockedShares)) / state.totalShares;\n}\n\n/** Buy from the pool: spend `kasInSompi` (floored to a SCALE step) → tokenOut, retaining the voluntary LP fee in-pool. */\nexport function quotePoolCpBuy(state: PoolCpState, p: PoolCpParams, kasInSompi: bigint): PoolCpBuyQuote | null {\n const kasInUnits = kasInSompi / SCALE; const kasIn = kasInUnits * SCALE;\n if (kasInUnits <= 0n) return null;\n const newKas = state.kasReserve + kasInUnits;\n const oldK = state.kasReserve * state.tokenReserve;\n // Retain the voluntary share of THIS trade's LP fee in-pool — trade-proportional, mirroring the covenant EXACTLY:\n // (newKas − retainKas)·newToken ≥ oldK, so the most tokenOut comes from newToken = ceil(oldK / (newKas − retainKas)).\n const retainKas = (kasInUnits * lpRetainBps(state, p)) / 10000n;\n const effKas = newKas - retainKas;\n if (effKas <= 0n) return null;\n const newToken = ceilDiv(oldK, effKas);\n const tokenOut = state.tokenReserve - newToken;\n if (tokenOut <= 0n) return null;\n const creatorFee = (kasIn * p.creatorFeeBps) / 10000n;\n const platformFee = (kasIn * p.platformFeeBps) / 10000n;\n const lpFee = (kasIn * p.lpFeeBps) / 10000n;\n const creatorFloorRent = (lpFee * p.lockedShares) / state.totalShares;\n const creatorOut = padFee(creatorFee + creatorFloorRent);\n const platformOut = padFee(platformFee);\n return { kasInUnits, kasIn, tokenOut, creatorFee, creatorFloorRent, platformFee, lpFee, creatorOut, platformOut, total: kasIn + creatorOut + platformOut, newKas, newToken };\n}\n\n/** Sell to the pool: fold `tokenIn` tokens in → kasOut sompi (a SCALE step), retaining the voluntary LP fee in-pool. */\nexport function quotePoolCpSell(state: PoolCpState, p: PoolCpParams, tokenIn: bigint): PoolCpSellQuote | null {\n if (tokenIn <= 0n) return null;\n const newToken = state.tokenReserve + tokenIn;\n const oldK = state.kasReserve * state.tokenReserve;\n const r = lpRetainBps(state, p);\n // The covenant requires (kasReserve − kasOut − floor(kasOut·r/1e4))·newToken ≥ oldK. Pick the LARGEST kasOut that\n // clears it: kasOut + floor(kasOut·r/1e4) ≤ kasReserve − ceil(oldK/newToken). Closed-form start, then ±1-adjust for\n // the floor() so we land on EXACTLY the covenant's max (never over-ask the VM rejects, never under-pay the trader).\n const effMin = ceilDiv(oldK, newToken);\n const budget = state.kasReserve - effMin;\n if (budget <= 0n) return null;\n const g = (x: bigint) => x + (x * r) / 10000n;\n let kasOutUnits = (budget * 10000n) / (10000n + r);\n while (kasOutUnits > 0n && g(kasOutUnits) > budget) kasOutUnits -= 1n;\n while (g(kasOutUnits + 1n) <= budget) kasOutUnits += 1n;\n const newKas = state.kasReserve - kasOutUnits;\n if (kasOutUnits <= 0n || newKas < 1n) return null;\n const kasOut = kasOutUnits * SCALE;\n const creatorFee = (kasOut * p.creatorFeeBps) / 10000n;\n const platformFee = (kasOut * p.platformFeeBps) / 10000n;\n const lpFee = (kasOut * p.lpFeeBps) / 10000n;\n const creatorFloorRent = (lpFee * p.lockedShares) / state.totalShares;\n const creatorOut = padFee(creatorFee + creatorFloorRent);\n const platformOut = padFee(platformFee);\n return { tokenIn, kasOutUnits, kasOut, creatorFee, creatorFloorRent, platformFee, lpFee, creatorOut, platformOut, net: kasOut - creatorOut - platformOut, newKas, newToken };\n}\n\n// =================================================================================================\n// addLiquidity / removeLiquidity (inventory moves of L; two-sided A/KAS at the current ratio)\n// =================================================================================================\n\nexport type AddLiquidityQuote = { dKas: bigint; dToken: bigint; dShares: bigint; newKas: bigint; newToken: bigint; newShares: bigint };\nexport type RemoveLiquidityQuote = { dShares: bigint; dKas: bigint; dToken: bigint; newKas: bigint; newToken: bigint; newShares: bigint };\n\n/** The smallest deposit (in SCALE units) that mints ≥ 1 LP share at the current ratio. The covenant floors\n * dShares = floor(totalShares·dKas/kasReserve), so dShares ≥ 1 ⟺ dKas ≥ ceil(kasReserve/totalShares). ANY dKas\n * at/above this deposits — the old exact-integer lcm \"step\" (which could force a near-whole-pool minimum when the\n * reserves were coprime to totalShares) is gone now that addLiquidity is floored like removeLiquidity. */\nexport function addMinDKas(state: PoolCpState): bigint {\n return (state.kasReserve + state.totalShares - 1n) / state.totalShares; // ceil(kasReserve/totalShares)\n}\n\n/** Clamp a desired `dKas` to a valid deposit: unchanged if ≥ the minimum (see addMinDKas), else 0 (too small to\n * mint an integer share). No down-stepping — every value at/above the min is valid now that the covenant floors. */\nexport function snapAddDKas(state: PoolCpState, desiredDKas: bigint): bigint {\n const min = addMinDKas(state);\n if (min <= 0n || desiredDKas < min) return 0n;\n return desiredDKas;\n}\n\n/** Size a balanced deposit from `dKas` (SCALE units), FLOORED to match the covenant: dShares =\n * floor(totalShares·dKas/kasReserve) (the depositor never gets more than their KAS-contribution fraction, so\n * existing LPs aren't diluted), dToken = ceil(tokenReserve·dShares/totalShares) (they supply ≥ the proportional\n * token). Any dKas ≥ addMinDKas works; throws only if dKas rounds to 0 shares. */\nexport function quoteAddLiquidity(state: PoolCpState, dKas: bigint): AddLiquidityQuote {\n if (dKas <= 0n) throw new Error('dKas must be positive');\n const dShares = (state.totalShares * dKas) / state.kasReserve; // floor\n if (dShares <= 0n) throw new Error('dKas too small to mint an integer LP share (snap with snapAddDKas / addMinDKas first)');\n const dToken = (state.tokenReserve * dShares + state.totalShares - 1n) / state.totalShares; // ceil(tokenReserve·dShares/totalShares)\n return { dKas, dToken, dShares, newKas: state.kasReserve + dKas, newToken: state.tokenReserve + dToken, newShares: state.totalShares + dShares };\n}\n\n/** The smallest withdrawable dShares — the floored covenant only needs the payout to round to ≥ 1 on BOTH sides\n * (dKas ≥ 1 ⟺ dShares ≥ ⌈totalShares/kasReserve⌉; dToken ≥ 1 likewise). No exact-integer \"step\" exists anymore,\n * so any dShares at/above this withdraws (the old lcm-step that could strand a voluntary LP is gone). */\nexport function removeMinDShares(state: PoolCpState): bigint {\n const ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\n const minKas = ceilDiv(state.totalShares, state.kasReserve);\n const minTok = ceilDiv(state.totalShares, state.tokenReserve);\n return minKas > minTok ? minKas : minTok;\n}\n\n/** Clamp a desired `dShares` to a withdrawable amount: returns it unchanged if ≥ the minimum (see removeMinDShares),\n * else 0 (too small to round to ≥ 1 of either side). No down-stepping — every value at/above the min is valid. */\nexport function snapRemoveDShares(state: PoolCpState, desiredDShares: bigint): bigint {\n if (desiredDShares <= 0n || desiredDShares < removeMinDShares(state)) return 0n;\n return desiredDShares;\n}\n\n/** Compute a FLOORED-proportional withdrawal for `dShares` (matches the covenant): dKas/dToken are floored, so\n * the sub-unit remainder stays in the pool. Throws only if dShares is non-positive, would dip below the locked\n * floor (totalShares − dShares < lockedShares), or is so small the floored payout rounds to < 1 of either side. */\nexport function quoteRemoveLiquidity(state: PoolCpState, p: Pick<PoolCpParams, 'lockedShares'>, dShares: bigint): RemoveLiquidityQuote {\n if (dShares <= 0n) throw new Error('dShares must be positive');\n if (state.totalShares - dShares < p.lockedShares) throw new Error('removal would dip below the permanently-locked floor');\n const dKas = (state.kasReserve * dShares) / state.totalShares; // bigint division floors (positives)\n const dToken = (state.tokenReserve * dShares) / state.totalShares;\n if (dKas < 1n || dToken < 1n) throw new Error('withdrawal too small — rounds to less than 1 KAS-unit or 1 token');\n return { dShares, dKas, dToken, newKas: state.kasReserve - dKas, newToken: state.tokenReserve - dToken, newShares: state.totalShares - dShares };\n}\n\nfunction addLiquiditySig(k: K, redeem: Uint8Array, dKas: bigint, dToken: bigint, dShares: bigint, poolTokenOut: Kcc20State, poolLpOut: Kcc20State, lpSharesOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(dKas).int(dToken).int(dShares);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, poolLpOut); pushKcc20StateScalar(b, lpSharesOut);\n return b.selector(POOL_CP_SELECTOR.addLiquidity).redeem(redeem).drain();\n}\nfunction removeLiquiditySig(k: K, redeem: Uint8Array, dShares: bigint, dKas: bigint, dToken: bigint, poolTokenOut: Kcc20State, lpTokenOut: Kcc20State, poolLpOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(dShares).int(dKas).int(dToken);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, lpTokenOut); pushKcc20StateScalar(b, poolLpOut);\n return b.selector(POOL_CP_SELECTOR.removeLiquidity).redeem(redeem).drain();\n}\n\n/**\n * addLiquidity — deposit dKas (SCALE units) + dToken at the current ratio, receive dShares of L moved out of\n * the pool's inventory. The LP must supply a token-A UTXO of EXACTLY dToken (full-UTXO deposit — the covenant\n * allows only ONE covid-A output, the grown pool reserve) and a co-present P2PK input at `presenceWitnessIdx`.\n *\n * Inputs: [0]=pool [1]=LP token-A deposit(presence, =dToken) [2]=pool token-A reserve(P) [3]=pool L inventory(P)\n * Outputs: [0]=pool(grown) [1]=pool token-A reserve(P, newToken) [2]=reduced pool L inventory(P) [3]=LP dShares(presence)\n */\nexport function buildAddLiquidity(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, lpInventory: PoolLpInventoryUtxo, poolCovid: Uint8Array,\n lpDepositToken: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n lpPubkey: Uint8Array, q: AddLiquidityQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (lpDepositToken.state.amount !== q.dToken) throw new Error('LP deposit token UTXO must equal dToken exactly (split first)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, lpCovid } = utxo.state;\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false); // grown token-A reserve (P)\n const poolLpOut = covenantIdOwned(poolCovid, lpInventory.amount - q.dShares, false); // reduced L inventory (P)\n const lpSharesOut = addressPresenceOwned(lpPubkey, q.dShares); // the LP's new shares (presence)\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const newRedeem = materializePoolCpScript(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares: q.newShares, lpCovid });\n const lpDepositRedeem = materializeKcc20Script(tokenTpl, lpDepositToken.state);\n const poolAResRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const poolLpInvRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, lpInventory.amount, false));\n\n // token-A group: inputs in tx order [LP deposit (input 1, presence), pool reserve (input 2, P)] → 1 output.\n const aStates = [poolTokenOut];\n const aWitnesses = [presenceWitnessIdx, 0];\n // L group: input [pool inventory (input 3, P)] → 2 outputs [reduced inventory, LP shares].\n const lStates = [poolLpOut, lpSharesOut];\n const lWitnesses = [0];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: addLiquiditySig(k, curRedeem, q.dKas, q.dToken, q.dShares, poolTokenOut, poolLpOut, lpSharesOut), redeem: curRedeem, role: 'pool' },\n { transactionId: lpDepositToken.transactionId, index: lpDepositToken.index, value: lpDepositToken.value, scriptPublicKey: kcc20Spk(k, lpDepositRedeem), signatureScript: transferSigScript(k, lpDepositRedeem, aStates, aWitnesses), redeem: lpDepositRedeem, role: 'lpDeposit' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolAResRedeem), signatureScript: transferSigScript(k, poolAResRedeem, aStates, aWitnesses), redeem: poolAResRedeem, role: 'poolToken' },\n { transactionId: lpInventory.transactionId, index: lpInventory.index, value: lpInventory.value, scriptPublicKey: kcc20Spk(k, poolLpInvRedeem), signatureScript: transferSigScript(k, poolLpInvRedeem, lStates, lWitnesses), redeem: poolLpInvRedeem, role: 'poolLpInventory' },\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpSpk(k, newRedeem), role: 'pool' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolLpOut)), role: 'poolLpInventory' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, lpSharesOut)), role: 'lpShares' },\n ];\n return { kind: 'addLiquidity', inputs, outputs, economics: { dKas: q.dKas, dToken: q.dToken, dShares: q.dShares, newShares: q.newShares }, covids: { poolCovid: hexOf(poolCovid), tokenCovid: hexOf(tokenCovid) } };\n}\n\n/**\n * removeLiquidity — return dShares of L to the pool inventory, withdraw a strictly-proportional dKas + dToken.\n * The withdrawn KAS is the tx change (the pool value drops by dKas·SCALE). The LP must supply an L UTXO of\n * EXACTLY dShares (full-UTXO) and a co-present P2PK input at `presenceWitnessIdx`. The covenant floor guard\n * (totalShares − dShares ≥ lockedShares) makes the graduation floor un-withdrawable.\n *\n * Inputs: [0]=pool [1]=pool token-A reserve(P) [2]=LP L shares(presence, =dShares)\n * Outputs: [0]=pool(shrunk) [1]=pool token-A reserve(P, newToken) [2]=LP withdrawn token(presence, dToken)\n * [3]=dShares returned to the pool L inventory(P)\n */\nexport function buildRemoveLiquidity(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, lpShares: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n poolCovid: Uint8Array, lpPubkey: Uint8Array, q: RemoveLiquidityQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (lpShares.state.amount !== q.dShares) throw new Error('LP shares UTXO must equal dShares exactly (split first)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, lpCovid } = utxo.state;\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false); // shrunk token-A reserve (P)\n const lpTokenOut = addressPresenceOwned(lpPubkey, q.dToken); // the LP's withdrawn token (presence)\n const poolLpOut = covenantIdOwned(poolCovid, q.dShares, false); // dShares returned to inventory (P)\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const newRedeem = materializePoolCpScript(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares: q.newShares, lpCovid });\n const poolAResRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const lpSharesRedeem = materializeKcc20Script(tokenTpl, lpShares.state);\n\n // token-A group: input [pool reserve (input 1, P)] → 2 outputs [shrunk reserve, LP withdrawn token].\n const aStates = [poolTokenOut, lpTokenOut];\n const aWitnesses = [0];\n // L group: input [LP shares (input 2, presence)] → 1 output [returned to pool inventory].\n const lStates = [poolLpOut];\n const lWitnesses = [presenceWitnessIdx];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: removeLiquiditySig(k, curRedeem, q.dShares, q.dKas, q.dToken, poolTokenOut, lpTokenOut, poolLpOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolAResRedeem), signatureScript: transferSigScript(k, poolAResRedeem, aStates, aWitnesses), redeem: poolAResRedeem, role: 'poolToken' },\n { transactionId: lpShares.transactionId, index: lpShares.index, value: lpShares.value, scriptPublicKey: kcc20Spk(k, lpSharesRedeem), signatureScript: transferSigScript(k, lpSharesRedeem, lStates, lWitnesses), redeem: lpSharesRedeem, role: 'lpShares' },\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpSpk(k, newRedeem), role: 'pool' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, lpTokenOut)), role: 'lpToken' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolLpOut)), role: 'poolLpInventory' },\n ];\n return { kind: 'removeLiquidity', inputs, outputs, economics: { dShares: q.dShares, dKas: q.dKas, dToken: q.dToken, newShares: q.newShares }, covids: { poolCovid: hexOf(poolCovid), tokenCovid: hexOf(tokenCovid) } };\n}\n\n// =================================================================================================\n// bindLp — one-time, permissionless genesis-mint of the LP-share token L + bind lpCovid into the pool\n// =================================================================================================\n\n/** The result of buildBindLp: the spend + the freshly-derived L covid + the inventory the pool now holds. */\nexport type BindLpResult = CovenantSpend & { lpCovidHex: string; lpInventoryAmount: bigint };\n\n/**\n * bindLp — runs once on a freshly-graduated pool (lpCovid == ZERO, totalShares == lockedShares). Genesis-mints\n * the FIXED supply (MAX_SHARES) of the LP-share token L: the floor (lockedShares) is burned to an unspendable\n * ZERO-covid owner, the rest (MAX_SHARES − lockedShares) seeds the pool's inventory (owned by the pool covid\n * P). L carries NO minter branch → its supply is fixed forever (mint-renounced, like token A's init). The pool\n * continuation carries lpCovid = the new L genesis covid; value + reserves + totalShares are unchanged.\n *\n * Inputs: [0]=pool (lpCovid == ZERO)\n * Outputs: [0]=pool(lpCovid bound) [1]=locked floor L(ZERO-owned, lockedShares) [2]=pool L inventory(P-owned)\n */\nexport function buildBindLp(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, poolCovid: Uint8Array, lockedShares: bigint, opts: { tokenDust?: bigint } = {},\n): BindLpResult {\n if (utxo.state.lpCovid.length !== 32 || !utxo.state.lpCovid.every((b) => b === 0)) throw new Error('pool lpCovid is already bound — bindLp is one-time');\n if (lockedShares < 1n || lockedShares >= MAX_SHARES) throw new Error('lockedShares out of range');\n if (utxo.state.totalShares !== lockedShares) throw new Error('bindLp requires totalShares == lockedShares (graduation state)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid } = utxo.state;\n const inventoryAmount = MAX_SHARES - lockedShares;\n const lpFloor = covenantIdOwned(ZERO32, lockedShares, false); // floor → unspendable ZERO covid\n const lpInventory = covenantIdOwned(poolCovid, inventoryAmount, false); // inventory → pool covid P\n\n const floorSpk = kcc20Spk(k, materializeKcc20Script(tokenTpl, lpFloor));\n const invSpk = kcc20Spk(k, materializeKcc20Script(tokenTpl, lpInventory));\n // L genesis covid = KIP-20 id over the pool UTXO outpoint (tx input 0) + the two L genesis outputs (idx 1,2).\n const lpCovidHex = genesisCovenantId(k, { transactionId: utxo.transactionId, index: utxo.index }, [\n { index: 1, value: dust, scriptPublicKey: floorSpk },\n { index: 2, value: dust, scriptPublicKey: invSpk },\n ]);\n const boundLp = covidToBytes(lpCovidHex);\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const boundRedeem = materializePoolCpScript(tpl, { kasReserve, tokenReserve, tokenCovid, totalShares: lockedShares, lpCovid: boundLp });\n const poolValue = kasReserve * SCALE;\n\n const b = new SigScriptBuilder(k);\n pushKcc20StateScalar(b, lpFloor); pushKcc20StateScalar(b, lpInventory);\n const bindSig = b.selector(POOL_CP_SELECTOR.bindLp).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: poolValue, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: bindSig, redeem: curRedeem, role: 'pool' },\n ];\n const outputs: CovOutput[] = [\n { value: poolValue, scriptPublicKey: poolCpSpk(k, boundRedeem), role: 'pool' },\n { value: dust, scriptPublicKey: floorSpk, role: 'lpFloor' },\n { value: dust, scriptPublicKey: invSpk, role: 'lpInventory' },\n ];\n return { kind: 'bindLp', inputs, outputs, economics: { lockedShares, inventoryAmount }, covids: { poolCovid: hexOf(poolCovid), tokenCovid: hexOf(tokenCovid) }, lpCovidHex, lpInventoryAmount: inventoryAmount };\n}\n","// amm_pool_cp_v3 swap builders — SINGLE-TOKEN swaps (the LIVE deployed pool). Reuses the shared pool state,\n// quotes, address derivation, and LP builders from poolCpTx.ts; only the two swap entrypoints differ.\n//\n// V3 (see docs/DESIGN-single-token-swaps.md): swaps are symmetric so every trade is ONE tx / ONE signature /\n// ONE resulting token UTXO — no pre-split, no fragmentation.\n// • sell: the trader folds PART of a piece into the pool and gets the UNSOLD remainder back as one\n// presence-owned change output. covid-A outputs = [pool reserve] or [pool reserve, trader change(LAST)].\n// • buy: the trader may ALSO input their EXISTING token UTXO(s); the bought amount is merged into ONE output.\n//\n// The pool STATE layout, address derivation, and CP quotes are IDENTICAL to v2 — only the compiled script (and\n// thus the P2SH address) differs, plus the swap tx in/out shapes. So this module REUSES the v2 state/quote/\n// address helpers and only re-implements the two swap builders + the sell sig (which gains traderChangeOut).\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder } from './sigscript.js';\nimport {\n type Kcc20State, type Kcc20Template,\n materializeKcc20Script, kcc20Spk, covenantIdOwned, addressPresenceOwned, pushKcc20StateScalar, transferSigScript,\n} from './kcc20Tx.js';\nimport { SCALE } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\nimport {\n type PoolCpTemplate, type PoolCpState, type PoolCpParams, type PoolCpUtxo,\n type PoolCpBuyQuote, type PoolCpSellQuote,\n materializePoolCpScript, poolCpSpk, poolCpAddress, poolCpSpkForState, quotePoolCpBuy, quotePoolCpSell,\n} from './poolCpTx.js';\n\ntype K = Kaspa;\n\n// v3 pool == v2 pool state/template/quote; only the script (P2SH address) + swap tx shapes differ. Aliases so\n// callers can speak in v3 terms while the splice/derivation logic stays one battle-tested implementation.\nexport type PoolCpV3Template = PoolCpTemplate;\nexport type PoolCpV3State = PoolCpState;\nexport type PoolV3Params = PoolCpParams;\nexport type PoolCpV3Utxo = PoolCpUtxo;\nexport const materializePoolCpV3Script = materializePoolCpScript;\nexport const poolCpV3Spk = poolCpSpk;\nexport const poolCpV3SpkForState = poolCpSpkForState;\nexport const poolCpV3Address = poolCpAddress;\nexport const quotePoolV3Buy = quotePoolCpBuy; // pricing is unchanged from v2 (merge is a tx-build concern)\nexport const quotePoolV3Sell = quotePoolCpSell; // `tokenIn` here is the amount FOLDED; change is a tx-build concern\n\n/** v3 pool entrypoint selectors (same declaration order as v2). */\nexport const POOL_V3_SELECTOR = { swapKasForToken: 0, swapTokenForKas: 1, addLiquidity: 2, removeLiquidity: 3, bindLp: 4 } as const;\n\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\nconst p2pkSpk = (k: any, pubkey: Uint8Array) => { const sb = new k.ScriptBuilder(); sb.addData(pubkey).addOp(172); return new k.ScriptPublicKey(0, sb.drain()); };\n\nfunction v3SwapBuySig(k: K, redeem: Uint8Array, kasInUnits: bigint, tokenOut: bigint, poolTokenOut: Kcc20State, traderTokenOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasInUnits).int(tokenOut);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, traderTokenOut);\n return b.selector(POOL_V3_SELECTOR.swapKasForToken).redeem(redeem).drain();\n}\n// v3 sell takes (kasOut, poolTokenOut, traderChangeOut) — the change state is pushed even on a full sell (the\n// covenant only validates it when a 2nd covid-A output exists; otherwise it's an ignored placeholder).\nfunction v3SwapSellSig(k: K, redeem: Uint8Array, kasOutUnits: bigint, poolTokenOut: Kcc20State, traderChangeOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasOutUnits);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, traderChangeOut);\n return b.selector(POOL_V3_SELECTOR.swapTokenForKas).redeem(redeem).drain();\n}\n\n/** swapKasForToken (v3 — MERGE): buy `q.tokenOut`, optionally merging the buyer's EXISTING token UTXO(s)\n * (`mergeTokens`, presence-owned, authorized by the co-present P2PK at `presenceWitnessIdx`) into ONE trader\n * output of amount `tokenOut + Σ(existing)`. With no mergeTokens it's a plain buy. Outputs: [0]=pool [1]=pool\n * token(P) [2]=trader token(presence, merged) [3]=creatorFee [4]=platformFee. kcc20 conservation pins the merge. */\nexport function buildPoolV3SwapKasForToken(\n k: K, tpl: PoolCpV3Template, tokenTpl: Kcc20Template, params: PoolV3Params,\n utxo: PoolCpV3Utxo, poolCovid: Uint8Array, traderPubkey: Uint8Array, q: PoolCpBuyQuote,\n mergeTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[] = [],\n presenceWitnessIdx = 0, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid } = utxo.state;\n const mergeSum = mergeTokens.reduce((s, t) => s + t.state.amount, 0n);\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false);\n const traderTokenOut = addressPresenceOwned(traderPubkey, q.tokenOut + mergeSum);\n const curRedeem = materializePoolCpV3Script(tpl, utxo.state);\n const newRedeem = materializePoolCpV3Script(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares, lpCovid });\n const poolTokInRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n // covid-A inputs: pool token (witness=pool input 0), then each merged existing token (presence → P2PK witness).\n const witnesses = [0, ...mergeTokens.map(() => presenceWitnessIdx)];\n const newStates = [poolTokenOut, traderTokenOut];\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpV3Spk(k, curRedeem), signatureScript: v3SwapBuySig(k, curRedeem, q.kasInUnits, q.tokenOut, poolTokenOut, traderTokenOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolTokInRedeem), signatureScript: transferSigScript(k, poolTokInRedeem, newStates, witnesses), redeem: poolTokInRedeem, role: 'poolToken' },\n ...mergeTokens.map((tt) => {\n const r = materializeKcc20Script(tokenTpl, tt.state);\n return { transactionId: tt.transactionId, index: tt.index, value: tt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'traderToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpV3Spk(k, newRedeem), role: 'pool' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderTokenOut)), role: 'trader' },\n { value: q.creatorOut, scriptPublicKey: p2pkSpk(k, params.creatorFeeOwner), role: 'creatorFee' },\n { value: q.platformOut, scriptPublicKey: p2pkSpk(k, params.platformFeeOwner), role: 'platformFee' },\n ];\n return { kind: 'swapKasForToken', inputs, outputs, economics: { kasIn: q.kasIn, tokenOut: q.tokenOut }, covids: { poolCovid: hexOf(poolCovid), tokenCovid: hexOf(tokenCovid) } };\n}\n\n/** swapTokenForKas (v3 — FRACTIONAL): fold `q.tokenIn` of the trader's piece(s) into the pool, getting kasOut;\n * the UNSOLD remainder (Σ trader inputs − q.tokenIn) returns as ONE presence-owned change output (placed LAST).\n * Outputs: [0]=pool [1]=pool token(P) [2]=creatorFee [3]=platformFee [4]=OPTIONAL trader change(presence). */\nexport function buildPoolV3SwapTokenForKas(\n k: K, tpl: PoolCpV3Template, tokenTpl: Kcc20Template, params: PoolV3Params,\n utxo: PoolCpV3Utxo, poolCovid: Uint8Array, traderPubkey: Uint8Array,\n traderTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n q: PoolCpSellQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (traderTokens.length < 1) throw new Error('need at least one trader token');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid } = utxo.state;\n const traderIn = traderTokens.reduce((s, t) => s + t.state.amount, 0n);\n const change = traderIn - q.tokenIn; // q.tokenIn == the amount folded into the reserve\n if (change < 0n) throw new Error('trader inputs are less than the sell amount');\n const hasChange = change > 0n;\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false);\n const traderChangeOut = addressPresenceOwned(traderPubkey, hasChange ? change : 1n); // dummy(1) on a full sell — the covenant ignores it\n const curRedeem = materializePoolCpV3Script(tpl, utxo.state);\n const newRedeem = materializePoolCpV3Script(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares, lpCovid });\n const poolTokInRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const witnesses = [0, ...traderTokens.map(() => presenceWitnessIdx)];\n // covid-A outputs in tx order: pool reserve first (idx 1), then the change LAST (idx 4) when present.\n const newStates = hasChange ? [poolTokenOut, traderChangeOut] : [poolTokenOut];\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpV3Spk(k, curRedeem), signatureScript: v3SwapSellSig(k, curRedeem, q.kasOutUnits, poolTokenOut, traderChangeOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolTokInRedeem), signatureScript: transferSigScript(k, poolTokInRedeem, newStates, witnesses), redeem: poolTokInRedeem, role: 'poolToken' },\n ...traderTokens.map((tt) => {\n const r = materializeKcc20Script(tokenTpl, tt.state);\n return { transactionId: tt.transactionId, index: tt.index, value: tt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'traderToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpV3Spk(k, newRedeem), role: 'pool' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken' },\n { value: q.creatorOut, scriptPublicKey: p2pkSpk(k, params.creatorFeeOwner), role: 'creatorFee' },\n { value: q.platformOut, scriptPublicKey: p2pkSpk(k, params.platformFeeOwner), role: 'platformFee' },\n ];\n if (hasChange) outputs.push({ value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderChangeOut)), role: 'trader' });\n return { kind: 'swapTokenForKas', inputs, outputs, economics: { kasOut: q.kasOut, tokenIn: q.tokenIn }, covids: { poolCovid: hexOf(poolCovid), tokenCovid: hexOf(tokenCovid) } };\n}\n","// Dev-allocation VESTING covenant builder — wires vesting.sil into Kaspa transactions. The lock OWNS the dev\n// allocation (a covid-A kcc20 token) and releases it to the creator's presence only as it vests (gated by\n// tx.locktime). This module covers the claim side (claim / claimFinal) against an already-deployed lock.\n//\n// State region (silverc state_layout {start:1, len:9}): off 1: 0x08 <claimed: 8-byte LE int>.\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20Template,\n type Kcc20State,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n// entrypoint selectors — vesting.sil declares claim then claimFinal\nexport const VEST_SELECTOR = { claim: 0, claimFinal: 1 } as const;\n\n/** Tokens vested by DAA score `daaScore` (linear from startScore over durationScore; capped at total). Mirrors\n * the covenant's cross-multiplied bound exactly, so the flow can offer `vested − claimed` to claim. */\nexport function vestedAmount(total: bigint, startScore: number, durationScore: number, daaScore: number): bigint {\n if (daaScore <= startScore) return 0n;\n const elapsed = BigInt(daaScore - startScore);\n const dur = BigInt(durationScore);\n if (elapsed >= dur) return total;\n return (total * elapsed) / dur;\n}\n\n/** Fixed per-token vesting parameters (baked into the lock script by silverc). */\nexport type VestingParams = {\n creatorIdentifier: string; // x-only pubkey hex (the only allowed recipient)\n total: number; // dev allocation locked\n startScore: number; // vesting start (tx.locktime units)\n durationScore: number; // linear release length\n};\nexport type VestingTemplate = { script: Uint8Array; stateStart: number; stateLen: number; params: VestingParams };\n\n// --- state splice (off `stateStart`, 9 bytes): 0x08 <claimed:8 LE> -----------------------------\nexport function materializeVestingScript(tpl: VestingTemplate, claimed: bigint): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x08) throw new Error('vesting template has an unexpected state layout (expected push8 claimed)');\n if (claimed < 0n) throw new Error('claimed must be non-negative');\n const out = t.slice();\n out[s] = 0x08;\n out.set(int8LE(claimed), s + 1);\n return out;\n}\n\nexport const vestingSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const vestingSpkForState = (k: K, tpl: VestingTemplate, claimed: bigint): Spk => vestingSpk(k, materializeVestingScript(tpl, claimed));\n\nexport type VestUtxo = { transactionId: string; index: number; value: bigint };\n\n/**\n * Partial claim: release `release` (0 < release < remaining) to the creator's presence, re-lock the rest under\n * V. inputs [vesting(0), lockedToken(1)]; outputs [vesting cont(0), relock(1, A/V-owned), recipient(2, A/creator)].\n * The flow must set tx.lockTime = current DAA score (consensus blocks the tx until then; the covenant reads it).\n */\nexport function buildVestingClaim(\n k: K,\n vestTpl: VestingTemplate,\n tokenTpl: Kcc20Template,\n vestingUtxo: VestUtxo,\n lockedToken: VestUtxo,\n vestingCovid: Uint8Array,\n creatorPubkey: Uint8Array,\n claimed: bigint,\n release: bigint,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n const total = BigInt(vestTpl.params.total);\n if (claimed < 0n || claimed >= total) throw new Error('nothing left to claim');\n const remaining = total - claimed;\n if (release <= 0n || release >= remaining) throw new Error('partial claim must be > 0 and < remaining (use claimFinal to drain)');\n const dust = opts.tokenDust ?? 1000n;\n const newClaimed = claimed + release, newRemaining = remaining - release;\n\n const curRedeem = materializeVestingScript(vestTpl, claimed);\n const newRedeem = materializeVestingScript(vestTpl, newClaimed);\n const lockedState: Kcc20State = covenantIdOwned(vestingCovid, remaining, false);\n const relockState: Kcc20State = covenantIdOwned(vestingCovid, newRemaining, false);\n const recipientState: Kcc20State = addressPresenceOwned(creatorPubkey, release);\n const lockedRedeem = materializeKcc20Script(tokenTpl, lockedState);\n\n const b = new SigScriptBuilder(k).int(release);\n pushKcc20StateScalar(b, relockState);\n pushKcc20StateScalar(b, recipientState);\n const claimSig = b.selector(VEST_SELECTOR.claim).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: vestingUtxo.transactionId, index: vestingUtxo.index, value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, curRedeem), signatureScript: claimSig, redeem: curRedeem, role: 'vesting' },\n { transactionId: lockedToken.transactionId, index: lockedToken.index, value: lockedToken.value, scriptPublicKey: kcc20Spk(k, lockedRedeem), signatureScript: transferSigScript(k, lockedRedeem, [relockState, recipientState], [0]), redeem: lockedRedeem, role: 'lockedToken' },\n ];\n const outputs: CovOutput[] = [\n { value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, newRedeem), role: 'vesting' }, // V continuation (claimed bumped)\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, relockState)), role: 'relock' }, // re-locked (A, V-owned)\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, recipientState)), role: 'recipient' }, // to creator (A, presence)\n ];\n return { kind: 'claim', inputs, outputs, economics: { release, newClaimed } };\n}\n\n/** Final claim: once fully vested, pay ALL remaining to the creator and continue V with claimed=total (husk).\n * inputs [vesting(0), lockedToken(1)]; outputs [vesting cont(0), recipient(1, A/creator)]. */\nexport function buildVestingClaimFinal(\n k: K,\n vestTpl: VestingTemplate,\n tokenTpl: Kcc20Template,\n vestingUtxo: VestUtxo,\n lockedToken: VestUtxo,\n vestingCovid: Uint8Array,\n creatorPubkey: Uint8Array,\n claimed: bigint,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n const total = BigInt(vestTpl.params.total);\n if (claimed < 0n || claimed >= total) throw new Error('nothing left to claim');\n const remaining = total - claimed;\n const dust = opts.tokenDust ?? 1000n;\n\n const curRedeem = materializeVestingScript(vestTpl, claimed);\n const newRedeem = materializeVestingScript(vestTpl, total); // husk: fully claimed\n const lockedState: Kcc20State = covenantIdOwned(vestingCovid, remaining, false);\n const recipientState: Kcc20State = addressPresenceOwned(creatorPubkey, remaining);\n const lockedRedeem = materializeKcc20Script(tokenTpl, lockedState);\n\n const b = new SigScriptBuilder(k);\n pushKcc20StateScalar(b, recipientState);\n const claimSig = b.selector(VEST_SELECTOR.claimFinal).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: vestingUtxo.transactionId, index: vestingUtxo.index, value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, curRedeem), signatureScript: claimSig, redeem: curRedeem, role: 'vesting' },\n { transactionId: lockedToken.transactionId, index: lockedToken.index, value: lockedToken.value, scriptPublicKey: kcc20Spk(k, lockedRedeem), signatureScript: transferSigScript(k, lockedRedeem, [recipientState], [0]), redeem: lockedRedeem, role: 'lockedToken' },\n ];\n const outputs: CovOutput[] = [\n { value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, newRedeem), role: 'vesting' },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, recipientState)), role: 'recipient' },\n ];\n return { kind: 'claimFinal', inputs, outputs, economics: { release: remaining } };\n}\n","export * from './types.js';\nexport { ExampleWalletAdapter } from './example.js';\n","// Wallet abstraction — one interface, swappable implementations. This is the shape KRON's non-custodial\n// signing flow needs: build the transaction, hand specific inputs to a wallet to sign, broadcast. It is NOT\n// an officially standardized Kaspa wallet API (none exists yet — see README) — a working pattern this\n// package promotes as a reusable interface, illustrated by the generic reference implementation in\n// `example.ts`. See `docs/WALLETS.md` for how to implement this against a real wallet's injected provider.\n//\n// Capability-flag pattern: every signing method beyond `connect`/`getAddress`/`disconnect` is OPTIONAL on\n// the interface, because not every wallet implements every capability — check `capabilities()` rather than\n// assuming a method exists.\nexport type Provider = string;\nexport type Connected = { provider: Provider; address: string };\n\n/** Which of the optional signing capabilities a given adapter instance actually implements. Check this\n * before relying on a method — an adapter that returns `signPskt: false` will throw if you call it anyway. */\nexport type WalletCapabilities = {\n signPskt: boolean;\n getXOnlyPublicKey: boolean;\n signMessage: boolean;\n reconnect: boolean;\n};\n\nexport interface WalletAdapter {\n readonly provider: Provider;\n readonly label: string;\n isAvailable(): boolean;\n /** Which optional methods this adapter actually implements (vs. throws on call). */\n capabilities(): WalletCapabilities;\n /** Connect/authorize; resolves to the active kaspa:/kaspatest: address. */\n connect(): Promise<string>;\n /** Silently restore a prior session on page load WITHOUT prompting the user (an already-authorized\n * accounts lookup with no popup, if the wallet supports one). Resolves to the address, or null if there\n * is nothing to restore. */\n reconnect?(): Promise<string | null>;\n getAddress(): string | null;\n /**\n * The signPskt wallet bridge: sign ONLY the listed inputs (the user's P2PK inputs) of a tx (Safe JSON)\n * and return the signed tx (Safe JSON). Covenant inputs are never signed by the wallet — their\n * transition rules / presence-based ownership authorize them. This is what makes sell/transfer work with\n * existing wallets without KRON ever holding a key. See ../native/spend.ts `toPsktJson`.\n */\n signPskt?(txJsonString: string, signInputs: { index: number; sighashType?: number }[]): Promise<string>;\n /** The connected account's 32-byte x-only pubkey hex (the curve/pool fee owner at deploy, or a\n * presence-owned token's owner identifier). null if unavailable. */\n getXOnlyPublicKey?(): Promise<string | null>;\n /** Sign a UTF-8 message with the account key (KIP-5 Kaspa message-signing scheme — see README \"Message\n * signing\"). Returns the Schnorr signature hex + the signer's x-only pubkey hex. null if unavailable. */\n signMessage?(message: string): Promise<{ signature: string; publicKey: string } | null>;\n disconnect(): void;\n}\n\n/** Thrown by a wallet adapter method that exists on the interface but isn't implemented by a given wallet.\n * Distinct from a generic Error so callers can detect \"not supported\" vs. \"failed\". */\nexport class WalletCapabilityError extends Error {\n constructor(public readonly provider: Provider, public readonly method: string, hint?: string) {\n super(`${provider} does not implement ${method}()${hint ? ` — ${hint}` : ''}`);\n this.name = 'WalletCapabilityError';\n }\n}\n","// A generic, illustrative reference implementation of WalletAdapter — NOT tied to any specific wallet\n// product. It targets the shape most Kaspa browser-extension wallets already use for a plain send (an\n// injected `window.<walletName>` object with account/connect/sign methods), applied to the signPskt bridge\n// described in docs/WALLETS.md. Copy this file and point `GLOBAL_NAME` (and the method calls, if your\n// wallet's shape differs — see docs/WALLETS.md \"Writing your own adapter\") at your own injected provider.\nimport type { WalletAdapter, WalletCapabilities } from './types.js';\n\n/** Replace with the property name your wallet injects on `window`/`globalThis`. */\nconst GLOBAL_NAME = 'exampleWallet';\n\nconst provider = (): any => {\n const p = (globalThis as any)[GLOBAL_NAME];\n if (!p) throw new Error(`${GLOBAL_NAME} not installed`);\n return p;\n};\n\n/**\n * ExampleWalletAdapter — a template, not a real integration. It assumes a provider shaped like:\n * requestAccounts(): Promise<string[]>\n * getAccounts(): Promise<string[]> // already-authorized, no popup\n * signPskt({ txJsonString, options: { signInputs } }): Promise<string | { txJsonString }>\n * getPublicKey(): Promise<string> // compressed hex\n * signMessage(text: string): Promise<string> // KIP-5 scheme\n * If your wallet's provider looks different (a different method name, a different sighash encoding, a\n * different signing call shape entirely), adapt the method bodies accordingly — the `WalletAdapter`\n * interface only constrains what you expose, not how you get there.\n */\nexport class ExampleWalletAdapter implements WalletAdapter {\n readonly provider = GLOBAL_NAME;\n readonly label = 'Example Wallet (template)';\n private address: string | null = null;\n\n isAvailable() {\n return typeof (globalThis as any)[GLOBAL_NAME] !== 'undefined';\n }\n\n capabilities(): WalletCapabilities {\n return { signPskt: true, getXOnlyPublicKey: true, signMessage: true, reconnect: true };\n }\n\n async connect(): Promise<string> {\n const p = provider();\n const accounts: string[] = await p.requestAccounts();\n this.address = accounts?.[0] ?? null;\n if (!this.address) throw new Error('No account authorized');\n return this.address;\n }\n\n async reconnect(): Promise<string | null> {\n const p = (globalThis as any)[GLOBAL_NAME];\n if (!p) return null;\n try {\n const accounts: string[] = (await p.getAccounts?.()) ?? [];\n if (!accounts.length) return null;\n this.address = accounts[0];\n return this.address;\n } catch { return null; }\n }\n\n getAddress() { return this.address; }\n\n async signPskt(txJsonString: string, signInputs: { index: number; sighashType?: number }[]): Promise<string> {\n const p = provider();\n const options = { signInputs: signInputs.map((s) => ({ index: s.index, sighashType: s.sighashType ?? 1 })) };\n const res: any = await p.signPskt({ txJsonString, options });\n return typeof res === 'string' ? res : (res?.txJsonString ?? res?.signedTx ?? res?.tx ?? JSON.stringify(res));\n }\n\n async getXOnlyPublicKey(): Promise<string | null> {\n const p = provider();\n const pub: string | undefined = await p.getPublicKey?.();\n if (!pub) return null;\n const hex = pub.replace(/^0x/, '');\n return hex.length >= 64 ? hex.slice(-64) : null; // drop the 02/03 compression prefix -> 32-byte x-only\n }\n\n async signMessage(message: string): Promise<{ signature: string; publicKey: string } | null> {\n const p = provider();\n const publicKey = await this.getXOnlyPublicKey();\n if (!publicKey) return null;\n const signature: string = await p.signMessage(message);\n return { signature, publicKey };\n }\n\n disconnect() { this.address = null; }\n}\n","export { IndexerClient } from './indexerClient.js';\nexport { RegistryClient } from './registryClient.js';\nexport { SequencerClient } from './sequencerClient.js';\n","// Typed wrapper for the KCC-20 indexer's REST + SSE surface (docs/INTEGRATION.md §4 in the kron repo).\n// Uses the common Kaspa token-indexer response shape ({ message, result }) so existing tooling adapts with\n// minimal changes. Amounts are decimal strings in base units (apply `dec` to render); KAS values inside\n// `cpState` are sompi unless noted as SCALE units.\n\nexport type Envelope<T> = { message: string; result: T };\n\nexport type CpState = {\n realKas: number;\n tokenReserve: number;\n graduated: boolean;\n poolTokenReserve?: number;\n poolKas?: number;\n poolTotalShares?: number;\n poolLpCovid?: string;\n};\n\nexport type TokenInfo = {\n tick: string; name: string; dec: number; max: string; minted: string; holderTotal: number;\n covenantId: string; curveCovenantId: string; poolCovenantId: string | null; graduated: boolean;\n tokenReserve: string; cpState: CpState;\n price?: number; change24h?: number; volume24h?: number; volumeTotal?: number;\n trades24h?: number; tradesTotal?: number; tvl?: number; reserveKas?: string;\n};\n\nexport type Balance = { tick: string; balance: string; dec: number };\nexport type TokenUtxo = {\n outpoint: { transactionId: string; index: number };\n amount: string;\n scriptPublicKey: string;\n redeemScriptHex: string;\n ownerAddress: string;\n};\nexport type PoolHead = {\n pool: { transactionId: string; index: number };\n poolToken: { transactionId: string; index: number };\n reserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n};\nexport type LpUtxo = { outpoint: { transactionId: string; index: number }; amount: string };\nexport type LpEarnings = { tick: string; address: string; earnedKas: string };\nexport type IndexerInfo = { tokenTotal: number; daaScore: number; synced: boolean; network: string };\nexport type Trade = Record<string, unknown>;\nexport type Holder = { address: string; balance: string };\nexport type Ohlc = { t: number; o: number; h: number; l: number; c: number; v: number };\n\nasync function fetchJson<T>(url: string): Promise<T> {\n const res = await fetch(url);\n if (!res.ok) throw new Error(`${url} -> HTTP ${res.status}`);\n const body: Envelope<T> = await res.json();\n return body.result;\n}\n\nconst qs = (params: Record<string, string | number | undefined>): string => {\n const parts = Object.entries(params).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`);\n return parts.length ? `?${parts.join('&')}` : '';\n};\n\nexport class IndexerClient {\n /** @param baseUrl e.g. 'https://idx.kron.technology/v1/kcc20' (TN10) — no default baked in; pass the\n * network-appropriate URL explicitly (mainnet endpoints publish separately at launch). */\n constructor(private baseUrl: string) {}\n\n info(): Promise<IndexerInfo> { return fetchJson(`${this.baseUrl}/info`); }\n markets(opts: { kind?: 'curve' | 'pool' } = {}): Promise<TokenInfo[]> { return fetchJson(`${this.baseUrl}/markets${qs(opts)}`); }\n topTraders(): Promise<unknown[]> { return fetchJson(`${this.baseUrl}/top-traders`); }\n\n token(tick: string): Promise<TokenInfo> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}`); }\n balance(tick: string, address: string): Promise<Balance> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/address/${encodeURIComponent(address)}`);\n }\n tokenlist(address: string): Promise<Balance[]> { return fetchJson(`${this.baseUrl}/address/${encodeURIComponent(address)}/tokenlist`); }\n tokenUtxos(tick: string, address: string): Promise<TokenUtxo[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/address/${encodeURIComponent(address)}/utxos`);\n }\n\n holders(tick: string): Promise<Holder[]> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/holders`); }\n trades(tick: string, opts: { offset?: number; limit?: number } = {}): Promise<Trade[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/trades${qs(opts)}`);\n }\n ohlc(tick: string, opts: { interval: string; from?: number; to?: number }): Promise<Ohlc[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/ohlc${qs(opts)}`);\n }\n addressTrades(address: string): Promise<Trade[]> { return fetchJson(`${this.baseUrl}/address/${encodeURIComponent(address)}/trades`); }\n\n poolhead(tick: string): Promise<PoolHead> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/poolhead`); }\n\n lpUtxos(tick: string, address: string): Promise<LpUtxo[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/lp/${encodeURIComponent(address)}/utxos`);\n }\n lpEarnings(tick: string, address: string): Promise<LpEarnings> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/lp/${encodeURIComponent(address)}/earnings`);\n }\n\n /**\n * Subscribe to the SSE update stream (all tokens, or one if `tick` is given). Returns an unsubscribe\n * function. Browser: uses the native EventSource. Node: pass an EventSource-compatible constructor (e.g.\n * the `eventsource` npm package) via `EventSourceImpl` — Node has no built-in EventSource on most\n * supported versions.\n */\n stream(onUpdate: (data: unknown) => void, opts: { tick?: string; EventSourceImpl?: typeof EventSource } = {}): () => void {\n const ES = opts.EventSourceImpl ?? (globalThis as any).EventSource;\n if (!ES) throw new Error('No EventSource available — in Node, pass EventSourceImpl (e.g. from the \"eventsource\" package)');\n const es = new ES(`${this.baseUrl}/stream${qs({ tick: opts.tick })}`);\n es.addEventListener('update', (ev: MessageEvent) => {\n try { onUpdate(JSON.parse(ev.data)); } catch { /* ignore malformed events */ }\n });\n return () => es.close();\n }\n}\n","// Typed wrapper for KRON's token metadata registry (docs/INTEGRATION.md §4 \"Token metadata registry\" in the\n// kron repo). The indexer is the source of truth for amounts/trading state; this registry holds *display*\n// metadata the creator signed (name, description, image, social links, the `cp` deploy record). Read-only\n// here on purpose — registry WRITES are signature-gated to the on-chain creator key, which is out of scope\n// for a generic SDK client (a wallet/bot integrating KRON generally only needs to read this).\n\nexport type CpCurveParamsRecord = {\n creatorFeeOwner: string; platformFeeOwner: string;\n vKas: number; graduationKas: number;\n creatorFeeBps: number; platformFeeBps: number; graduationFeeBps: number;\n dexCreatorFeeBps: number; dexPlatformFeeBps: number;\n dexLpFeeBps?: number; poolLockedShares?: number; vestingCovid?: string;\n};\n\nexport type RegistryToken = {\n tick: string; name: string; creator: string; txid: string; dec: number; max: string;\n description?: string; image?: string;\n links?: { website?: string; x?: string; telegram?: string };\n cp: { curveParams: CpCurveParamsRecord; tokenCovid?: string; curveCovid?: string; poolCovid?: string; genesisTxid?: string };\n chainVerified?: boolean;\n};\n\n/** One entry of the public token list (GET /api/registry/tokenlist). tokenlists.org-shaped: the EVM-core\n * fields (network/covenantId/symbol/name/decimals/logoURI) plus a KRON `extensions` block. `covenantId`\n * (covid A) is the canonical TOKEN id (add-to-wallet / asset id); `extensions.poolCovenantId` (covid P) is\n * the POOL/PAIR id, non-null only post-graduation. `extensions.genesisTxid` is the proof pointer used by\n * verify.verifyTokenListEntry. Mirrors the `GET /api/registry/tokenlist` response contract. */\nexport type TokenListEntry = {\n network: string;\n covenantId: string;\n symbol: string; name: string; decimals: number;\n logoURI?: string;\n extensions: {\n curveCovenantId: string | null;\n poolCovenantId: string | null;\n genesisTxid: string | null;\n creator: string | null;\n creatorPubkey: string | null;\n curveParams: CpCurveParamsRecord | null;\n graduated: boolean;\n chainVerified: boolean;\n };\n};\n\n/** The token-list envelope (tokenlists.org shape). `version.minor` tracks the token count so a consumer can\n * cheaply detect list changes. */\nexport type TokenList = {\n name: string;\n timestamp: string;\n version: { major: number; minor: number; patch: number };\n network: string;\n keywords: string[];\n tokens: TokenListEntry[];\n};\n\nexport class RegistryClient {\n /** @param baseUrl e.g. 'https://api.kron.technology' (TN10) */\n constructor(private baseUrl: string) {}\n\n async tokens(): Promise<RegistryToken[]> {\n const res = await fetch(`${this.baseUrl}/api/registry/tokens`);\n if (!res.ok) throw new Error(`registry tokens -> HTTP ${res.status}`);\n const body: { tokens: RegistryToken[] } = await res.json();\n return body.tokens;\n }\n\n /** Fetch the public token list — a tokenlists.org-shaped index of KRON tokens for wallets/explorers/\n * aggregators. Default = chain-verified tokens only (anti-phishing); `{ all: true }` adds unverified ones\n * (each tagged `extensions.chainVerified:false`). Verify any entry against the chain with\n * verify.verifyTokenListEntry before trusting it. */\n async tokenlist(opts?: { all?: boolean }): Promise<TokenList> {\n const q = opts?.all ? '?all=1' : '';\n const res = await fetch(`${this.baseUrl}/api/registry/tokenlist${q}`);\n if (!res.ok) throw new Error(`registry tokenlist -> HTTP ${res.status}`);\n return (await res.json()) as TokenList;\n }\n}\n","// Typed wrapper for KRON's sequencer (docs/INTEGRATION.md §6 in the kron repo). A non-custodial batcher\n// that orders signed txs into a valid mempool chain — it never holds keys. Covers BOTH markets:\n// • graduated-pool swaps (`/head` + `/submit`, keyed by the pool P2SH), and\n// • pre-graduation bonding-curve buys/sells (`/curve/head` + `/curve/submit`, keyed by the curve covid) —\n// the curve is also a single mutable UTXO, so trades chain exactly like pool swaps.\n// Direct node submission also works under low contention; the sequencer is a convenience for hot markets.\n// `health()` reports which markets the deployed sequencer supports (`markets: ['pool','curve']`).\n\nexport type SequencerHead = {\n head: {\n poolOutpoint: { transactionId: string; index: number };\n poolTokenOutpoint: { transactionId: string; index: number };\n reserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n };\n depth: number;\n};\n\nexport type SubmitResult =\n | { ok: true; txid: string; position: number }\n | { ok: false; reason: string; retry: boolean };\n\n/** The curve head a client builds a pre-graduation buy/sell against: the curve covenant UTXO\n * (`poolOutpoint` slot) + the curve-owned token inventory (`poolTokenOutpoint` slot). `head` is null when\n * no chain is in flight (depth 0) — resolve your own live head from the node/indexer in that case. */\nexport type CurveSequencerHead = {\n poolOutpoint: { transactionId: string; index: number };\n poolTokenOutpoint: { transactionId: string; index: number };\n reserves: { realKas: string; tokenReserve: string; vKas: string };\n};\nexport type CurveHeadResult =\n | { ok: true; head: CurveSequencerHead | null; depth: number }\n | { ok: false; reason: string };\n\nexport class SequencerClient {\n /** @param baseUrl e.g. 'https://seq.kron.technology' (TN10) */\n constructor(private baseUrl: string) {}\n\n async health(): Promise<{ ok: boolean; markets?: ('pool' | 'curve')[]; attribution?: boolean }> {\n const res = await fetch(`${this.baseUrl}/health`);\n return res.json();\n }\n\n /** The in-flight head + queue depth for a pool — use this instead of the indexer's confirmed `poolhead`\n * when the pool is busy, so you build on the latest unconfirmed state. */\n async head(poolP2sh: string): Promise<SequencerHead> {\n const res = await fetch(`${this.baseUrl}/head?pool=${encodeURIComponent(poolP2sh)}`);\n if (!res.ok) throw new Error(`sequencer head -> HTTP ${res.status}`);\n return res.json();\n }\n\n /** Enqueue a signed swap tx built against a `head()` snapshot. A 409-shaped `{ok:false, retry:true}`\n * means `prevHead` is stale — re-fetch `head()` and rebuild.\n *\n * `ref` (optional) — your wallet-integrator partner tag (kron.technology/wallets): 2–32 chars of\n * `a-z 0-9 - _`, case-insensitive. Tagged trades are recorded server-side per-trade and count toward\n * your revenue share; a malformed tag is rejected with 400 so a misconfigured integration fails on the\n * first submit rather than silently at settlement. Only sequencer-routed trades carry attribution. */\n async submit(body: {\n pool: string;\n signedTx: string;\n prevHead: SequencerHead['head'];\n declaredReserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n ref?: string;\n }): Promise<SubmitResult> {\n const res = await fetch(`${this.baseUrl}/submit`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return res.json();\n }\n\n /** The in-flight curve head + queue depth for a pre-graduation token, keyed by its curve covenant id\n * (hex). `head: null` with `ok: true` means no chain is in flight — build against the confirmed state\n * from the node/indexer instead. A `{ok:false}` gate (unknown/full/unreachable) → submit direct. */\n async curveHead(curveCovid: string): Promise<CurveHeadResult> {\n const res = await fetch(`${this.baseUrl}/curve/head?covid=${encodeURIComponent(curveCovid)}`);\n if (!res.ok && res.status !== 409) throw new Error(`sequencer curve head -> HTTP ${res.status}`);\n return res.json();\n }\n\n /** Enqueue a signed pre-graduation buy/sell built against a `curveHead()` snapshot. A 409-shaped\n * `{ok:false, retry:true}` means `prevHead` is stale — re-fetch `curveHead()` and rebuild.\n * `ref` — optional partner tag, same contract as `submit()`. */\n async curveSubmit(body: {\n covid: string;\n signedTx: string;\n prevHead: CurveSequencerHead;\n declaredReserves: { realKas: string; tokenReserve: string; vKas: string };\n ref?: string;\n }): Promise<SubmitResult> {\n const res = await fetch(`${this.baseUrl}/curve/submit`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return res.json();\n }\n\n /** SSE: head changes for a pool. Same Node-EventSource caveat as IndexerClient.stream. */\n events(poolP2sh: string, onEvent: (data: unknown) => void, EventSourceImpl?: typeof EventSource): () => void {\n const ES = EventSourceImpl ?? (globalThis as any).EventSource;\n if (!ES) throw new Error('No EventSource available — in Node, pass EventSourceImpl (e.g. from the \"eventsource\" package)');\n const es = new ES(`${this.baseUrl}/events?pool=${encodeURIComponent(poolP2sh)}`);\n es.onmessage = (ev: MessageEvent) => { try { onEvent(JSON.parse(ev.data)); } catch { /* ignore malformed events */ } };\n return () => es.close();\n }\n}\n","export { verifyTokenListEntry, kaspaRestFetchTx } from './tokenList.js';\nexport type { VerifyResult, FetchedTx, FetchTx } from './tokenList.js';\n","// Verify a token-list entry against the chain. The token list (RegistryClient.tokenlist) is self-verifiable\n// by design: each entry carries its covenantId (covid A) + a genesisTxid proof pointer, so a consumer can\n// confirm the token is a genuine on-chain covenant and not a registry spoof — WITHOUT trusting KRON's\n// backend. This is the anti-phishing check every wallet/explorer/aggregator should run before listing an\n// entry.\n//\n// The check: fetch the entry's genesis tx and confirm its covenantId appears as a `covenant_id` on one of\n// the tx's outputs (that is exactly where a KIP-20 covenant is created — proven against api-tn10). A forged\n// entry claiming a covenantId that isn't on its declared genesis tx fails.\n//\n// `fetchTx` is INJECTED: this SDK ships no Kaspa node/REST client (its own clients only talk to KRON's\n// backend/indexer). Use `kaspaRestFetchTx(baseUrl)` for the common Kaspa REST shape, or pass your own\n// (node RPC, a proxy, a fixture). NOTE: this does not re-derive the curve P2SH from params — the SDK has no\n// covenant compiler. For a full cryptographic re-derivation, feed the init tx's outpoint + authorized\n// outputs to `genesis.genesisCovenantId` (see src/native/genesis.ts).\nimport type { TokenListEntry } from '../client/registryClient.js';\n\n/** Minimal shape of a fetched Kaspa transaction — only what the verifier reads. `covenant_id` is the\n * Kaspa REST field; `covenantId` is accepted too for node/proxy shapes that camel-case it. */\nexport type FetchedTx = { outputs?: Array<{ covenant_id?: string | null; covenantId?: string | null } | null> };\nexport type FetchTx = (txid: string) => Promise<FetchedTx>;\n\nexport type VerifyResult = { ok: boolean; covenantIdPresent: boolean; reason?: string };\n\nconst lc = (s?: string | null): string => String(s ?? '').toLowerCase();\n\n/** Verify a single token-list entry against the chain via an injected tx fetcher. Never throws — a fetch\n * failure or a missing field is returned as `{ ok: false, reason }` so callers can filter a whole list. */\nexport async function verifyTokenListEntry(entry: TokenListEntry, fetchTx: FetchTx): Promise<VerifyResult> {\n const covid = lc(entry?.covenantId);\n const txid = entry?.extensions?.genesisTxid ?? null;\n if (!covid) return { ok: false, covenantIdPresent: false, reason: 'entry has no covenantId' };\n if (!txid) return { ok: false, covenantIdPresent: false, reason: 'entry has no genesisTxid to verify against' };\n\n let tx: FetchedTx;\n try {\n tx = await fetchTx(txid);\n } catch (e: any) {\n return { ok: false, covenantIdPresent: false, reason: `fetchTx failed for ${txid}: ${e?.message ?? e}` };\n }\n\n const outs = Array.isArray(tx?.outputs) ? tx.outputs : [];\n const present = outs.some((o) => lc(o?.covenant_id ?? o?.covenantId) === covid);\n return present\n ? { ok: true, covenantIdPresent: true }\n : { ok: false, covenantIdPresent: false, reason: `covenantId ${entry.covenantId} not found on any output of genesis tx ${txid}` };\n}\n\n/** A `fetchTx` for the common Kaspa REST shape: `GET {baseUrl}/transactions/{txid}?outputs=true`. Uses the\n * global `fetch` (Node ≥20 / browsers). Pass your own fetcher instead for a node RPC or a proxy. */\nexport function kaspaRestFetchTx(baseUrl: string): FetchTx {\n const base = baseUrl.replace(/\\/+$/, '');\n return async (txid: string): Promise<FetchedTx> => {\n const res = await fetch(`${base}/transactions/${encodeURIComponent(txid)}?outputs=true`);\n if (!res.ok) throw new Error(`kaspa REST tx ${txid} -> HTTP ${res.status}`);\n return (await res.json()) as FetchedTx;\n };\n}\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,IAAM,QAAQ;AAGd,IAAM,cAAc;AAC3B,IAAM,SAAS,CAAC,MAAe,IAAI,cAAc,IAAI;AAI9C,IAAM,UAAU;AAYvB,IAAM,UAAU,CAAC,GAAW,OAAe,IAAI,IAAI,MAAM;AAQlD,IAAM,uBAAuB;AAE7B,IAAM,qBAAqB,CAAC,KAAa,QAAwB,MAAO,MAAM,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC,IAAK;AAMtH,SAAS,WAAW,GAAY,YAAuC;AAC5E,QAAM,KAAK,aAAa;AACxB,QAAM,QAAQ,KAAK;AACnB,MAAI,SAAS,GAAI,QAAO;AACxB,QAAM,aAAa,EAAE,UAAU;AAC/B,MAAI,aAAa,QAAS,QAAO;AACjC,QAAM,KAAK,EAAE,UAAU;AACvB,QAAM,KAAK,EAAE,OAAO,MAAM,EAAE;AAC5B,QAAM,WAAW,QAAQ,GAAG,EAAE,OAAO,KAAK,EAAE;AAC5C,QAAM,WAAW,EAAE,eAAe;AAClC,MAAI,YAAY,GAAI,QAAO;AAC3B,QAAM,aAAa,OAAQ,QAAQ,EAAE,gBAAiB,MAAM;AAC5D,QAAM,cAAc,OAAQ,QAAQ,EAAE,iBAAkB,MAAM;AAC9D,QAAM,MAAM,aAAa;AACzB,SAAO,EAAE,OAAO,UAAU,YAAY,aAAa,KAAK,OAAO,QAAQ,KAAK,YAAY,iBA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AA,EACzB,SAAS,GAAQ;AACf,WAAO,EAAE,IAAI,OAAO,mBAAmB,OAAO,QAAQ,sBAAsB,IAAI,KAAK,GAAG,WAAW,CAAC,GAAG;AAAA,EACzG;AAEA,QAAM,OAAO,MAAM,QAAQ,IAAI,OAAO,IAAI,GAAG,UAAU,CAAC;AACxD,QAAM,UAAU,KAAK,KAAK,CAAC,MAAM,GAAG,GAAG,eAAe,GAAG,UAAU,MAAM,KAAK;AAC9E,SAAO,UACH,EAAE,IAAI,MAAM,mBAAmB,KAAK,IACpC,EAAE,IAAI,OAAO,mBAAmB,OAAO,QAAQ,cAAc,MAAM,UAAU,0CAA0C,IAAI,GAAG;AACpI;AAIO,SAAS,iBAAiB,SAA0B;AACzD,QAAM,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AACvC,SAAO,OAAO,SAAqC;AACjD,UAAM,MAAM,MAAM,MAAM,GAAG,IAAI,iBAAiB,mBAAmB,IAAI,CAAC,eAAe;AACvF,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,iBAAiB,IAAI,YAAY,IAAI,MAAM,EAAE;AAC1E,WAAQ,MAAM,IAAI,KAAK;AAAA,EACzB;AACF;","names":["SCALE","padFee","ceilDiv","ceilDiv","padFee","b","SCALE","padFee","ZERO32","hexOf","hexOf","p2pkSpk","provider"]}
|
|
1
|
+
{"version":3,"sources":["../src/curve/cpCurve.ts","../src/native/sigscript.ts","../src/native/genesis.ts","../src/native/spend.ts","../src/native/kcc20Tx.ts","../src/native/curveCpTx.ts","../src/native/poolCpTx.ts","../src/native/poolCpV3Tx.ts","../src/native/vestingTx.ts","../src/wallet/index.ts","../src/wallet/types.ts","../src/wallet/example.ts","../src/client/index.ts","../src/client/indexerClient.ts","../src/client/registryClient.ts","../src/client/sequencerClient.ts","../src/verify/index.ts","../src/verify/tokenList.ts"],"sourcesContent":["// Virtual-reserve constant-product bonding-curve math — mirrors the curve_cp.sil covenant EXACTLY (BigInt,\n// same SCALE / ceil rules) so quotes match what the covenant enforces. The inventory model: a fixed\n// inventory is sold/bought at a constant-product price using a virtual KAS reserve; nothing is minted or burned.\nexport const SCALE = 1_000_000n; // 1e6 sompi = 0.01 KAS — the KAS step used in the CP invariant\n// Fee/payment outputs can't be sub-dust (KIP-9 storage mass ≈ C/value), so on-chain fee outputs are padded to\n// this floor; quotes reflect the padded amount so the displayed total/net matches what's actually paid.\nexport const FEE_OUT_MIN = 20_000_000n; // 0.2 TKAS\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\n// int64-safety ceiling on the curve UTXO value (sompi) — mirrors curve_cp.sil MAX_KAS. A buy may overbuy PAST\n// graduationKas (excess → LP at graduation); this is the only upper bound on a single buy. 9e14 is essentially\n// the int64 ceiling: the covenant's graduation `gradFee·10000` peaks at ~9e18 (~2.5% under 2^63).\nexport const MAX_KAS = 900_000_000_000_000n; // 9e14 sompi = 9,000,000 TKAS\n\n/** Live curve state for quoting. realKas/graduationKas are sompi; vKas is in SCALE units; tokenReserve whole. */\nexport type CpState = {\n realKas: bigint; // curve UTXO value (sompi) = KAS raised so far\n tokenReserve: bigint; // curve inventory remaining (whole tokens)\n vKas: bigint; // virtual KAS reserve (SCALE units) — sets the opening price\n graduationKas: bigint; // raised-KAS target (sompi) that unlocks graduation\n creatorFeeBps: bigint; // e.g. 70n\n platformFeeBps: bigint; // e.g. 30n\n};\n\nconst ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\n\n// --- slippage protection ---------------------------------------------------------------------------\n// The covenant fixes the trade's output amount into the signed tx and only enforces the constant-product\n// FLOOR (it won't let you take MORE than fair), so it does NOT stop the app from baking a WORSE-than-shown\n// amount if the curve/pool state moved (another trade landed first) or a node fed stale/bad reserves. Fetch\n// fresh state at build time and abort if the achievable output drops below the user-agreed minimum =\n// (quote they saw) − tolerance. Default 1%.\nexport const DEFAULT_SLIPPAGE_BPS = 100;\n/** Minimum acceptable output after a slippage tolerance (bps). `out` is tokenOut (buy) or net KAS (sell). */\nexport const minOutWithSlippage = (out: bigint, bps: number): bigint => out - (out * BigInt(Math.max(0, Math.round(bps)))) / 10000n;\n\nexport type CpBuyQuote = { kasIn: bigint; tokenOut: bigint; creatorFee: bigint; platformFee: bigint; fee: bigint; total: bigint; newRealKas: bigint; newTokenReserve: bigint };\nexport type CpSellQuote = { tokenIn: bigint; kasOut: bigint; creatorFee: bigint; platformFee: bigint; fee: bigint; net: bigint; newRealKas: bigint; newTokenReserve: bigint };\n\n/** Buy: spend `kasInSompi` into the reserve (floored to a SCALE step) → tokenOut, plus the fee on top. */\nexport function quoteCpBuy(s: CpState, kasInSompi: bigint): CpBuyQuote | null {\n const ki = kasInSompi / SCALE; // floor to a whole SCALE step (the covenant requires kasIn % SCALE == 0)\n const kasIn = ki * SCALE;\n if (kasIn <= 0n) return null;\n const newRealKas = s.realKas + kasIn;\n if (newRealKas > MAX_KAS) return null; // overbuy past graduationKas is allowed; only the int64 ceiling caps a buy\n const ru = s.realKas / SCALE;\n const K = (s.vKas + ru) * s.tokenReserve;\n const newToken = ceilDiv(K, s.vKas + ru + ki); // pool keeps ≥ the CP tokens (floor check passes)\n const tokenOut = s.tokenReserve - newToken;\n if (tokenOut <= 0n) return null;\n const creatorFee = padFee((kasIn * s.creatorFeeBps) / 10000n);\n const platformFee = padFee((kasIn * s.platformFeeBps) / 10000n);\n const fee = creatorFee + platformFee;\n return { kasIn, tokenOut, creatorFee, platformFee, fee, total: kasIn + fee, newRealKas, newTokenReserve: newToken };\n}\n\n/** Sell: return `tokenIn` tokens to inventory → kasOut sompi (a SCALE step), minus the fee. */\nexport function quoteCpSell(s: CpState, tokenIn: bigint): CpSellQuote | null {\n if (tokenIn <= 0n) return null;\n const ru = s.realKas / SCALE;\n const K = (s.vKas + ru) * s.tokenReserve;\n const newToken = s.tokenReserve + tokenIn;\n const minKasUnits = ceilDiv(K, newToken) - s.vKas; // min units the pool must keep so it isn't drained\n const newKasUnits = minKasUnits < 0n ? 0n : minKasUnits;\n const kasOutUnits = ru - newKasUnits;\n if (kasOutUnits <= 0n) return null; // sell too small to refund a whole SCALE step\n const kasOut = kasOutUnits * SCALE;\n const creatorFee = padFee((kasOut * s.creatorFeeBps) / 10000n);\n const platformFee = padFee((kasOut * s.platformFeeBps) / 10000n);\n const fee = creatorFee + platformFee;\n return { tokenIn, kasOut, creatorFee, platformFee, fee, net: kasOut - fee, newRealKas: s.realKas - kasOut, newTokenReserve: newToken };\n}\n\n/** Marginal price in sompi per token: (vKas + realKas/SCALE) · SCALE / tokenReserve. */\nexport function cpPrice(s: CpState): number {\n if (s.tokenReserve <= 0n) return 0;\n const ru = s.realKas / SCALE;\n return Number((s.vKas + ru) * SCALE) / Number(s.tokenReserve);\n}\n\n/** Progress to graduation (0..100), measured by KAS raised vs the target. */\nexport function cpProgress(s: CpState): number {\n return s.graduationKas > 0n ? Math.min(100, (Number(s.realKas) / Number(s.graduationKas)) * 100) : 0;\n}\n\n/** Tokens sold so far (circulating from the curve) = initial inventory − current inventory. */\nexport const cpSold = (initialInventory: bigint, tokenReserve: bigint): bigint => initialInventory - tokenReserve;\n","// SilverScript signature-script argument ABI — a faithful TS port of the compiler's `build_sig_script`. A\n// covenant is spent with a P2SH input whose signature script is:\n// <encoded entrypoint args...> [<selector>] <redeemScript>\n// This module encodes the entrypoint args exactly as the compiler does, so the bytes the VM sees match what\n// `silverc` would build.\n//\n// The encoding rules (from build_sig_script / push_typed_sigscript_arg / encode_array_literal):\n// • Scalar arg / single-struct field — pushed individually (push_sigscript_arg):\n// int → addI64 (minimal CScriptNum) bool → addI64(0|1)\n// byte → addData([b]) byte[N]/pubkey/sig → addData(raw bytes)\n// A STRUCT arg pushes each field in declared order using these scalar rules.\n// • Struct-array arg (e.g. kcc20 `transfer`'s `State[]`) — COLUMN-MAJOR: for each struct field, the\n// field's value across all elements is gathered into a dynamic array and pushed as ONE item, using the\n// FIXED-WIDTH element encoding (encode_fixed_size_value): int → 8-byte LE, bool → 1 byte, byte → 1 byte,\n// byte[N] → N raw bytes. (Note the asymmetry: a scalar int field uses minimal addI64, but an int inside\n// an array column is fixed 8-byte LE.)\n// • Plain dynamic arrays — byte[] → addData(bytes); int[]/bool[]/sig[] → fixed-width-concat → addData.\n// • Selector — the entrypoint's branch index (declaration order among entrypoints) is appended via addI64,\n// UNLESS the contract has a single entrypoint (then it is omitted).\n//\n// No top-level SDK import (only `import type`) — the caller passes the loaded WASM namespace `k`, so this\n// runs unchanged in the browser and under Node.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\n\n/** 8-byte little-endian encoding of a non-negative int (encode_fixed_size_value for `int`, width 8). */\nexport function int8LE(v: bigint): Uint8Array {\n const out = new Uint8Array(8);\n let x = BigInt.asUintN(64, v);\n for (let i = 0; i < 8; i++) {\n out[i] = Number(x & 0xffn);\n x >>= 8n;\n }\n return out;\n}\n\nconst concat = (parts: Uint8Array[]): Uint8Array => {\n const len = parts.reduce((s, p) => s + p.length, 0);\n const out = new Uint8Array(len);\n let o = 0;\n for (const p of parts) {\n out.set(p, o);\n o += p.length;\n }\n return out;\n};\n\n/**\n * A SilverScript ScriptBuilder wrapper that records pushes in the compiler's order, then drains to hex.\n * Use the scalar push helpers for struct fields / scalar args and the column helpers for struct arrays,\n * then `selector()` (if multi-entrypoint) and `redeem()` last (the standard P2SH spend layout).\n */\nexport class SigScriptBuilder {\n sb: any;\n constructor(k: K) {\n this.sb = new (k as any).ScriptBuilder({ flags: { covenantsEnabled: true } });\n }\n /** int scalar (minimal CScriptNum). */\n int(v: bigint): this {\n this.sb.addI64(v);\n return this;\n }\n /** bool scalar → 1|0 via addI64 (matches push_sigscript_arg Bool). */\n bool(b: boolean): this {\n this.sb.addI64(b ? 1n : 0n);\n return this;\n }\n /** single byte → addData([b]). */\n byte(b: number): this {\n this.sb.addData(Uint8Array.of(b & 0xff));\n return this;\n }\n /** raw bytes (byte[N], pubkey, sig, byte[]) → addData. */\n data(bytes: Uint8Array): this {\n this.sb.addData(bytes);\n return this;\n }\n /** a column of N values pushed as one fixed-width-concatenated array item (encode_array_literal). */\n column(items: Uint8Array[]): this {\n this.sb.addData(concat(items));\n return this;\n }\n /** the entrypoint selector (branch index). Omit for single-entrypoint contracts. */\n selector(index: number): this {\n this.sb.addI64(BigInt(index));\n return this;\n }\n /** the P2SH redeem script (pushed last; the VM pops it, hash-checks, then runs it on the arg stack). */\n redeem(script: Uint8Array): this {\n this.sb.addData(script);\n return this;\n }\n /** finalize → signature-script hex. */\n drain(): string {\n return this.sb.drain();\n }\n}\n","// KIP-20 genesis covenant-id (the native track's identity primitive). A covenant-id `A` is assigned by\n// consensus when a covenant UTXO is first created (\"genesis\"): it is a CovenantID-keyed blake2b-256 over\n// the spending tx's first-input outpoint and the set of authorized outputs (see\n// rusty-kaspa/consensus/core/src/hashing/covenant_id.rs). A forged id raises WrongGenesisCovenantId.\n//\n// The vendored Kaspa WASM SDK already ships the consensus implementation as `covenantId(...)`, so we wrap\n// it rather than re-deriving the keyed blake2b. ONE non-obvious gotcha (cost real time to find upstream):\n// the SDK's `covenantId` only matches consensus when each authorized output's `scriptPublicKey` is passed\n// as a {version, script} object (or a ScriptPublicKey instance) — a BARE HEX STRING silently produces a\n// wrong id. `payToScriptHashScript()` returns a ScriptPublicKey instance, so pass that straight through.\n//\n// No top-level SDK import (only `import type`) so this runs in the browser (caller passes the loaded `k`)\n// and under Node. Returns/consumes covenant-ids as 32-byte big-endian hex (no 0x), the shape used across the\n// native builders and the indexer API.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\n/** SDK ScriptPublicKey instance, or a plain {version, script-hex} object. Kept loose, matching SDK style. */\ntype Spk = any;\n\n/** The genesis outpoint = the spending tx's FIRST input outpoint (`tx.inputs[0]`). */\nexport type GenesisOutpoint = { transactionId: string; index: number };\n\n/** An output the genesis outpoint authorizes for covenant-id derivation (its index + the output itself). */\nexport type AuthOutput = { index: number; value: bigint; scriptPublicKey: Spk };\n\nconst hexToBytes = (h: string): Uint8Array =>\n Uint8Array.from((h.replace(/^0x/, '').match(/../g) ?? []).map((b) => parseInt(b, 16)));\nconst bytesToHex = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/**\n * Compute the KIP-20 genesis covenant-id (32-byte hex, no 0x) for a covenant UTXO created by a tx whose\n * first input is `genesisOutpoint` and whose authorized outputs are `authOutputs`. Byte-exact with\n * consensus. Used to:\n * - bind the curve `C` ↔ its token `A` (curve_cp `init`),\n * - pre-compute the pool covenant-id `P` a graduation will assign,\n * - derive a freshly-created covenant's own id client-side before broadcast.\n */\nexport function genesisCovenantId(k: K, genesisOutpoint: GenesisOutpoint, authOutputs: AuthOutput[]): string {\n const auth = authOutputs.map((o) => ({\n index: o.index,\n // Normalize to a plain { version, script-hex } object — the form the SDK serializes to match consensus.\n // A bare hex string OR a ScriptPublicKey *instance* both yield a (different) wrong id; only this works.\n output: { value: o.value, scriptPublicKey: { version: o.scriptPublicKey.version ?? 0, script: o.scriptPublicKey.script ?? o.scriptPublicKey } },\n }));\n return (k as any).covenantId(genesisOutpoint, auth).toString();\n}\n\n/** Covenant-ids are byte[32] in the covenants; convert between the hex form and bytes for state encoding. */\nexport const covidToBytes = (covidHex: string): Uint8Array => hexToBytes(covidHex);\nexport const bytesToCovid = (u8: Uint8Array): string => bytesToHex(u8);\n\n/** The all-zero covenant-id placeholder (a curve's `tokenCovid` before `init` binds it; ZERO_COVID). */\nexport const ZERO_COVID = '00'.repeat(32);\n","// Native covenant-spend assembly — shared types + the tx-assembly layer for the native (KCC-20) builders.\n// A native action (init/buy/sell/graduate/swap) yields a `CovenantSpend`: the covenant INPUTS it spends\n// (each pre-scripted — the covenant's own transition rules authorize the spend, so no key signature) and\n// the covenant-required OUTPUTS (continuation, minted/moved token balances, fee). This module bolts on the\n// trader's funding inputs + change to make a complete Kaspa transaction.\n//\n// Covenant transactions are Toccata/KIP-20 **version-1** transactions:\n// • covenant outputs must carry a `CovenantBinding(authorizingInput, covenantId)` — without it the output\n// never enters the covenant-id group, so in-covenant checks like `OpCovOutputCount(id)` see 0 outputs\n// and the spend fails on-chain with \"script ran, but verification failed\" (a v0 output CANNOT carry a\n// binding, so a v0 tx can never satisfy a covenant that validates its outputs);\n// • each input carries a `computeBudget` (v1 replaces sigOpCount as the execution-metering commitment) —\n// a P2PK funding input needs ~10, a kcc20 transfer input ~500, a curve/pool input ~2000.\n// Set `binding` on each covenant `CovOutput` (the kcc20 builders do this when given the token covenant id);\n// `assembleNativeTx` attaches the WASM `CovenantBinding` and role-based compute budgets.\n//\n// Production signing path: the app builds the tx here, the wallet signs only the trader's P2PK funding\n// inputs via its signPskt-equivalent bridge (see ../wallet/types.ts), and the app broadcasts — covenant\n// inputs never need a wallet signature. `toPsktJson` shapes the tx + the funding-input indices for that\n// bridge. (The sighash commits to output covenant bindings, so bindings must be attached BEFORE signing.)\n//\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** Covenant txs are KIP-20 v1 transactions (covenant outputs require tx.version >= 1). */\nexport const TX_VERSION = 1;\n/** Per-input compute budget (v1): a P2PK funding input ≈ one sig op. */\nexport const FUNDING_COMPUTE = 10;\n/** Per-input compute budget (v1): a kcc20 `transfer` input (token balance / inventory / seller piece). */\nexport const TOKEN_COMPUTE = 500;\n/** Per-input compute budget (v1): a curve_cp / amm_pool_cp input (the large redeem scripts). */\nexport const COVENANT_COMPUTE = 2000;\n/** Covenant output min value (KIP-9 storage mass) — the conventional token-UTXO dust, 0.5 KAS. */\nexport const COVENANT_DUST = 50_000_000n;\n\n/** A covenant output's KIP-20 lineage: which covenant id it continues and which input authorizes it. */\nexport type CovBinding = { covid: string; authorizingInput: number };\n\n/** A covenant UTXO being spent, already carrying its signature script (no wallet signature needed). */\nexport type CovInput = {\n transactionId: string;\n index: number;\n value: bigint;\n scriptPublicKey: Spk;\n /** the covenant signature script (hex): <args> [selector] <redeem>, or kcc20 <transfer args> <redeem>. */\n signatureScript: string;\n /** redeem script bytes (kept so a caller can re-derive / inspect the spend). */\n redeem: Uint8Array;\n /** what this input is, for assembly/debugging: 'curve' | 'minterBranch' | 'burn' | 'pool' | 'poolToken'. */\n role: string;\n /** v1 compute budget override; defaults by role (curve/pool → COVENANT_COMPUTE, else TOKEN_COMPUTE). */\n computeBudget?: number;\n};\n\n/** A covenant-required output (value + scriptPublicKey [+ covenant binding]). */\nexport type CovOutput = { value: bigint; scriptPublicKey: Spk; role: string; binding?: CovBinding };\n\n/** A complete covenant action: the inputs it spends + the outputs it must create + computed economics. */\nexport type CovenantSpend = {\n kind: 'init' | 'initVested' | 'buy' | 'sell' | 'transfer' | 'graduate' | 'swapKasForToken' | 'swapTokenForKas' | 'addLiquidity' | 'removeLiquidity' | 'bindLp' | 'claim' | 'claimFinal';\n inputs: CovInput[];\n outputs: CovOutput[];\n economics: Record<string, bigint>;\n /** covenant-ids this action establishes/uses (hex): the bound token `A`, a new pool `P`, the curve `C`. */\n covids?: { tokenCovid?: string; poolCovid?: string; curveCovid?: string };\n};\n\n/** A funding UTXO entry (SDK UtxoEntryReference from rpc.getUtxosByAddresses, or a plain IUtxoEntry). */\nexport type FundingEntry = any;\n\nconst SUBNET_ZERO = '0000000000000000000000000000000000000000';\n\nconst budgetForRole = (role: string): number => (role === 'curve' || role === 'pool' ? COVENANT_COMPUTE : TOKEN_COMPUTE);\n\nexport type AssembledNativeTx = {\n transaction: any;\n /** indices of inputs the trader/wallet must sign (the covenant inputs come first and are pre-scripted). */\n fundingInputIndexes: number[];\n totalIn: bigint;\n covenantOut: bigint;\n change: bigint;\n};\n\n/**\n * Assemble a complete v1 covenant tx: the spend's covenant inputs (pre-scripted) + the trader's funding\n * inputs + a change output. Covenant outputs whose `binding` is set carry the KIP-20 `CovenantBinding`\n * (REQUIRED for any output the covenant validates — see the module header). `networkFee` is\n * caller-provided; size it with `estimateNativeFee` (v1 fees must cover the per-input compute budget, so a\n * flat legacy fee is usually too low). Covenant inputs default to a role-based compute budget; funding\n * inputs are signed via signFundingInputs (or the signPskt bridge).\n */\nexport function assembleNativeTx(\n k: K,\n opts: { spend: CovenantSpend; fundingEntries: FundingEntry[]; changeAddress: string; networkFee: bigint },\n): AssembledNativeTx {\n const { spend, fundingEntries, changeAddress, networkFee } = opts;\n const kk = k as any;\n\n const covInputs = spend.inputs.map(\n (ci) =>\n new kk.TransactionInput({\n previousOutpoint: { transactionId: ci.transactionId, index: ci.index },\n signatureScript: ci.signatureScript,\n sequence: 0n,\n sigOpCount: 0,\n computeBudget: ci.computeBudget ?? budgetForRole(ci.role),\n utxo: {\n outpoint: { transactionId: ci.transactionId, index: ci.index },\n amount: ci.value,\n scriptPublicKey: ci.scriptPublicKey,\n blockDaaScore: 0n,\n isCoinbase: false,\n },\n }),\n );\n const fundingInputs = fundingEntries.map(\n (e) => new kk.TransactionInput({ previousOutpoint: e.outpoint, signatureScript: '', sequence: 0n, sigOpCount: 0, computeBudget: FUNDING_COMPUTE, utxo: e }),\n );\n\n const covInValue = spend.inputs.reduce((s, ci) => s + ci.value, 0n);\n const fundingTotal = fundingEntries.reduce((s, e) => s + BigInt(e.amount), 0n);\n const totalIn = covInValue + fundingTotal;\n const covenantOut = spend.outputs.reduce((s, o) => s + o.value, 0n);\n const change = totalIn - covenantOut - networkFee;\n if (change < 0n) throw new Error(`insufficient funding: need ${covenantOut + networkFee} sompi, have ${totalIn}`);\n\n const outputs = spend.outputs.map((o) =>\n o.binding\n ? new kk.TransactionOutput(o.value, o.scriptPublicKey, new kk.CovenantBinding(o.binding.authorizingInput, new kk.Hash(o.binding.covid)))\n : new kk.TransactionOutput(o.value, o.scriptPublicKey),\n );\n outputs.push(new kk.TransactionOutput(change, kk.payToAddressScript(changeAddress)));\n\n const transaction = new kk.Transaction({\n version: TX_VERSION,\n inputs: [...covInputs, ...fundingInputs],\n outputs,\n lockTime: 0n,\n gas: 0n,\n payload: '',\n subnetworkId: SUBNET_ZERO,\n });\n return {\n transaction,\n fundingInputIndexes: fundingInputs.map((_, i) => i + covInputs.length),\n totalIn,\n covenantOut,\n change,\n };\n}\n\n/**\n * Size `networkFee` for an assembled v1 tx: byte/storage mass (via the WASM mass calculator, with\n * placeholder signatures on the funding inputs so byte mass is realistic) + the per-input compute budget\n * the calculator omits (grams = budget × 100), at `feeRateSompiPerGram` (use the node's feerate estimate;\n * min-relay on TN10 has been ~100 sompi/gram), with a 1.5× over-cover and a 10_000-sompi floor. Assemble\n * with a guess (e.g. 10_000n), call this, then re-assemble with the returned fee.\n */\nexport function estimateNativeFee(k: K, networkId: string, asm: AssembledNativeTx, feeRateSompiPerGram: number): bigint {\n const kk = k as any;\n const tx = asm.transaction;\n const ins = tx.inputs;\n const saved = asm.fundingInputIndexes.map((i: number) => ins[i].signatureScript);\n for (const i of asm.fundingInputIndexes) ins[i].signatureScript = '00'.repeat(66); // placeholder sig → realistic byte mass\n tx.inputs = ins;\n let byteMass = 2000n;\n try { byteMass = BigInt(kk.calculateTransactionMass(networkId, tx)); } catch { /* fall back */ }\n const ins2 = tx.inputs;\n asm.fundingInputIndexes.forEach((i: number, j: number) => (ins2[i].signatureScript = saved[j]));\n tx.inputs = ins2;\n let computeGrams = 0n;\n for (const inp of tx.inputs) computeGrams += BigInt(inp.computeBudget || 0) * 100n;\n const rate = BigInt(Math.max(Math.ceil(feeRateSompiPerGram), 1));\n const fee = ((byteMass + computeGrams) * rate * 3n) / 2n;\n return fee > 10000n ? fee : 10000n;\n}\n\n/** Sign the trader's funding inputs (P2PK) in place; covenant inputs are left untouched (pre-scripted). */\nexport function signFundingInputs(k: K, tx: any, privKey: any, fundingInputIndexes: number[]): any {\n const inputs = tx.inputs;\n for (const idx of fundingInputIndexes) {\n const sig = (k as any).createInputSignature(tx, idx, privKey);\n inputs[idx].signatureScript = new (k as any).ScriptBuilder().addData(sig).drain();\n }\n tx.inputs = inputs;\n return tx;\n}\n\n/**\n * Shape the assembled tx for a signPskt-style wallet bridge. Returns the tx JSON the wallet deserializes\n * plus the inputs it should sign (the trader's P2PK funding inputs only).\n */\nexport function toPsktJson(asm: AssembledNativeTx, sighashType = 1): { txJsonString: string; signInputs: { index: number; sighashType: number }[] } {\n return {\n txJsonString: asm.transaction.serializeToSafeJSON(),\n signInputs: asm.fundingInputIndexes.map((index) => ({ index, sighashType })),\n };\n}\n\n/**\n * The local side of a signPskt-style wallet bridge: deserialize a tx (Safe JSON), sign ONLY the listed\n * inputs with `privKey` (the user's P2PK inputs — funding, or the co-present presence input that authorizes\n * a sell/transfer of an address-owned token), reserialize to Safe JSON. Covenant inputs (not listed) are\n * left untouched: their transition rules — or the presence-based ownership check against a co-present\n * signed P2PK input — authorize them, so the wallet never signs a covenant P2SH input directly. This is\n * exactly what an extension wallet's native `signPskt({ txJsonString, options: { signInputs } })` does; use\n * this function to emulate that bridge with a raw key (e.g. for a backend bot holding its own key).\n */\nexport function signPsktWithKey(k: K, txJsonString: string, signInputs: { index: number }[], privKey: any): string {\n const kk = k as any;\n const tx = kk.Transaction.deserializeFromSafeJSON(txJsonString);\n const inputs = tx.inputs;\n for (const { index } of signInputs) {\n const sig = kk.createInputSignature(tx, index, privKey);\n inputs[index].signatureScript = new kk.ScriptBuilder().addData(sig).drain();\n }\n tx.inputs = inputs;\n return tx.serializeToSafeJSON();\n}\n","// KCC-20 native covenant-token transaction builder — wires kcc20.sil into Kaspa transactions. NO rollup.\n//\n// A token balance is a covenant P2SH UTXO whose redeem script carries a fixed-width 46-byte state region:\n// off 0 : 0x20 <ownerIdentifier:32> off 33: 0x01 <identifierType:1>\n// off 35: 0x08 <amount: 8-byte LE> off 44: 0x01 <isMinter:1>\n// Everything outside the region is identical for a given (maxIns,maxOuts), so a new-balance redeem script\n// is produced by SPLICING — no recompile at spend time.\n//\n// `transfer(State[] newStates, sig[] sigs, byte[] witnesses)` is the single entrypoint (no selector). It\n// authorizes each covenant input by its ownership mode, validates each output's state via the covenant-id\n// group, and enforces conservation unless the active branch isMinter (mint/burn). The curve & pool own\n// token balances by COVENANT-ID (mode 0x02, no signature), which is what makes atomic mint/swap possible.\n//\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport type { CovInput, CovOutput, CovenantSpend } from './spend.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** kcc20 identifierType (ownership mode) values — dispatched by `transfer`'s checkSigs. */\nexport const IDENTIFIER = { PUBKEY: 0, SCRIPT_HASH: 1, COVENANT_ID: 2, ADDRESS: 3 } as const;\nexport type IdentifierType = (typeof IDENTIFIER)[keyof typeof IDENTIFIER];\n\n/** A kcc20 token balance's full state (the 4 reference fields). `ownerIdentifier` is 32 bytes. */\nexport type Kcc20State = {\n ownerIdentifier: Uint8Array;\n identifierType: IdentifierType;\n amount: bigint;\n isMinter: boolean;\n};\n\n/** Compiled token template: silverc output at the genesis state + the (maxIns,maxOuts) it was built for. */\nexport type Kcc20Template = { script: Uint8Array; stateStart: number; maxIns: number; maxOuts: number };\n\nconst STATE_LEN = 46;\n\n// --- redeem-script materialization (the 46-byte state splice) -----------------------------------\n\n/** Produce the kcc20 redeem script for `state` by splicing the 46-byte region. Byte-identical to silverc. */\nexport function materializeKcc20Script(tpl: Kcc20Template, state: Kcc20State): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x20 || t[s + 33] !== 0x01 || t[s + 35] !== 0x08 || t[s + 44] !== 0x01) {\n throw new Error('kcc20 template has an unexpected state layout (expected push32 owner / push1 type / push8 amount / push1 isMinter)');\n }\n if (state.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n if (state.amount < 0n) throw new Error('amount must be non-negative');\n const out = t.slice();\n out[s] = 0x20;\n out.set(state.ownerIdentifier, s + 1);\n out[s + 33] = 0x01;\n out[s + 34] = state.identifierType;\n out[s + 35] = 0x08;\n out.set(int8LE(state.amount), s + 36);\n out[s + 44] = 0x01;\n out[s + 45] = state.isMinter ? 1 : 0;\n return out;\n}\n\n// --- redeem-script decode (template + state from a live UTXO's redeemScriptHex) ------------------\n\n/**\n * Recover the `{ script, stateStart }` template AND the current balance state from a live token UTXO's\n * redeem script (your indexer's `redeemScriptHex`). Scans for the 46-byte state region's push layout\n * (`0x20 <owner:32> 0x01 <type:1> 0x08 <amount:8> 0x01 <isMinter:1>` with type ≤ 0x03, isMinter ≤ 1) and\n * requires it to match at exactly ONE offset. This is the supported way to build the template for\n * `materializeKcc20Script` — splice the SAME script the chain holds; never re-compile.\n * `maxIns`/`maxOuts` are compiled constants not recoverable from the bytes — pass the token's deploy\n * params if you know them (KRON deploys use 4/4, the default) — they are informational only (the splice\n * uses just `script` + `stateStart`).\n */\nexport function decodeKcc20Redeem(redeem: Uint8Array, opts: { maxIns?: number; maxOuts?: number } = {}): { template: Kcc20Template; state: Kcc20State } {\n const hits: number[] = [];\n for (let s = 0; s + STATE_LEN <= redeem.length; s++) {\n if (redeem[s] === 0x20 && redeem[s + 33] === 0x01 && redeem[s + 34] <= 0x03 && redeem[s + 35] === 0x08 && redeem[s + 44] === 0x01 && redeem[s + 45] <= 1) hits.push(s);\n }\n if (hits.length !== 1) throw new Error(`could not locate the kcc20 state region in the redeem script (${hits.length} candidate offsets) — is this a kcc20 token UTXO?`);\n const s = hits[0];\n let amount = 0n;\n for (let i = 7; i >= 0; i--) amount = (amount << 8n) | BigInt(redeem[s + 36 + i]);\n return {\n template: { script: redeem.slice(), stateStart: s, maxIns: opts.maxIns ?? 4, maxOuts: opts.maxOuts ?? 4 },\n state: {\n ownerIdentifier: redeem.slice(s + 1, s + 33),\n identifierType: redeem[s + 34] as IdentifierType,\n amount,\n isMinter: redeem[s + 45] === 1,\n },\n };\n}\n\n// --- scriptPublicKeys + address ----------------------------------------------------------------\n\n/** Token P2SH scriptPublicKey for a redeem script. */\nexport const kcc20Spk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\n\n/** Token P2SH scriptPublicKey for a balance state (materialize → P2SH). */\nexport const kcc20SpkForState = (k: K, tpl: Kcc20Template, state: Kcc20State): Spk =>\n kcc20Spk(k, materializeKcc20Script(tpl, state));\n\n/** Token P2SH address (where this balance lives) for a balance state. */\nexport function kcc20Address(k: K, tpl: Kcc20Template, state: Kcc20State, network: string): string {\n return (k as any).addressFromScriptPublicKey(kcc20SpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\n// --- ownership-mode constructors ---------------------------------------------------------------\n\n/** A balance owned by a covenant-id `C` (mode 0x02): spendable only in a tx that also spends an input\n * carrying `C`. This is how the curve owns its minter branch and the pool owns its token UTXO. */\nexport const covenantIdOwned = (covid32: Uint8Array, amount: bigint, isMinter = false): Kcc20State => ({\n ownerIdentifier: covid32,\n identifierType: IDENTIFIER.COVENANT_ID,\n amount,\n isMinter,\n});\n\n/** A balance owned by a 32-byte x-only pubkey (mode 0x00): a user's normal holding (needs a signature). */\nexport const pubkeyOwned = (pubkey32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: pubkey32,\n identifierType: IDENTIFIER.PUBKEY,\n amount,\n isMinter: false,\n});\n\n/** A balance owned by a 32-byte P2SH script-hash (mode 0x01): needs a matching P2SH input in the tx. */\nexport const scriptHashOwned = (hash32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: hash32,\n identifierType: IDENTIFIER.SCRIPT_HASH,\n amount,\n isMinter: false,\n});\n\n/** A balance owned by a normal ADDRESS (mode 0x03, presence-based): spendable when the tx carries a\n * co-present input at the owner's P2PK address (a wallet-signed input). The token UTXO itself carries NO\n * signature, so sell/transfer work with existing wallets via a signPskt-style bridge. owner = x-only pubkey. */\nexport const addressPresenceOwned = (pubkey32: Uint8Array, amount: bigint): Kcc20State => ({\n ownerIdentifier: pubkey32,\n identifierType: IDENTIFIER.ADDRESS,\n amount,\n isMinter: false,\n});\n\n// --- transfer signature script (the column-major State[] ABI) -----------------------------------\n\n/** Push a SINGLE `State`/`TokenState` struct arg field-by-field (declared order, scalar rules) — used by\n * entrypoints whose covenant takes individual structs (e.g. curve buy/sell/graduate, pool swap). */\nexport function pushKcc20StateScalar(b: SigScriptBuilder, st: Kcc20State): void {\n if (st.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n b.data(st.ownerIdentifier).byte(st.identifierType).int(st.amount).bool(st.isMinter);\n}\n\n/** Push a `State[]` arg column-major (owners ‖ types ‖ amounts ‖ isMinters), per build_sig_script. */\nexport function pushKcc20States(b: SigScriptBuilder, states: Kcc20State[]): void {\n for (const st of states) if (st.ownerIdentifier.length !== 32) throw new Error('ownerIdentifier must be 32 bytes');\n b.column(states.map((s) => s.ownerIdentifier)); // byte[32][] column\n b.column(states.map((s) => Uint8Array.of(s.identifierType))); // byte[] column\n b.column(states.map((s) => int8LE(s.amount))); // int[] column (8-byte LE each)\n b.column(states.map((s) => Uint8Array.of(s.isMinter ? 1 : 0))); // bool[] column\n}\n\n/**\n * Build the kcc20 `transfer` signature script for a token covenant input:\n * <newStates column-major> <sigs> <witnesses> <redeem> (single entrypoint → no selector)\n * `witnesses[i]` is the tx-input index that authorizes input i (for covenant-id ownership, the input\n * carrying that covenant id). `sigs` are 65-byte Schnorr sigs (empty for covenant-id-only ownership).\n */\nexport function transferSigScript(\n k: K,\n redeem: Uint8Array,\n newStates: Kcc20State[],\n witnesses: number[],\n sigs: Uint8Array[] = [],\n): string {\n if (newStates.length < 1) throw new Error('transfer requires at least one output state');\n const b = new SigScriptBuilder(k);\n pushKcc20States(b, newStates);\n b.column(sigs); // sig[] — fixed-width concat (empty → empty push)\n b.data(Uint8Array.from(witnesses, (w) => w & 0xff)); // byte[] witnesses\n b.redeem(redeem);\n return b.drain();\n}\n\n// --- send (wallet \"Send\" — the plain user→user transfer) ----------------------------------------\n\n/**\n * Send `sendAmount` from one or more presence-owned token UTXOs (same owner) to `recipientPubkey32`, with\n * the remainder returned to the sender — the wallet \"Send\" button. A plain conserving `transfer`: inputs\n * are authorized by ONE co-present P2PK input at tx index `presenceWitnessIdx` (assemble the covenant\n * inputs first, then the sender's funding inputs: with N token inputs, `presenceWitnessIdx = N`).\n *\n * `tokenCovid` (the token's covenant id, hex — `covenantId` from the indexer's token info) is REQUIRED:\n * every covenant output must carry the KIP-20 `CovenantBinding` or the chain rejects the spend with\n * \"script ran, but verification failed\". Outputs: [recipient, change] (change omitted when exact).\n */\nexport function buildKcc20Send(\n k: K, tpl: Kcc20Template,\n senderTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n recipientPubkey32: Uint8Array, sendAmount: bigint, presenceWitnessIdx: number, tokenCovid: string,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (senderTokens.length < 1) throw new Error('send requires at least one token UTXO');\n if (!tokenCovid) throw new Error('send requires the token covenant id (indexer token info `covenantId`) for the output bindings');\n const total = senderTokens.reduce((s, t) => s + t.state.amount, 0n);\n const change = total - sendAmount;\n if (sendAmount < 1n || change < 0n) throw new Error(`send requires 1 <= sendAmount <= ${total} (the selected UTXOs' total)`);\n const dust = opts.tokenDust ?? 50_000_000n; // COVENANT_DUST — KIP-9 storage-mass floor for covenant outputs\n const owner = senderTokens[0].state.ownerIdentifier;\n const recipientOut = addressPresenceOwned(recipientPubkey32, sendAmount);\n const newStates = change >= 1n ? [recipientOut, addressPresenceOwned(owner, change)] : [recipientOut];\n const witnesses = senderTokens.map(() => presenceWitnessIdx); // every token input authorized by the one P2PK\n const inputs: CovInput[] = senderTokens.map((t) => {\n const r = materializeKcc20Script(tpl, t.state);\n return { transactionId: t.transactionId, index: t.index, value: t.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'token' };\n });\n const binding = { covid: tokenCovid, authorizingInput: 0 }; // ← the first token input carries covid A\n const outputs: CovOutput[] = newStates.map((st, i) => ({\n value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tpl, st)), role: i === 0 ? 'send' : 'change', binding,\n }));\n return { kind: 'transfer', inputs, outputs, economics: { sendAmount, change }, covids: { tokenCovid } };\n}\n","// Virtual-reserve constant-product curve builder — builds transactions against an ALREADY-DEPLOYED curve_cp\n// covenant instance (buy/sell/graduate). Curve state is {graduated, tokenCovid, tokenReserve} (realKas = the\n// curve UTXO value; tokenReserve = the committed token inventory, authoritative in state and kept in sync with\n// the C-owned inventory UTXO the curve also holds).\n//\n// buy — kasIn into the reserve, tokenOut from inventory to the buyer (presence-owned), fee split. The\n// bought tokens MERGE with any existing buyer holdings passed in `mergeTokens` into ONE output.\n// sell — the seller folds `tokenIn` from their piece(s) into inventory, refund kasOut; the unsold\n// remainder returns as ONE presence-owned change output (fractional; no pre-split needed).\n// graduate — lock the curve, seed amm_pool_cp_v3 with the post-fee reserve + leftover inventory.\n//\n// State region (verify: silverc state_layout {start:1,len:44}): off 1: 0x01 <graduated:1> 0x20 <tokenCovid:32>\n// 0x08 <tokenReserve:8 LE>. tokenReserve is the AUTHORITATIVE token inventory committed to state (this is the\n// reserve-spoof hardening: buy/sell/graduate read the reserve from state, not from an attacker-chosen input).\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`. Callers need\n// the target curve's compiled script bytes (`CpTemplate.script`) — read them from your indexer's live UTXO\n// data (e.g. the `redeemScriptHex` field), not compiled locally; this package doesn't ship a covenant\n// compiler (see README).\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20State,\n type Kcc20Template,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport { genesisCovenantId, covidToBytes } from './genesis.js';\nimport { materializePoolCpScript, type PoolCpTemplate } from './poolCpTx.js';\nimport { FEE_OUT_MIN, MAX_KAS } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\nexport const SCALE = 1_000_000n; // 1e6 sompi = 0.01 KAS (matches curve_cp.sil)\n// Fee outputs padded to FEE_OUT_MIN (cpCurve) — a sub-dust output blows KIP-9 storage mass past the 500k cap.\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\nexport const SELECTOR = { init: 0, buy: 1, sell: 2, graduate: 3, initVested: 4 } as const;\nconst ZERO32 = new Uint8Array(32);\n\n/** Fixed per-token curve parameters (baked into the redeem script by silverc). */\nexport type CpParams = {\n creatorFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK)\n platformFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK)\n vKas: bigint; // virtual KAS reserve, SCALE units\n graduationKas: bigint; // raised-KAS target (sompi)\n creatorFeeBps: bigint;\n platformFeeBps: bigint;\n graduationFeeBps: bigint;\n};\nexport type CpTemplate = { script: Uint8Array; stateStart: number; params: CpParams };\nexport type CpCurveState = { graduated: boolean; tokenCovid: Uint8Array; tokenReserve: bigint };\n/** The live curve UTXO. `realKas` (sompi) = its value = KAS raised. */\nexport type CpCurveUtxo = { transactionId: string; index: number; realKas: bigint; state: CpCurveState };\n/** The curve's C-owned token inventory UTXO (covid A). `amount` = tokens remaining. */\nexport type CpInventoryUtxo = { transactionId: string; index: number; value: bigint; amount: bigint };\n\n// --- state splice (off 1, 44 bytes: graduated + tokenCovid + tokenReserve) ---------------------\nexport function materializeCpScript(tpl: CpTemplate, state: CpCurveState): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x01 || t[s + 2] !== 0x20 || t[s + 35] !== 0x08) {\n throw new Error('curve_cp template has an unexpected state layout (expected push1 graduated / push32 tokenCovid / push8 tokenReserve)');\n }\n if (state.tokenCovid.length !== 32) throw new Error('tokenCovid must be 32 bytes');\n if (state.tokenReserve < 0n) throw new Error('tokenReserve must be non-negative');\n const out = t.slice();\n out[s] = 0x01;\n out[s + 1] = state.graduated ? 1 : 0;\n out[s + 2] = 0x20;\n out.set(state.tokenCovid, s + 3);\n out[s + 35] = 0x08;\n out.set(int8LE(state.tokenReserve), s + 36);\n return out;\n}\n\nexport const cpSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const cpSpkForState = (k: K, tpl: CpTemplate, state: CpCurveState): Spk => cpSpk(k, materializeCpScript(tpl, state));\nexport function cpAddress(k: K, tpl: CpTemplate, state: CpCurveState, network: string): string {\n return (k as any).addressFromScriptPublicKey(cpSpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\n/** Fee output scriptPublicKey: P2PK (`<32-byte pubkey> OP_CHECKSIG`). */\nexport function p2pkSpk(k: K, pubkey: Uint8Array): Spk {\n const sb = new (k as any).ScriptBuilder();\n sb.addData(pubkey).addOp(172);\n return new (k as any).ScriptPublicKey(0, sb.drain());\n}\n\n// --- curve-input signature scripts -------------------------------------------------------------\nfunction buySig(k: K, redeem: Uint8Array, kasIn: bigint, tokenOut: bigint, inventoryOut: Kcc20State, buyerOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasIn).int(tokenOut);\n pushKcc20StateScalar(b, inventoryOut);\n pushKcc20StateScalar(b, buyerOut);\n return b.selector(SELECTOR.buy).redeem(redeem).drain();\n}\n// single-token sell: pushes traderChangeOut too (even on a full sell — the covenant only validates it when a\n// 2nd covid-A output exists; otherwise it's an ignored placeholder).\nfunction sellSig(k: K, redeem: Uint8Array, tokenIn: bigint, kasOut: bigint, inventoryOut: Kcc20State, traderChangeOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(tokenIn).int(kasOut);\n pushKcc20StateScalar(b, inventoryOut);\n pushKcc20StateScalar(b, traderChangeOut);\n return b.selector(SELECTOR.sell).redeem(redeem).drain();\n}\n// graduate: the PoolState struct has five fields (kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid)\n// — push all five in declared order.\nfunction graduateSigV2(k: K, redeem: Uint8Array, pool: { kasReserve: bigint; tokenReserve: bigint; tokenCovid: Uint8Array; totalShares: bigint; lpCovid: Uint8Array }, poolTokens: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(pool.kasReserve).int(pool.tokenReserve).data(pool.tokenCovid).int(pool.totalShares).data(pool.lpCovid);\n pushKcc20StateScalar(b, poolTokens);\n return b.selector(SELECTOR.graduate).redeem(redeem).drain();\n}\n\n// --- buy (MERGE): kasIn into reserve, tokenOut from inventory; the bought tokens MERGE with any EXISTING holdings\n// the buyer passes in `mergeTokens` into ONE presence-owned output — so a buy never fragments. `presenceWitnessIdx`\n// = the tx input index of a co-present P2PK input at the buyer's address (only needed when merging).\nexport function buildCpBuy(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n utxo: CpCurveUtxo,\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n buyerPubkey: Uint8Array,\n kasIn: bigint,\n tokenOut: bigint,\n mergeTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[] = [],\n presenceWitnessIdx = 0,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('curve has graduated — buys are locked');\n if (kasIn <= 0n || kasIn % SCALE !== 0n) throw new Error('kasIn must be a positive multiple of SCALE (0.01 KAS)');\n if (tokenOut <= 0n || tokenOut >= inventory.amount) throw new Error('invalid tokenOut');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const dust = opts.tokenDust ?? 1000n;\n const curveCovidHex = hexOf(curveCovid);\n const tokenCovidHex = hexOf(utxo.state.tokenCovid);\n const newKas = utxo.realKas + kasIn;\n // Overbuy allowed: a buy may exceed graduationKas (excess seeds the LP at graduation). Only MAX_KAS caps it.\n if (newKas > MAX_KAS) throw new Error('buy exceeds the curve max raise (9,000,000 TKAS)');\n const newToken = inventory.amount - tokenOut;\n const creatorFee = (kasIn * tpl.params.creatorFeeBps) / 10000n;\n const platformFee = (kasIn * tpl.params.platformFeeBps) / 10000n;\n const mergeSum = mergeTokens.reduce((s, t) => s + t.state.amount, 0n);\n\n const inventoryOut = covenantIdOwned(curveCovid, newToken, false);\n const buyerOut = addressPresenceOwned(buyerPubkey, tokenOut + mergeSum); // bought + merged existing → ONE UTXO\n const curRedeem = materializeCpScript(tpl, utxo.state);\n const newCurveRedeem = materializeCpScript(tpl, { graduated: false, tokenCovid: utxo.state.tokenCovid, tokenReserve: newToken });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n const invOutRedeem = materializeKcc20Script(tokenTpl, inventoryOut);\n const buyerRedeem = materializeKcc20Script(tokenTpl, buyerOut);\n // covid-A inputs in tx order: inventory (witness = curve input 0), then each merged existing token (presence → P2PK).\n const witnesses = [0, ...mergeTokens.map(() => presenceWitnessIdx)];\n const newStates = [inventoryOut, buyerOut];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: buySig(k, curRedeem, kasIn, tokenOut, inventoryOut, buyerOut), redeem: curRedeem, role: 'curve' },\n // inventory (covid A, C-owned) spent via kcc20 transfer; the C-owned input is authorized by the curve (input 0)\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, newStates, witnesses), redeem: invRedeem, role: 'inventory' },\n ...mergeTokens.map((mt) => {\n const r = materializeKcc20Script(tokenTpl, mt.state);\n return { transactionId: mt.transactionId, index: mt.index, value: mt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'buyerToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: newKas, scriptPublicKey: cpSpk(k, newCurveRedeem), role: 'curve', binding: { covid: curveCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, invOutRedeem), role: 'inventory', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, buyerRedeem), role: 'recipient', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: padFee(creatorFee), scriptPublicKey: p2pkSpk(k, tpl.params.creatorFeeOwner), role: 'creatorFee' },\n { value: padFee(platformFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'platformFee' },\n ];\n return { kind: 'buy', inputs, outputs, economics: { kasIn, tokenOut, creatorFee, platformFee, newRealKas: newKas, newTokenReserve: newToken, merged: mergeSum }, covids: { tokenCovid: tokenCovidHex } };\n}\n\n// --- sell (single-token, FRACTIONAL): fold `tokenIn` from the seller's piece(s), refund kasOut, return the\n// unsold remainder as ONE presence-owned change output (LAST) — no pre-split. Inputs: [curve(0), inventory(1),\n// seller1(2)…sellerN]. `presenceWitnessIdx` = the tx index of a co-present P2PK input at the seller's address the\n// wallet signs (also the presence witness that authorizes the address-owned seller tokens). covid-A outputs:\n// [inventory(0), OPTIONAL change(1)]. kcc20 conservation forces change == Σ(seller inputs) − tokenIn.\nexport function buildCpSell(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n utxo: CpCurveUtxo,\n sellerTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n traderPubkey: Uint8Array,\n tokenIn: bigint,\n kasOut: bigint,\n presenceWitnessIdx: number,\n opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('curve has graduated — sells are locked');\n if (sellerTokens.length < 1) throw new Error('need at least one seller token');\n if (tokenIn <= 0n) throw new Error('tokenIn must be positive');\n if (kasOut <= 0n || kasOut % SCALE !== 0n || kasOut > utxo.realKas) throw new Error('invalid kasOut');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const dust = opts.tokenDust ?? 1000n;\n const curveCovidHex = hexOf(curveCovid);\n const tokenCovidHex = hexOf(utxo.state.tokenCovid);\n const sellerIn = sellerTokens.reduce((s, t) => s + t.state.amount, 0n);\n const change = sellerIn - tokenIn; // the unsold remainder (kcc20 conservation pins it on-chain)\n if (change < 0n) throw new Error('seller inputs are less than the sell amount');\n const hasChange = change > 0n;\n const newToken = inventory.amount + tokenIn;\n const creatorFee = (kasOut * tpl.params.creatorFeeBps) / 10000n;\n const platformFee = (kasOut * tpl.params.platformFeeBps) / 10000n;\n\n const inventoryOut = covenantIdOwned(curveCovid, newToken, false);\n const traderChangeOut = addressPresenceOwned(traderPubkey, hasChange ? change : 1n); // dummy(1) on a full sell — covenant ignores it\n const curRedeem = materializeCpScript(tpl, utxo.state);\n const newCurveRedeem = materializeCpScript(tpl, { graduated: false, tokenCovid: utxo.state.tokenCovid, tokenReserve: newToken });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n const invOutRedeem = materializeKcc20Script(tokenTpl, inventoryOut);\n // covid-A inputs in tx order: inventory (witness = curve input 0), then each seller (presence → its P2PK witness).\n const witnesses = [0, ...sellerTokens.map(() => presenceWitnessIdx)];\n const newStates = hasChange ? [inventoryOut, traderChangeOut] : [inventoryOut];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: sellSig(k, curRedeem, tokenIn, kasOut, inventoryOut, traderChangeOut), redeem: curRedeem, role: 'curve' },\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, newStates, witnesses), redeem: invRedeem, role: 'inventory' },\n ...sellerTokens.map((st) => {\n const r = materializeKcc20Script(tokenTpl, st.state);\n return { transactionId: st.transactionId, index: st.index, value: st.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'sellerToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: utxo.realKas - kasOut, scriptPublicKey: cpSpk(k, newCurveRedeem), role: 'curve', binding: { covid: curveCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, invOutRedeem), role: 'inventory', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: padFee(creatorFee), scriptPublicKey: p2pkSpk(k, tpl.params.creatorFeeOwner), role: 'creatorFee' },\n { value: padFee(platformFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'platformFee' },\n ];\n if (hasChange) outputs.push({ value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderChangeOut)), role: 'seller', binding: { covid: tokenCovidHex, authorizingInput: 1 } });\n return { kind: 'sell', inputs, outputs, economics: { tokenIn, kasOut, change, creatorFee, platformFee, newRealKas: utxo.realKas - kasOut, newTokenReserve: newToken }, covids: { tokenCovid: tokenCovidHex } };\n}\n\n// --- graduate: lock curve, seed the CP pool (amm_pool_cp_v3) with the 5-field PoolState (locked floor, L unbound) ---\n// The curve must have been compiled with the CP pool template + `poolLockedShares` (curve_cp.sil graduate\n// requires pool.totalShares == poolLockedShares and pool.lpCovid == ZERO_COVID). The pool's LP-share token L\n// is NOT minted here — it's bound post-graduation by the pool's bindLp (buildBindLp), which needs the pool\n// live first.\nexport function buildCpGraduate(\n k: K,\n tpl: CpTemplate,\n tokenTpl: Kcc20Template,\n poolTemplate: PoolCpTemplate,\n utxo: CpCurveUtxo,\n inventory: CpInventoryUtxo,\n curveCovid: Uint8Array,\n poolLockedShares: bigint,\n opts: { lockedCurveValue?: bigint; tokenDust?: bigint } = {},\n): CovenantSpend {\n if (utxo.state.graduated) throw new Error('already graduated');\n if (utxo.realKas < tpl.params.graduationKas) throw new Error('reserve has not reached the graduation target');\n if (poolLockedShares < 1n) throw new Error('poolLockedShares must be >= 1');\n if (inventory.amount !== utxo.state.tokenReserve) throw new Error('inventory.amount must equal the curve\\'s committed tokenReserve');\n const lockedValue = opts.lockedCurveValue ?? 1000n;\n const dust = opts.tokenDust ?? 1000n;\n // poolKas ≈ (1 − gradFeeBps) of the reserve, floored to a whole SCALE step; platform takes the remainder.\n const targetPoolKas = (utxo.realKas * (10000n - tpl.params.graduationFeeBps)) / 10000n;\n const poolKasUnits = targetPoolKas / SCALE;\n const poolKas = poolKasUnits * SCALE;\n const gradFee = utxo.realKas - poolKas;\n const leftover = inventory.amount;\n\n const A = utxo.state.tokenCovid;\n // pool genesis state: locked floor seeded (totalShares == poolLockedShares), L unbound (lpCovid == ZERO).\n const poolState = { kasReserve: poolKasUnits, tokenReserve: leftover, tokenCovid: A, totalShares: poolLockedShares, lpCovid: ZERO32 };\n const poolRedeem = materializePoolCpScript(poolTemplate, poolState);\n const poolSpkV = (k as any).payToScriptHashScript(poolRedeem);\n const poolCovidHex = genesisCovenantId(k, { transactionId: utxo.transactionId, index: utxo.index }, [\n { index: 1, value: poolKas, scriptPublicKey: poolSpkV },\n ]);\n const poolCovid = covidToBytes(poolCovidHex);\n const poolTokens = covenantIdOwned(poolCovid, leftover, false);\n const poolTokenRedeem = materializeKcc20Script(tokenTpl, poolTokens);\n\n const curRedeem = materializeCpScript(tpl, utxo.state);\n // graduated husk carries the reserve unchanged (== inventory.amount == the committed reserve at lock time).\n const lockedRedeem = materializeCpScript(tpl, { graduated: true, tokenCovid: A, tokenReserve: inventory.amount });\n const invRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(curveCovid, inventory.amount, false));\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: utxo.realKas, scriptPublicKey: cpSpk(k, curRedeem), signatureScript: graduateSigV2(k, curRedeem, poolState, poolTokens), redeem: curRedeem, role: 'curve' },\n { transactionId: inventory.transactionId, index: inventory.index, value: inventory.value, scriptPublicKey: kcc20Spk(k, invRedeem), signatureScript: transferSigScript(k, invRedeem, [poolTokens], [0]), redeem: invRedeem, role: 'inventory' },\n ];\n const curveCovidHex = hexOf(curveCovid);\n const tokenCovidHex = hexOf(A);\n const outputs: CovOutput[] = [\n { value: lockedValue, scriptPublicKey: cpSpk(k, lockedRedeem), role: 'curve', binding: { covid: curveCovidHex, authorizingInput: 0 } },\n { value: poolKas, scriptPublicKey: poolSpkV, role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, poolTokenRedeem), role: 'poolToken', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: padFee(gradFee), scriptPublicKey: p2pkSpk(k, tpl.params.platformFeeOwner), role: 'gradFee' },\n ];\n return { kind: 'graduate', inputs, outputs, economics: { poolKas, gradFee, leftover, poolLockedShares }, covids: { tokenCovid: hexOf(A), poolCovid: poolCovidHex } };\n}\n\n/**\n * Split a presence-owned token UTXO into [sellAmount, change], both still presence-owned by the same holder —\n * a plain conserving kcc20 transfer authorized by a co-present P2PK input at `presenceWitnessIdx`. Lets a\n * holder sell an ARBITRARY amount on covenants that require full-UTXO sells (curve/pool): split, then sell the\n * `sellAmount` piece. No curve/pool involved — just the token covenant.\n * Pass `opts.tokenCovid` (the token's covenant id, hex — `covenantId` from the indexer) so both outputs carry\n * the KIP-20 covenant binding the chain requires; without it the assembled tx fails on-chain.\n */\nexport function buildSplitToken(\n k: K, tokenTpl: Kcc20Template,\n sellerToken: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n sellAmount: bigint, presenceWitnessIdx: number, opts: { tokenDust?: bigint; tokenCovid?: string } = {},\n): CovenantSpend {\n const change = sellerToken.state.amount - sellAmount;\n if (sellAmount <= 0n || change <= 0n) throw new Error('split requires 0 < sellAmount < the UTXO amount');\n const dust = opts.tokenDust ?? 1000n;\n const owner = sellerToken.state.ownerIdentifier;\n const out1 = addressPresenceOwned(owner, sellAmount); // the piece to sell (output 0)\n const out2 = addressPresenceOwned(owner, change); // the change (output 1)\n const redeem = materializeKcc20Script(tokenTpl, sellerToken.state);\n const binding = opts.tokenCovid ? { covid: opts.tokenCovid, authorizingInput: 0 } : undefined; // ← the seller-token input\n const inputs: CovInput[] = [\n { transactionId: sellerToken.transactionId, index: sellerToken.index, value: sellerToken.value, scriptPublicKey: kcc20Spk(k, redeem), signatureScript: transferSigScript(k, redeem, [out1, out2], [presenceWitnessIdx]), redeem, role: 'sellerToken' },\n ];\n const outputs: CovOutput[] = [\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, out1)), role: 'split', binding },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, out2)), role: 'change', binding },\n ];\n return { kind: 'sell', inputs, outputs, economics: { sellAmount, change }, covids: opts.tokenCovid ? { tokenCovid: opts.tokenCovid } : {} };\n}\n\n/**\n * Consolidate several presence-owned token UTXOs (same owner) into ONE — a conserving kcc20 transfer (N covid-A\n * inputs → 1 output) authorized by a single co-present P2PK input at `presenceWitnessIdx`. Lets a holder merge\n * many small buys into one piece so a later sell needs just one (or two) inputs. No curve/pool involved.\n * Pass `opts.tokenCovid` (the token's covenant id, hex) so the merged output carries the KIP-20 covenant\n * binding the chain requires; without it the assembled tx fails on-chain.\n */\nexport function buildConsolidate(\n k: K, tokenTpl: Kcc20Template,\n tokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n presenceWitnessIdx: number, opts: { tokenDust?: bigint; tokenCovid?: string } = {},\n): CovenantSpend {\n if (tokens.length < 2) throw new Error('consolidate needs at least 2 UTXOs');\n const dust = opts.tokenDust ?? 1000n;\n const owner = tokens[0].state.ownerIdentifier;\n const total = tokens.reduce((s, t) => s + t.state.amount, 0n);\n const merged = addressPresenceOwned(owner, total);\n const newStates = [merged];\n const witnesses = tokens.map(() => presenceWitnessIdx); // every covid-A input authorized by the one P2PK\n const inputs: CovInput[] = tokens.map((t) => {\n const r = materializeKcc20Script(tokenTpl, t.state);\n return { transactionId: t.transactionId, index: t.index, value: t.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'token' };\n });\n const binding = opts.tokenCovid ? { covid: opts.tokenCovid, authorizingInput: 0 } : undefined; // ← the first token input\n const outputs: CovOutput[] = [\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, merged)), role: 'merged', binding },\n ];\n return { kind: 'sell', inputs, outputs, economics: { total }, covids: opts.tokenCovid ? { tokenCovid: opts.tokenCovid } : {} };\n}\n\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n","// amm_pool_cp transaction builder — the graduated DEX pool with TWO-TIER liquidity. SHARED core: pool state\n// layout, P2SH/address derivation, CP quotes, and the LP entrypoints (bindLp / addLiquidity / removeLiquidity),\n// which are byte-identical across the pool covenant versions. The LIVE deployed covenant is amm_pool_cp_v3.sil\n// (single-token swaps); its swap builders live in poolCpV3Tx.ts and reuse everything here.\n//\n// MODEL (see docs/lp-provision-design.md + amm_pool_cp_v3.sil):\n// • Graduation seeds a PERMANENTLY-LOCKED floor (`lockedShares`); on top, anyone can add/remove VOLUNTARY\n// liquidity and earn swap fees. LP shares follow KRON's INVENTORY model (a pre-minted kcc20 token `L`,\n// pool holds the unissued shares; add/remove MOVE shares, never mint/burn).\n// • 5-field pool state {kasReserve(SCALE units), tokenReserve, tokenCovid, totalShares, lpCovid}.\n// • Post-grad fee (option ii): creator base + the floor's share of the LP fee paid OUT to the creator\n// (creatorFloorRent = lpFee·lockedShares/totalShares); the voluntary share stays in-pool (k grows).\n//\n// SECURITY: the pool owns TWO covenant tokens (A reserve + L inventory), both covenant-id-owned. Every\n// entrypoint fully constrains BOTH groups — swaps forbid any L movement; add/remove validate the exact moves.\n//\n// Reuses the kcc20 template/helpers (token A AND the LP-share token L share the SAME kcc20 contract — only\n// the covid differs). No top-level SDK import — caller passes the loaded WASM `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20State,\n type Kcc20Template,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport { genesisCovenantId, covidToBytes } from './genesis.js';\nimport { FEE_OUT_MIN, SCALE } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n/** pool entrypoint selectors (declaration order in amm_pool_cp_v3.sil). */\nexport const POOL_CP_SELECTOR = { swapKasForToken: 0, swapTokenForKas: 1, addLiquidity: 2, removeLiquidity: 3, bindLp: 4 } as const;\n/** the LP-share token's FIXED total supply S_MAX (== MAX_SHARES in amm_pool_cp_v3.sil). */\nexport const MAX_SHARES = 10_000_000n;\n/** the all-zero covenant id — the bindLp floor owner (unspendable) and the unbound `lpCovid` placeholder. */\nconst ZERO32 = new Uint8Array(32);\n\nconst padFee = (f: bigint) => (f > FEE_OUT_MIN ? f : FEE_OUT_MIN);\nconst ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n\n// --- pool state (5 fields) + redeem-script splice -------------------------------------------\n// silverc state_layout {start, len:93}:\n// off 0: 0x08 <kasReserve:8 LE> off 9: 0x08 <tokenReserve:8 LE> off 18: 0x20 <tokenCovid:32>\n// off 51: 0x08 <totalShares:8 LE> off 60: 0x20 <lpCovid:32>\n\n/** Compiled pool template (silverc output; one template per (lockedShares,bps...) — only state varies). */\nexport type PoolCpTemplate = { script: Uint8Array; stateStart: number };\n\n/** Pool state: KAS reserve (SCALE units; pool UTXO value == kasReserve·SCALE), token reserve, the token\n * covid A, issued LP shares, and the LP-share token covid L (ZERO until bindLp). */\nexport type PoolCpState = {\n kasReserve: bigint;\n tokenReserve: bigint;\n tokenCovid: Uint8Array;\n totalShares: bigint;\n lpCovid: Uint8Array;\n};\n\n/** Produce the pool redeem script for `state` by splicing the 93-byte region. Byte-identical to silverc. */\nexport function materializePoolCpScript(tpl: PoolCpTemplate, state: PoolCpState): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x08 || t[s + 9] !== 0x08 || t[s + 18] !== 0x20 || t[s + 51] !== 0x08 || t[s + 60] !== 0x20) {\n throw new Error('pool template has an unexpected state layout (expected kasReserve/tokenReserve/tokenCovid/totalShares/lpCovid)');\n }\n if (state.kasReserve < 0n || state.tokenReserve < 0n || state.totalShares < 0n) throw new Error('reserves/shares must be non-negative');\n if (state.tokenCovid.length !== 32) throw new Error('tokenCovid must be 32 bytes');\n if (state.lpCovid.length !== 32) throw new Error('lpCovid must be 32 bytes');\n const out = t.slice();\n out[s] = 0x08;\n out.set(int8LE(state.kasReserve), s + 1);\n out[s + 9] = 0x08;\n out.set(int8LE(state.tokenReserve), s + 10);\n out[s + 18] = 0x20;\n out.set(state.tokenCovid, s + 19);\n out[s + 51] = 0x08;\n out.set(int8LE(state.totalShares), s + 52);\n out[s + 60] = 0x20;\n out.set(state.lpCovid, s + 61);\n return out;\n}\n\nexport const poolCpSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const poolCpSpkForState = (k: K, tpl: PoolCpTemplate, state: PoolCpState): Spk => poolCpSpk(k, materializePoolCpScript(tpl, state));\nexport function poolCpAddress(k: K, tpl: PoolCpTemplate, state: PoolCpState, network: string): string {\n return (k as any).addressFromScriptPublicKey(poolCpSpkForState(k, tpl, state), network)?.toString() ?? '';\n}\n\nconst p2pkSpk = (k: any, pubkey: Uint8Array) => { const sb = new k.ScriptBuilder(); sb.addData(pubkey).addOp(172); return new k.ScriptPublicKey(0, sb.drain()); };\n\n/** Fixed per-pool fee schedule (baked into the redeem script by silverc; the builder needs them for quotes). */\nexport type PoolCpParams = {\n creatorFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK): creator base fee + the floor's LP-fee share\n platformFeeOwner: Uint8Array; // 32-byte x-only pubkey (P2PK): platform fee\n creatorFeeBps: bigint; // e.g. 10 = 0.10%\n platformFeeBps: bigint; // e.g. 5 = 0.05%\n lpFeeBps: bigint; // e.g. 20 = 0.20%\n lockedShares: bigint; // the permanently-locked floor shares (baked; == graduation totalShares)\n};\n\n/** The live pool UTXO (value = kasReserve·SCALE) + its P-owned token-A reserve UTXO. */\nexport type PoolCpUtxo = {\n transactionId: string;\n index: number;\n state: PoolCpState;\n /** the pool's token-A reserve UTXO (kcc20 owned by the pool covid P, amount = tokenReserve). */\n tokenUtxo: { transactionId: string; index: number; value: bigint };\n};\n\n/** The pool's P-owned LP-share (L) inventory UTXO (amount = the unissued shares the pool holds). */\nexport type PoolLpInventoryUtxo = { transactionId: string; index: number; value: bigint; amount: bigint };\n\n// =================================================================================================\n// swaps (with the option-ii floor-rent fee + voluntary-yield k-growth)\n// =================================================================================================\n\nexport type PoolCpBuyQuote = {\n kasInUnits: bigint; kasIn: bigint; tokenOut: bigint;\n creatorFee: bigint; creatorFloorRent: bigint; platformFee: bigint; lpFee: bigint;\n creatorOut: bigint; platformOut: bigint; total: bigint; newKas: bigint; newToken: bigint;\n};\nexport type PoolCpSellQuote = {\n tokenIn: bigint; kasOutUnits: bigint; kasOut: bigint;\n creatorFee: bigint; creatorFloorRent: bigint; platformFee: bigint; lpFee: bigint;\n creatorOut: bigint; platformOut: bigint; net: bigint; newKas: bigint; newToken: bigint;\n};\n\n/** The voluntary share of the LP fee, in bps, that must stay in the pool (k-growth) — matches the covenant. */\nfunction lpRetainBps(state: PoolCpState, p: PoolCpParams): bigint {\n return (p.lpFeeBps * (state.totalShares - p.lockedShares)) / state.totalShares;\n}\n\n/** Buy from the pool: spend `kasInSompi` (floored to a SCALE step) → tokenOut, retaining the voluntary LP fee in-pool. */\nexport function quotePoolCpBuy(state: PoolCpState, p: PoolCpParams, kasInSompi: bigint): PoolCpBuyQuote | null {\n const kasInUnits = kasInSompi / SCALE; const kasIn = kasInUnits * SCALE;\n if (kasInUnits <= 0n) return null;\n const newKas = state.kasReserve + kasInUnits;\n const oldK = state.kasReserve * state.tokenReserve;\n // Retain the voluntary share of THIS trade's LP fee in-pool — trade-proportional, mirroring the covenant EXACTLY:\n // (newKas − retainKas)·newToken ≥ oldK, so the most tokenOut comes from newToken = ceil(oldK / (newKas − retainKas)).\n const retainKas = (kasInUnits * lpRetainBps(state, p)) / 10000n;\n const effKas = newKas - retainKas;\n if (effKas <= 0n) return null;\n const newToken = ceilDiv(oldK, effKas);\n const tokenOut = state.tokenReserve - newToken;\n if (tokenOut <= 0n) return null;\n const creatorFee = (kasIn * p.creatorFeeBps) / 10000n;\n const platformFee = (kasIn * p.platformFeeBps) / 10000n;\n const lpFee = (kasIn * p.lpFeeBps) / 10000n;\n const creatorFloorRent = (lpFee * p.lockedShares) / state.totalShares;\n const creatorOut = padFee(creatorFee + creatorFloorRent);\n const platformOut = padFee(platformFee);\n return { kasInUnits, kasIn, tokenOut, creatorFee, creatorFloorRent, platformFee, lpFee, creatorOut, platformOut, total: kasIn + creatorOut + platformOut, newKas, newToken };\n}\n\n/** Sell to the pool: fold `tokenIn` tokens in → kasOut sompi (a SCALE step), retaining the voluntary LP fee in-pool. */\nexport function quotePoolCpSell(state: PoolCpState, p: PoolCpParams, tokenIn: bigint): PoolCpSellQuote | null {\n if (tokenIn <= 0n) return null;\n const newToken = state.tokenReserve + tokenIn;\n const oldK = state.kasReserve * state.tokenReserve;\n const r = lpRetainBps(state, p);\n // The covenant requires (kasReserve − kasOut − floor(kasOut·r/1e4))·newToken ≥ oldK. Pick the LARGEST kasOut that\n // clears it: kasOut + floor(kasOut·r/1e4) ≤ kasReserve − ceil(oldK/newToken). Closed-form start, then ±1-adjust for\n // the floor() so we land on EXACTLY the covenant's max (never over-ask the VM rejects, never under-pay the trader).\n const effMin = ceilDiv(oldK, newToken);\n const budget = state.kasReserve - effMin;\n if (budget <= 0n) return null;\n const g = (x: bigint) => x + (x * r) / 10000n;\n let kasOutUnits = (budget * 10000n) / (10000n + r);\n while (kasOutUnits > 0n && g(kasOutUnits) > budget) kasOutUnits -= 1n;\n while (g(kasOutUnits + 1n) <= budget) kasOutUnits += 1n;\n const newKas = state.kasReserve - kasOutUnits;\n if (kasOutUnits <= 0n || newKas < 1n) return null;\n const kasOut = kasOutUnits * SCALE;\n const creatorFee = (kasOut * p.creatorFeeBps) / 10000n;\n const platformFee = (kasOut * p.platformFeeBps) / 10000n;\n const lpFee = (kasOut * p.lpFeeBps) / 10000n;\n const creatorFloorRent = (lpFee * p.lockedShares) / state.totalShares;\n const creatorOut = padFee(creatorFee + creatorFloorRent);\n const platformOut = padFee(platformFee);\n return { tokenIn, kasOutUnits, kasOut, creatorFee, creatorFloorRent, platformFee, lpFee, creatorOut, platformOut, net: kasOut - creatorOut - platformOut, newKas, newToken };\n}\n\n// =================================================================================================\n// addLiquidity / removeLiquidity (inventory moves of L; two-sided A/KAS at the current ratio)\n// =================================================================================================\n\nexport type AddLiquidityQuote = { dKas: bigint; dToken: bigint; dShares: bigint; newKas: bigint; newToken: bigint; newShares: bigint };\nexport type RemoveLiquidityQuote = { dShares: bigint; dKas: bigint; dToken: bigint; newKas: bigint; newToken: bigint; newShares: bigint };\n\n/** The smallest deposit (in SCALE units) that mints ≥ 1 LP share at the current ratio. The covenant floors\n * dShares = floor(totalShares·dKas/kasReserve), so dShares ≥ 1 ⟺ dKas ≥ ceil(kasReserve/totalShares). ANY dKas\n * at/above this deposits — the old exact-integer lcm \"step\" (which could force a near-whole-pool minimum when the\n * reserves were coprime to totalShares) is gone now that addLiquidity is floored like removeLiquidity. */\nexport function addMinDKas(state: PoolCpState): bigint {\n return (state.kasReserve + state.totalShares - 1n) / state.totalShares; // ceil(kasReserve/totalShares)\n}\n\n/** Clamp a desired `dKas` to a valid deposit: unchanged if ≥ the minimum (see addMinDKas), else 0 (too small to\n * mint an integer share). No down-stepping — every value at/above the min is valid now that the covenant floors. */\nexport function snapAddDKas(state: PoolCpState, desiredDKas: bigint): bigint {\n const min = addMinDKas(state);\n if (min <= 0n || desiredDKas < min) return 0n;\n return desiredDKas;\n}\n\n/** Size a balanced deposit from `dKas` (SCALE units), FLOORED to match the covenant: dShares =\n * floor(totalShares·dKas/kasReserve) (the depositor never gets more than their KAS-contribution fraction, so\n * existing LPs aren't diluted), dToken = ceil(tokenReserve·dShares/totalShares) (they supply ≥ the proportional\n * token). Any dKas ≥ addMinDKas works; throws only if dKas rounds to 0 shares. */\nexport function quoteAddLiquidity(state: PoolCpState, dKas: bigint): AddLiquidityQuote {\n if (dKas <= 0n) throw new Error('dKas must be positive');\n const dShares = (state.totalShares * dKas) / state.kasReserve; // floor\n if (dShares <= 0n) throw new Error('dKas too small to mint an integer LP share (snap with snapAddDKas / addMinDKas first)');\n const dToken = (state.tokenReserve * dShares + state.totalShares - 1n) / state.totalShares; // ceil(tokenReserve·dShares/totalShares)\n return { dKas, dToken, dShares, newKas: state.kasReserve + dKas, newToken: state.tokenReserve + dToken, newShares: state.totalShares + dShares };\n}\n\n/** The smallest withdrawable dShares — the floored covenant only needs the payout to round to ≥ 1 on BOTH sides\n * (dKas ≥ 1 ⟺ dShares ≥ ⌈totalShares/kasReserve⌉; dToken ≥ 1 likewise). No exact-integer \"step\" exists anymore,\n * so any dShares at/above this withdraws (the old lcm-step that could strand a voluntary LP is gone). */\nexport function removeMinDShares(state: PoolCpState): bigint {\n const ceilDiv = (a: bigint, b: bigint) => (a + b - 1n) / b;\n const minKas = ceilDiv(state.totalShares, state.kasReserve);\n const minTok = ceilDiv(state.totalShares, state.tokenReserve);\n return minKas > minTok ? minKas : minTok;\n}\n\n/** Clamp a desired `dShares` to a withdrawable amount: returns it unchanged if ≥ the minimum (see removeMinDShares),\n * else 0 (too small to round to ≥ 1 of either side). No down-stepping — every value at/above the min is valid. */\nexport function snapRemoveDShares(state: PoolCpState, desiredDShares: bigint): bigint {\n if (desiredDShares <= 0n || desiredDShares < removeMinDShares(state)) return 0n;\n return desiredDShares;\n}\n\n/** Compute a FLOORED-proportional withdrawal for `dShares` (matches the covenant): dKas/dToken are floored, so\n * the sub-unit remainder stays in the pool. Throws only if dShares is non-positive, would dip below the locked\n * floor (totalShares − dShares < lockedShares), or is so small the floored payout rounds to < 1 of either side. */\nexport function quoteRemoveLiquidity(state: PoolCpState, p: Pick<PoolCpParams, 'lockedShares'>, dShares: bigint): RemoveLiquidityQuote {\n if (dShares <= 0n) throw new Error('dShares must be positive');\n if (state.totalShares - dShares < p.lockedShares) throw new Error('removal would dip below the permanently-locked floor');\n const dKas = (state.kasReserve * dShares) / state.totalShares; // bigint division floors (positives)\n const dToken = (state.tokenReserve * dShares) / state.totalShares;\n if (dKas < 1n || dToken < 1n) throw new Error('withdrawal too small — rounds to less than 1 KAS-unit or 1 token');\n return { dShares, dKas, dToken, newKas: state.kasReserve - dKas, newToken: state.tokenReserve - dToken, newShares: state.totalShares - dShares };\n}\n\nfunction addLiquiditySig(k: K, redeem: Uint8Array, dKas: bigint, dToken: bigint, dShares: bigint, poolTokenOut: Kcc20State, poolLpOut: Kcc20State, lpSharesOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(dKas).int(dToken).int(dShares);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, poolLpOut); pushKcc20StateScalar(b, lpSharesOut);\n return b.selector(POOL_CP_SELECTOR.addLiquidity).redeem(redeem).drain();\n}\nfunction removeLiquiditySig(k: K, redeem: Uint8Array, dShares: bigint, dKas: bigint, dToken: bigint, poolTokenOut: Kcc20State, lpTokenOut: Kcc20State, poolLpOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(dShares).int(dKas).int(dToken);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, lpTokenOut); pushKcc20StateScalar(b, poolLpOut);\n return b.selector(POOL_CP_SELECTOR.removeLiquidity).redeem(redeem).drain();\n}\n\n/**\n * addLiquidity — deposit dKas (SCALE units) + dToken at the current ratio, receive dShares of L moved out of\n * the pool's inventory. The LP must supply a token-A UTXO of EXACTLY dToken (full-UTXO deposit — the covenant\n * allows only ONE covid-A output, the grown pool reserve) and a co-present P2PK input at `presenceWitnessIdx`.\n *\n * Inputs: [0]=pool [1]=LP token-A deposit(presence, =dToken) [2]=pool token-A reserve(P) [3]=pool L inventory(P)\n * Outputs: [0]=pool(grown) [1]=pool token-A reserve(P, newToken) [2]=reduced pool L inventory(P) [3]=LP dShares(presence)\n */\nexport function buildAddLiquidity(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, lpInventory: PoolLpInventoryUtxo, poolCovid: Uint8Array,\n lpDepositToken: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n lpPubkey: Uint8Array, q: AddLiquidityQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (lpDepositToken.state.amount !== q.dToken) throw new Error('LP deposit token UTXO must equal dToken exactly (split first)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, lpCovid } = utxo.state;\n const poolCovidHex = hexOf(poolCovid);\n const tokenCovidHex = hexOf(tokenCovid);\n const lpCovidHex = hexOf(lpCovid);\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false); // grown token-A reserve (P)\n const poolLpOut = covenantIdOwned(poolCovid, lpInventory.amount - q.dShares, false); // reduced L inventory (P)\n const lpSharesOut = addressPresenceOwned(lpPubkey, q.dShares); // the LP's new shares (presence)\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const newRedeem = materializePoolCpScript(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares: q.newShares, lpCovid });\n const lpDepositRedeem = materializeKcc20Script(tokenTpl, lpDepositToken.state);\n const poolAResRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const poolLpInvRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, lpInventory.amount, false));\n\n // token-A group: inputs in tx order [LP deposit (input 1, presence), pool reserve (input 2, P)] → 1 output.\n const aStates = [poolTokenOut];\n const aWitnesses = [presenceWitnessIdx, 0];\n // L group: input [pool inventory (input 3, P)] → 2 outputs [reduced inventory, LP shares].\n const lStates = [poolLpOut, lpSharesOut];\n const lWitnesses = [0];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: addLiquiditySig(k, curRedeem, q.dKas, q.dToken, q.dShares, poolTokenOut, poolLpOut, lpSharesOut), redeem: curRedeem, role: 'pool' },\n { transactionId: lpDepositToken.transactionId, index: lpDepositToken.index, value: lpDepositToken.value, scriptPublicKey: kcc20Spk(k, lpDepositRedeem), signatureScript: transferSigScript(k, lpDepositRedeem, aStates, aWitnesses), redeem: lpDepositRedeem, role: 'lpDeposit' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolAResRedeem), signatureScript: transferSigScript(k, poolAResRedeem, aStates, aWitnesses), redeem: poolAResRedeem, role: 'poolToken' },\n { transactionId: lpInventory.transactionId, index: lpInventory.index, value: lpInventory.value, scriptPublicKey: kcc20Spk(k, poolLpInvRedeem), signatureScript: transferSigScript(k, poolLpInvRedeem, lStates, lWitnesses), redeem: poolLpInvRedeem, role: 'poolLpInventory' },\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpSpk(k, newRedeem), role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken', binding: { covid: tokenCovidHex, authorizingInput: 2 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolLpOut)), role: 'poolLpInventory', binding: { covid: lpCovidHex, authorizingInput: 3 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, lpSharesOut)), role: 'lpShares', binding: { covid: lpCovidHex, authorizingInput: 3 } },\n ];\n return { kind: 'addLiquidity', inputs, outputs, economics: { dKas: q.dKas, dToken: q.dToken, dShares: q.dShares, newShares: q.newShares }, covids: { poolCovid: poolCovidHex, tokenCovid: tokenCovidHex } };\n}\n\n/**\n * removeLiquidity — return dShares of L to the pool inventory, withdraw a strictly-proportional dKas + dToken.\n * The withdrawn KAS is the tx change (the pool value drops by dKas·SCALE). The LP must supply an L UTXO of\n * EXACTLY dShares (full-UTXO) and a co-present P2PK input at `presenceWitnessIdx`. The covenant floor guard\n * (totalShares − dShares ≥ lockedShares) makes the graduation floor un-withdrawable.\n *\n * Inputs: [0]=pool [1]=pool token-A reserve(P) [2]=LP L shares(presence, =dShares)\n * Outputs: [0]=pool(shrunk) [1]=pool token-A reserve(P, newToken) [2]=LP withdrawn token(presence, dToken)\n * [3]=dShares returned to the pool L inventory(P)\n */\nexport function buildRemoveLiquidity(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, lpShares: { transactionId: string; index: number; value: bigint; state: Kcc20State },\n poolCovid: Uint8Array, lpPubkey: Uint8Array, q: RemoveLiquidityQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (lpShares.state.amount !== q.dShares) throw new Error('LP shares UTXO must equal dShares exactly (split first)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, lpCovid } = utxo.state;\n const poolCovidHex = hexOf(poolCovid);\n const tokenCovidHex = hexOf(tokenCovid);\n const lpCovidHex = hexOf(lpCovid);\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false); // shrunk token-A reserve (P)\n const lpTokenOut = addressPresenceOwned(lpPubkey, q.dToken); // the LP's withdrawn token (presence)\n const poolLpOut = covenantIdOwned(poolCovid, q.dShares, false); // dShares returned to inventory (P)\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const newRedeem = materializePoolCpScript(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares: q.newShares, lpCovid });\n const poolAResRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const lpSharesRedeem = materializeKcc20Script(tokenTpl, lpShares.state);\n\n // token-A group: input [pool reserve (input 1, P)] → 2 outputs [shrunk reserve, LP withdrawn token].\n const aStates = [poolTokenOut, lpTokenOut];\n const aWitnesses = [0];\n // L group: input [LP shares (input 2, presence)] → 1 output [returned to pool inventory].\n const lStates = [poolLpOut];\n const lWitnesses = [presenceWitnessIdx];\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: removeLiquiditySig(k, curRedeem, q.dShares, q.dKas, q.dToken, poolTokenOut, lpTokenOut, poolLpOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolAResRedeem), signatureScript: transferSigScript(k, poolAResRedeem, aStates, aWitnesses), redeem: poolAResRedeem, role: 'poolToken' },\n { transactionId: lpShares.transactionId, index: lpShares.index, value: lpShares.value, scriptPublicKey: kcc20Spk(k, lpSharesRedeem), signatureScript: transferSigScript(k, lpSharesRedeem, lStates, lWitnesses), redeem: lpSharesRedeem, role: 'lpShares' },\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpSpk(k, newRedeem), role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, lpTokenOut)), role: 'lpToken', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolLpOut)), role: 'poolLpInventory', binding: { covid: lpCovidHex, authorizingInput: 2 } },\n ];\n return { kind: 'removeLiquidity', inputs, outputs, economics: { dShares: q.dShares, dKas: q.dKas, dToken: q.dToken, newShares: q.newShares }, covids: { poolCovid: poolCovidHex, tokenCovid: tokenCovidHex } };\n}\n\n// =================================================================================================\n// bindLp — one-time, permissionless genesis-mint of the LP-share token L + bind lpCovid into the pool\n// =================================================================================================\n\n/** The result of buildBindLp: the spend + the freshly-derived L covid + the inventory the pool now holds. */\nexport type BindLpResult = CovenantSpend & { lpCovidHex: string; lpInventoryAmount: bigint };\n\n/**\n * bindLp — runs once on a freshly-graduated pool (lpCovid == ZERO, totalShares == lockedShares). Genesis-mints\n * the FIXED supply (MAX_SHARES) of the LP-share token L: the floor (lockedShares) is burned to an unspendable\n * ZERO-covid owner, the rest (MAX_SHARES − lockedShares) seeds the pool's inventory (owned by the pool covid\n * P). L carries NO minter branch → its supply is fixed forever (mint-renounced, like token A's init). The pool\n * continuation carries lpCovid = the new L genesis covid; value + reserves + totalShares are unchanged.\n *\n * Inputs: [0]=pool (lpCovid == ZERO)\n * Outputs: [0]=pool(lpCovid bound) [1]=locked floor L(ZERO-owned, lockedShares) [2]=pool L inventory(P-owned)\n */\nexport function buildBindLp(\n k: K, tpl: PoolCpTemplate, tokenTpl: Kcc20Template,\n utxo: PoolCpUtxo, poolCovid: Uint8Array, lockedShares: bigint, opts: { tokenDust?: bigint } = {},\n): BindLpResult {\n if (utxo.state.lpCovid.length !== 32 || !utxo.state.lpCovid.every((b) => b === 0)) throw new Error('pool lpCovid is already bound — bindLp is one-time');\n if (lockedShares < 1n || lockedShares >= MAX_SHARES) throw new Error('lockedShares out of range');\n if (utxo.state.totalShares !== lockedShares) throw new Error('bindLp requires totalShares == lockedShares (graduation state)');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid } = utxo.state;\n const inventoryAmount = MAX_SHARES - lockedShares;\n const lpFloor = covenantIdOwned(ZERO32, lockedShares, false); // floor → unspendable ZERO covid\n const lpInventory = covenantIdOwned(poolCovid, inventoryAmount, false); // inventory → pool covid P\n\n const floorSpk = kcc20Spk(k, materializeKcc20Script(tokenTpl, lpFloor));\n const invSpk = kcc20Spk(k, materializeKcc20Script(tokenTpl, lpInventory));\n // L genesis covid = KIP-20 id over the pool UTXO outpoint (tx input 0) + the two L genesis outputs (idx 1,2).\n const lpCovidHex = genesisCovenantId(k, { transactionId: utxo.transactionId, index: utxo.index }, [\n { index: 1, value: dust, scriptPublicKey: floorSpk },\n { index: 2, value: dust, scriptPublicKey: invSpk },\n ]);\n const boundLp = covidToBytes(lpCovidHex);\n\n const curRedeem = materializePoolCpScript(tpl, utxo.state);\n const boundRedeem = materializePoolCpScript(tpl, { kasReserve, tokenReserve, tokenCovid, totalShares: lockedShares, lpCovid: boundLp });\n const poolValue = kasReserve * SCALE;\n\n const b = new SigScriptBuilder(k);\n pushKcc20StateScalar(b, lpFloor); pushKcc20StateScalar(b, lpInventory);\n const bindSig = b.selector(POOL_CP_SELECTOR.bindLp).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: poolValue, scriptPublicKey: poolCpSpk(k, curRedeem), signatureScript: bindSig, redeem: curRedeem, role: 'pool' },\n ];\n const poolCovidHex = hexOf(poolCovid);\n const outputs: CovOutput[] = [\n { value: poolValue, scriptPublicKey: poolCpSpk(k, boundRedeem), role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: floorSpk, role: 'lpFloor', binding: { covid: lpCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: invSpk, role: 'lpInventory', binding: { covid: lpCovidHex, authorizingInput: 0 } },\n ];\n return { kind: 'bindLp', inputs, outputs, economics: { lockedShares, inventoryAmount }, covids: { poolCovid: poolCovidHex, tokenCovid: hexOf(tokenCovid) }, lpCovidHex, lpInventoryAmount: inventoryAmount };\n}\n","// amm_pool_cp_v3 swap builders — SINGLE-TOKEN swaps (the LIVE deployed pool). Reuses the shared pool state,\n// quotes, address derivation, and LP builders from poolCpTx.ts; only the two swap entrypoints differ.\n//\n// V3 (see docs/DESIGN-single-token-swaps.md): swaps are symmetric so every trade is ONE tx / ONE signature /\n// ONE resulting token UTXO — no pre-split, no fragmentation.\n// • sell: the trader folds PART of a piece into the pool and gets the UNSOLD remainder back as one\n// presence-owned change output. covid-A outputs = [pool reserve] or [pool reserve, trader change(LAST)].\n// • buy: the trader may ALSO input their EXISTING token UTXO(s); the bought amount is merged into ONE output.\n//\n// The pool STATE layout, address derivation, and CP quotes are IDENTICAL to v2 — only the compiled script (and\n// thus the P2SH address) differs, plus the swap tx in/out shapes. So this module REUSES the v2 state/quote/\n// address helpers and only re-implements the two swap builders + the sell sig (which gains traderChangeOut).\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder } from './sigscript.js';\nimport {\n type Kcc20State, type Kcc20Template,\n materializeKcc20Script, kcc20Spk, covenantIdOwned, addressPresenceOwned, pushKcc20StateScalar, transferSigScript,\n} from './kcc20Tx.js';\nimport { SCALE } from '../curve/cpCurve.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\nimport {\n type PoolCpTemplate, type PoolCpState, type PoolCpParams, type PoolCpUtxo,\n type PoolCpBuyQuote, type PoolCpSellQuote,\n materializePoolCpScript, poolCpSpk, poolCpAddress, poolCpSpkForState, quotePoolCpBuy, quotePoolCpSell,\n} from './poolCpTx.js';\n\ntype K = Kaspa;\n\n// v3 pool == v2 pool state/template/quote; only the script (P2SH address) + swap tx shapes differ. Aliases so\n// callers can speak in v3 terms while the splice/derivation logic stays one battle-tested implementation.\nexport type PoolCpV3Template = PoolCpTemplate;\nexport type PoolCpV3State = PoolCpState;\nexport type PoolV3Params = PoolCpParams;\nexport type PoolCpV3Utxo = PoolCpUtxo;\nexport const materializePoolCpV3Script = materializePoolCpScript;\nexport const poolCpV3Spk = poolCpSpk;\nexport const poolCpV3SpkForState = poolCpSpkForState;\nexport const poolCpV3Address = poolCpAddress;\nexport const quotePoolV3Buy = quotePoolCpBuy; // pricing is unchanged from v2 (merge is a tx-build concern)\nexport const quotePoolV3Sell = quotePoolCpSell; // `tokenIn` here is the amount FOLDED; change is a tx-build concern\n\n/** v3 pool entrypoint selectors (same declaration order as v2). */\nexport const POOL_V3_SELECTOR = { swapKasForToken: 0, swapTokenForKas: 1, addLiquidity: 2, removeLiquidity: 3, bindLp: 4 } as const;\n\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\nconst p2pkSpk = (k: any, pubkey: Uint8Array) => { const sb = new k.ScriptBuilder(); sb.addData(pubkey).addOp(172); return new k.ScriptPublicKey(0, sb.drain()); };\n\nfunction v3SwapBuySig(k: K, redeem: Uint8Array, kasInUnits: bigint, tokenOut: bigint, poolTokenOut: Kcc20State, traderTokenOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasInUnits).int(tokenOut);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, traderTokenOut);\n return b.selector(POOL_V3_SELECTOR.swapKasForToken).redeem(redeem).drain();\n}\n// v3 sell takes (kasOut, poolTokenOut, traderChangeOut) — the change state is pushed even on a full sell (the\n// covenant only validates it when a 2nd covid-A output exists; otherwise it's an ignored placeholder).\nfunction v3SwapSellSig(k: K, redeem: Uint8Array, kasOutUnits: bigint, poolTokenOut: Kcc20State, traderChangeOut: Kcc20State): string {\n const b = new SigScriptBuilder(k).int(kasOutUnits);\n pushKcc20StateScalar(b, poolTokenOut); pushKcc20StateScalar(b, traderChangeOut);\n return b.selector(POOL_V3_SELECTOR.swapTokenForKas).redeem(redeem).drain();\n}\n\n/** swapKasForToken (v3 — MERGE): buy `q.tokenOut`, optionally merging the buyer's EXISTING token UTXO(s)\n * (`mergeTokens`, presence-owned, authorized by the co-present P2PK at `presenceWitnessIdx`) into ONE trader\n * output of amount `tokenOut + Σ(existing)`. With no mergeTokens it's a plain buy. Outputs: [0]=pool [1]=pool\n * token(P) [2]=trader token(presence, merged) [3]=creatorFee [4]=platformFee. kcc20 conservation pins the merge. */\nexport function buildPoolV3SwapKasForToken(\n k: K, tpl: PoolCpV3Template, tokenTpl: Kcc20Template, params: PoolV3Params,\n utxo: PoolCpV3Utxo, poolCovid: Uint8Array, traderPubkey: Uint8Array, q: PoolCpBuyQuote,\n mergeTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[] = [],\n presenceWitnessIdx = 0, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid } = utxo.state;\n const poolCovidHex = hexOf(poolCovid);\n const tokenCovidHex = hexOf(tokenCovid);\n const mergeSum = mergeTokens.reduce((s, t) => s + t.state.amount, 0n);\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false);\n const traderTokenOut = addressPresenceOwned(traderPubkey, q.tokenOut + mergeSum);\n const curRedeem = materializePoolCpV3Script(tpl, utxo.state);\n const newRedeem = materializePoolCpV3Script(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares, lpCovid });\n const poolTokInRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n // covid-A inputs: pool token (witness=pool input 0), then each merged existing token (presence → P2PK witness).\n const witnesses = [0, ...mergeTokens.map(() => presenceWitnessIdx)];\n const newStates = [poolTokenOut, traderTokenOut];\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpV3Spk(k, curRedeem), signatureScript: v3SwapBuySig(k, curRedeem, q.kasInUnits, q.tokenOut, poolTokenOut, traderTokenOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolTokInRedeem), signatureScript: transferSigScript(k, poolTokInRedeem, newStates, witnesses), redeem: poolTokInRedeem, role: 'poolToken' },\n ...mergeTokens.map((tt) => {\n const r = materializeKcc20Script(tokenTpl, tt.state);\n return { transactionId: tt.transactionId, index: tt.index, value: tt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'traderToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpV3Spk(k, newRedeem), role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderTokenOut)), role: 'trader', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: q.creatorOut, scriptPublicKey: p2pkSpk(k, params.creatorFeeOwner), role: 'creatorFee' },\n { value: q.platformOut, scriptPublicKey: p2pkSpk(k, params.platformFeeOwner), role: 'platformFee' },\n ];\n return { kind: 'swapKasForToken', inputs, outputs, economics: { kasIn: q.kasIn, tokenOut: q.tokenOut }, covids: { poolCovid: poolCovidHex, tokenCovid: tokenCovidHex } };\n}\n\n/** swapTokenForKas (v3 — FRACTIONAL): fold `q.tokenIn` of the trader's piece(s) into the pool, getting kasOut;\n * the UNSOLD remainder (Σ trader inputs − q.tokenIn) returns as ONE presence-owned change output (placed LAST).\n * Outputs: [0]=pool [1]=pool token(P) [2]=creatorFee [3]=platformFee [4]=OPTIONAL trader change(presence). */\nexport function buildPoolV3SwapTokenForKas(\n k: K, tpl: PoolCpV3Template, tokenTpl: Kcc20Template, params: PoolV3Params,\n utxo: PoolCpV3Utxo, poolCovid: Uint8Array, traderPubkey: Uint8Array,\n traderTokens: { transactionId: string; index: number; value: bigint; state: Kcc20State }[],\n q: PoolCpSellQuote, presenceWitnessIdx: number, opts: { tokenDust?: bigint } = {},\n): CovenantSpend {\n if (traderTokens.length < 1) throw new Error('need at least one trader token');\n const dust = opts.tokenDust ?? 1000n;\n const { kasReserve, tokenReserve, tokenCovid, totalShares, lpCovid } = utxo.state;\n const poolCovidHex = hexOf(poolCovid);\n const tokenCovidHex = hexOf(tokenCovid);\n const traderIn = traderTokens.reduce((s, t) => s + t.state.amount, 0n);\n const change = traderIn - q.tokenIn; // q.tokenIn == the amount folded into the reserve\n if (change < 0n) throw new Error('trader inputs are less than the sell amount');\n const hasChange = change > 0n;\n const poolTokenOut = covenantIdOwned(poolCovid, q.newToken, false);\n const traderChangeOut = addressPresenceOwned(traderPubkey, hasChange ? change : 1n); // dummy(1) on a full sell — the covenant ignores it\n const curRedeem = materializePoolCpV3Script(tpl, utxo.state);\n const newRedeem = materializePoolCpV3Script(tpl, { kasReserve: q.newKas, tokenReserve: q.newToken, tokenCovid, totalShares, lpCovid });\n const poolTokInRedeem = materializeKcc20Script(tokenTpl, covenantIdOwned(poolCovid, tokenReserve, false));\n const witnesses = [0, ...traderTokens.map(() => presenceWitnessIdx)];\n // covid-A outputs in tx order: pool reserve first (idx 1), then the change LAST (idx 4) when present.\n const newStates = hasChange ? [poolTokenOut, traderChangeOut] : [poolTokenOut];\n const inputs: CovInput[] = [\n { transactionId: utxo.transactionId, index: utxo.index, value: kasReserve * SCALE, scriptPublicKey: poolCpV3Spk(k, curRedeem), signatureScript: v3SwapSellSig(k, curRedeem, q.kasOutUnits, poolTokenOut, traderChangeOut), redeem: curRedeem, role: 'pool' },\n { transactionId: utxo.tokenUtxo.transactionId, index: utxo.tokenUtxo.index, value: utxo.tokenUtxo.value, scriptPublicKey: kcc20Spk(k, poolTokInRedeem), signatureScript: transferSigScript(k, poolTokInRedeem, newStates, witnesses), redeem: poolTokInRedeem, role: 'poolToken' },\n ...traderTokens.map((tt) => {\n const r = materializeKcc20Script(tokenTpl, tt.state);\n return { transactionId: tt.transactionId, index: tt.index, value: tt.value, scriptPublicKey: kcc20Spk(k, r), signatureScript: transferSigScript(k, r, newStates, witnesses), redeem: r, role: 'traderToken' as const };\n }),\n ];\n const outputs: CovOutput[] = [\n { value: q.newKas * SCALE, scriptPublicKey: poolCpV3Spk(k, newRedeem), role: 'pool', binding: { covid: poolCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, poolTokenOut)), role: 'poolToken', binding: { covid: tokenCovidHex, authorizingInput: 1 } },\n { value: q.creatorOut, scriptPublicKey: p2pkSpk(k, params.creatorFeeOwner), role: 'creatorFee' },\n { value: q.platformOut, scriptPublicKey: p2pkSpk(k, params.platformFeeOwner), role: 'platformFee' },\n ];\n if (hasChange) outputs.push({ value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, traderChangeOut)), role: 'trader', binding: { covid: tokenCovidHex, authorizingInput: 1 } });\n return { kind: 'swapTokenForKas', inputs, outputs, economics: { kasOut: q.kasOut, tokenIn: q.tokenIn }, covids: { poolCovid: poolCovidHex, tokenCovid: tokenCovidHex } };\n}\n","// Dev-allocation VESTING covenant builder — wires vesting.sil into Kaspa transactions. The lock OWNS the dev\n// allocation (a covid-A kcc20 token) and releases it to the creator's presence only as it vests (gated by\n// tx.locktime). This module covers the claim side (claim / claimFinal) against an already-deployed lock.\n//\n// State region (silverc state_layout {start:1, len:9}): off 1: 0x08 <claimed: 8-byte LE int>.\n// No top-level SDK import (only `import type`) — caller passes the loaded WASM namespace `k`.\nimport type { Kaspa } from '../wasm/kaspa.types.js';\nimport { SigScriptBuilder, int8LE } from './sigscript.js';\nimport {\n type Kcc20Template,\n type Kcc20State,\n materializeKcc20Script,\n kcc20Spk,\n covenantIdOwned,\n addressPresenceOwned,\n pushKcc20StateScalar,\n transferSigScript,\n} from './kcc20Tx.js';\nimport type { CovenantSpend, CovInput, CovOutput } from './spend.js';\n\ntype K = Kaspa;\ntype Spk = any;\n\n// entrypoint selectors — vesting.sil declares claim then claimFinal\nexport const VEST_SELECTOR = { claim: 0, claimFinal: 1 } as const;\n\nconst hexOf = (u8: Uint8Array): string => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');\n\n/** Tokens vested by DAA score `daaScore` (linear from startScore over durationScore; capped at total). Mirrors\n * the covenant's cross-multiplied bound exactly, so the flow can offer `vested − claimed` to claim. */\nexport function vestedAmount(total: bigint, startScore: number, durationScore: number, daaScore: number): bigint {\n if (daaScore <= startScore) return 0n;\n const elapsed = BigInt(daaScore - startScore);\n const dur = BigInt(durationScore);\n if (elapsed >= dur) return total;\n return (total * elapsed) / dur;\n}\n\n/** Fixed per-token vesting parameters (baked into the lock script by silverc). */\nexport type VestingParams = {\n creatorIdentifier: string; // x-only pubkey hex (the only allowed recipient)\n total: number; // dev allocation locked\n startScore: number; // vesting start (tx.locktime units)\n durationScore: number; // linear release length\n};\nexport type VestingTemplate = { script: Uint8Array; stateStart: number; stateLen: number; params: VestingParams };\n\n// --- state splice (off `stateStart`, 9 bytes): 0x08 <claimed:8 LE> -----------------------------\nexport function materializeVestingScript(tpl: VestingTemplate, claimed: bigint): Uint8Array {\n const s = tpl.stateStart;\n const t = tpl.script;\n if (t[s] !== 0x08) throw new Error('vesting template has an unexpected state layout (expected push8 claimed)');\n if (claimed < 0n) throw new Error('claimed must be non-negative');\n const out = t.slice();\n out[s] = 0x08;\n out.set(int8LE(claimed), s + 1);\n return out;\n}\n\nexport const vestingSpk = (k: K, redeem: Uint8Array): Spk => (k as any).payToScriptHashScript(redeem);\nexport const vestingSpkForState = (k: K, tpl: VestingTemplate, claimed: bigint): Spk => vestingSpk(k, materializeVestingScript(tpl, claimed));\n\nexport type VestUtxo = { transactionId: string; index: number; value: bigint };\n\n/**\n * Partial claim: release `release` (0 < release < remaining) to the creator's presence, re-lock the rest under\n * V. inputs [vesting(0), lockedToken(1)]; outputs [vesting cont(0), relock(1, A/V-owned), recipient(2, A/creator)].\n * The flow must set tx.lockTime = current DAA score (consensus blocks the tx until then; the covenant reads it).\n *\n * Pass `opts.tokenCovid` (the vested token's covenant id, hex — `covenantId` from the indexer) so the relock +\n * recipient outputs carry the KIP-20 covenant binding the chain requires; without it the assembled tx fails\n * on-chain. The vesting-continuation output is always bound to `vestingCovid` (already a required param).\n */\nexport function buildVestingClaim(\n k: K,\n vestTpl: VestingTemplate,\n tokenTpl: Kcc20Template,\n vestingUtxo: VestUtxo,\n lockedToken: VestUtxo,\n vestingCovid: Uint8Array,\n creatorPubkey: Uint8Array,\n claimed: bigint,\n release: bigint,\n opts: { tokenDust?: bigint; tokenCovid?: string } = {},\n): CovenantSpend {\n const total = BigInt(vestTpl.params.total);\n if (claimed < 0n || claimed >= total) throw new Error('nothing left to claim');\n const remaining = total - claimed;\n if (release <= 0n || release >= remaining) throw new Error('partial claim must be > 0 and < remaining (use claimFinal to drain)');\n const dust = opts.tokenDust ?? 1000n;\n const vestingCovidHex = hexOf(vestingCovid);\n const tokenBinding = opts.tokenCovid ? { covid: opts.tokenCovid, authorizingInput: 1 } : undefined;\n const newClaimed = claimed + release, newRemaining = remaining - release;\n\n const curRedeem = materializeVestingScript(vestTpl, claimed);\n const newRedeem = materializeVestingScript(vestTpl, newClaimed);\n const lockedState: Kcc20State = covenantIdOwned(vestingCovid, remaining, false);\n const relockState: Kcc20State = covenantIdOwned(vestingCovid, newRemaining, false);\n const recipientState: Kcc20State = addressPresenceOwned(creatorPubkey, release);\n const lockedRedeem = materializeKcc20Script(tokenTpl, lockedState);\n\n const b = new SigScriptBuilder(k).int(release);\n pushKcc20StateScalar(b, relockState);\n pushKcc20StateScalar(b, recipientState);\n const claimSig = b.selector(VEST_SELECTOR.claim).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: vestingUtxo.transactionId, index: vestingUtxo.index, value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, curRedeem), signatureScript: claimSig, redeem: curRedeem, role: 'vesting' },\n { transactionId: lockedToken.transactionId, index: lockedToken.index, value: lockedToken.value, scriptPublicKey: kcc20Spk(k, lockedRedeem), signatureScript: transferSigScript(k, lockedRedeem, [relockState, recipientState], [0]), redeem: lockedRedeem, role: 'lockedToken' },\n ];\n const outputs: CovOutput[] = [\n { value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, newRedeem), role: 'vesting', binding: { covid: vestingCovidHex, authorizingInput: 0 } }, // V continuation (claimed bumped)\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, relockState)), role: 'relock', binding: tokenBinding }, // re-locked (A, V-owned)\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, recipientState)), role: 'recipient', binding: tokenBinding }, // to creator (A, presence)\n ];\n return { kind: 'claim', inputs, outputs, economics: { release, newClaimed }, covids: opts.tokenCovid ? { tokenCovid: opts.tokenCovid } : {} };\n}\n\n/** Final claim: once fully vested, pay ALL remaining to the creator and continue V with claimed=total (husk).\n * inputs [vesting(0), lockedToken(1)]; outputs [vesting cont(0), recipient(1, A/creator)].\n *\n * Pass `opts.tokenCovid` (the vested token's covenant id, hex) so the recipient output carries the KIP-20\n * covenant binding the chain requires; without it the assembled tx fails on-chain. */\nexport function buildVestingClaimFinal(\n k: K,\n vestTpl: VestingTemplate,\n tokenTpl: Kcc20Template,\n vestingUtxo: VestUtxo,\n lockedToken: VestUtxo,\n vestingCovid: Uint8Array,\n creatorPubkey: Uint8Array,\n claimed: bigint,\n opts: { tokenDust?: bigint; tokenCovid?: string } = {},\n): CovenantSpend {\n const total = BigInt(vestTpl.params.total);\n if (claimed < 0n || claimed >= total) throw new Error('nothing left to claim');\n const remaining = total - claimed;\n const dust = opts.tokenDust ?? 1000n;\n const vestingCovidHex = hexOf(vestingCovid);\n const tokenBinding = opts.tokenCovid ? { covid: opts.tokenCovid, authorizingInput: 1 } : undefined;\n\n const curRedeem = materializeVestingScript(vestTpl, claimed);\n const newRedeem = materializeVestingScript(vestTpl, total); // husk: fully claimed\n const lockedState: Kcc20State = covenantIdOwned(vestingCovid, remaining, false);\n const recipientState: Kcc20State = addressPresenceOwned(creatorPubkey, remaining);\n const lockedRedeem = materializeKcc20Script(tokenTpl, lockedState);\n\n const b = new SigScriptBuilder(k);\n pushKcc20StateScalar(b, recipientState);\n const claimSig = b.selector(VEST_SELECTOR.claimFinal).redeem(curRedeem).drain();\n\n const inputs: CovInput[] = [\n { transactionId: vestingUtxo.transactionId, index: vestingUtxo.index, value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, curRedeem), signatureScript: claimSig, redeem: curRedeem, role: 'vesting' },\n { transactionId: lockedToken.transactionId, index: lockedToken.index, value: lockedToken.value, scriptPublicKey: kcc20Spk(k, lockedRedeem), signatureScript: transferSigScript(k, lockedRedeem, [recipientState], [0]), redeem: lockedRedeem, role: 'lockedToken' },\n ];\n const outputs: CovOutput[] = [\n { value: vestingUtxo.value, scriptPublicKey: vestingSpk(k, newRedeem), role: 'vesting', binding: { covid: vestingCovidHex, authorizingInput: 0 } },\n { value: dust, scriptPublicKey: kcc20Spk(k, materializeKcc20Script(tokenTpl, recipientState)), role: 'recipient', binding: tokenBinding },\n ];\n return { kind: 'claimFinal', inputs, outputs, economics: { release: remaining }, covids: opts.tokenCovid ? { tokenCovid: opts.tokenCovid } : {} };\n}\n","export * from './types.js';\nexport { ExampleWalletAdapter } from './example.js';\n","// Wallet abstraction — one interface, swappable implementations. This is the shape KRON's non-custodial\n// signing flow needs: build the transaction, hand specific inputs to a wallet to sign, broadcast. It is NOT\n// an officially standardized Kaspa wallet API (none exists yet — see README) — a working pattern this\n// package promotes as a reusable interface, illustrated by the generic reference implementation in\n// `example.ts`. See `docs/WALLETS.md` for how to implement this against a real wallet's injected provider.\n//\n// Capability-flag pattern: every signing method beyond `connect`/`getAddress`/`disconnect` is OPTIONAL on\n// the interface, because not every wallet implements every capability — check `capabilities()` rather than\n// assuming a method exists.\nexport type Provider = string;\nexport type Connected = { provider: Provider; address: string };\n\n/** Which of the optional signing capabilities a given adapter instance actually implements. Check this\n * before relying on a method — an adapter that returns `signPskt: false` will throw if you call it anyway. */\nexport type WalletCapabilities = {\n signPskt: boolean;\n getXOnlyPublicKey: boolean;\n signMessage: boolean;\n reconnect: boolean;\n};\n\nexport interface WalletAdapter {\n readonly provider: Provider;\n readonly label: string;\n isAvailable(): boolean;\n /** Which optional methods this adapter actually implements (vs. throws on call). */\n capabilities(): WalletCapabilities;\n /** Connect/authorize; resolves to the active kaspa:/kaspatest: address. */\n connect(): Promise<string>;\n /** Silently restore a prior session on page load WITHOUT prompting the user (an already-authorized\n * accounts lookup with no popup, if the wallet supports one). Resolves to the address, or null if there\n * is nothing to restore. */\n reconnect?(): Promise<string | null>;\n getAddress(): string | null;\n /**\n * The signPskt wallet bridge: sign ONLY the listed inputs (the user's P2PK inputs) of a tx (Safe JSON)\n * and return the signed tx (Safe JSON). Covenant inputs are never signed by the wallet — their\n * transition rules / presence-based ownership authorize them. This is what makes sell/transfer work with\n * existing wallets without KRON ever holding a key. See ../native/spend.ts `toPsktJson`.\n */\n signPskt?(txJsonString: string, signInputs: { index: number; sighashType?: number }[]): Promise<string>;\n /** The connected account's 32-byte x-only pubkey hex (the curve/pool fee owner at deploy, or a\n * presence-owned token's owner identifier). null if unavailable. */\n getXOnlyPublicKey?(): Promise<string | null>;\n /** Sign a UTF-8 message with the account key (KIP-5 Kaspa message-signing scheme — see README \"Message\n * signing\"). Returns the Schnorr signature hex + the signer's x-only pubkey hex. null if unavailable. */\n signMessage?(message: string): Promise<{ signature: string; publicKey: string } | null>;\n disconnect(): void;\n}\n\n/** Thrown by a wallet adapter method that exists on the interface but isn't implemented by a given wallet.\n * Distinct from a generic Error so callers can detect \"not supported\" vs. \"failed\". */\nexport class WalletCapabilityError extends Error {\n constructor(public readonly provider: Provider, public readonly method: string, hint?: string) {\n super(`${provider} does not implement ${method}()${hint ? ` — ${hint}` : ''}`);\n this.name = 'WalletCapabilityError';\n }\n}\n","// A generic, illustrative reference implementation of WalletAdapter — NOT tied to any specific wallet\n// product. It targets the shape most Kaspa browser-extension wallets already use for a plain send (an\n// injected `window.<walletName>` object with account/connect/sign methods), applied to the signPskt bridge\n// described in docs/WALLETS.md. Copy this file and point `GLOBAL_NAME` (and the method calls, if your\n// wallet's shape differs — see docs/WALLETS.md \"Writing your own adapter\") at your own injected provider.\nimport type { WalletAdapter, WalletCapabilities } from './types.js';\n\n/** Replace with the property name your wallet injects on `window`/`globalThis`. */\nconst GLOBAL_NAME = 'exampleWallet';\n\nconst provider = (): any => {\n const p = (globalThis as any)[GLOBAL_NAME];\n if (!p) throw new Error(`${GLOBAL_NAME} not installed`);\n return p;\n};\n\n/**\n * ExampleWalletAdapter — a template, not a real integration. It assumes a provider shaped like:\n * requestAccounts(): Promise<string[]>\n * getAccounts(): Promise<string[]> // already-authorized, no popup\n * signPskt({ txJsonString, options: { signInputs } }): Promise<string | { txJsonString }>\n * getPublicKey(): Promise<string> // compressed hex\n * signMessage(text: string): Promise<string> // KIP-5 scheme\n * If your wallet's provider looks different (a different method name, a different sighash encoding, a\n * different signing call shape entirely), adapt the method bodies accordingly — the `WalletAdapter`\n * interface only constrains what you expose, not how you get there.\n */\nexport class ExampleWalletAdapter implements WalletAdapter {\n readonly provider = GLOBAL_NAME;\n readonly label = 'Example Wallet (template)';\n private address: string | null = null;\n\n isAvailable() {\n return typeof (globalThis as any)[GLOBAL_NAME] !== 'undefined';\n }\n\n capabilities(): WalletCapabilities {\n return { signPskt: true, getXOnlyPublicKey: true, signMessage: true, reconnect: true };\n }\n\n async connect(): Promise<string> {\n const p = provider();\n const accounts: string[] = await p.requestAccounts();\n this.address = accounts?.[0] ?? null;\n if (!this.address) throw new Error('No account authorized');\n return this.address;\n }\n\n async reconnect(): Promise<string | null> {\n const p = (globalThis as any)[GLOBAL_NAME];\n if (!p) return null;\n try {\n const accounts: string[] = (await p.getAccounts?.()) ?? [];\n if (!accounts.length) return null;\n this.address = accounts[0];\n return this.address;\n } catch { return null; }\n }\n\n getAddress() { return this.address; }\n\n async signPskt(txJsonString: string, signInputs: { index: number; sighashType?: number }[]): Promise<string> {\n const p = provider();\n const options = { signInputs: signInputs.map((s) => ({ index: s.index, sighashType: s.sighashType ?? 1 })) };\n const res: any = await p.signPskt({ txJsonString, options });\n return typeof res === 'string' ? res : (res?.txJsonString ?? res?.signedTx ?? res?.tx ?? JSON.stringify(res));\n }\n\n async getXOnlyPublicKey(): Promise<string | null> {\n const p = provider();\n const pub: string | undefined = await p.getPublicKey?.();\n if (!pub) return null;\n const hex = pub.replace(/^0x/, '');\n return hex.length >= 64 ? hex.slice(-64) : null; // drop the 02/03 compression prefix -> 32-byte x-only\n }\n\n async signMessage(message: string): Promise<{ signature: string; publicKey: string } | null> {\n const p = provider();\n const publicKey = await this.getXOnlyPublicKey();\n if (!publicKey) return null;\n const signature: string = await p.signMessage(message);\n return { signature, publicKey };\n }\n\n disconnect() { this.address = null; }\n}\n","export { IndexerClient } from './indexerClient.js';\nexport { RegistryClient } from './registryClient.js';\nexport { SequencerClient } from './sequencerClient.js';\n","// Typed wrapper for the KCC-20 indexer's REST + SSE surface (docs/INTEGRATION.md §4 in the kron repo).\n// Uses the common Kaspa token-indexer response shape ({ message, result }) so existing tooling adapts with\n// minimal changes. Amounts are decimal strings in base units (apply `dec` to render); KAS values inside\n// `cpState` are sompi unless noted as SCALE units.\n\nexport type Envelope<T> = { message: string; result: T };\n\nexport type CpState = {\n realKas: number;\n tokenReserve: number;\n graduated: boolean;\n poolTokenReserve?: number;\n poolKas?: number;\n poolTotalShares?: number;\n poolLpCovid?: string;\n};\n\nexport type TokenInfo = {\n tick: string; name: string; dec: number; max: string; minted: string; holderTotal: number;\n covenantId: string; curveCovenantId: string; poolCovenantId: string | null; graduated: boolean;\n tokenReserve: string; cpState: CpState;\n price?: number; change24h?: number; volume24h?: number; volumeTotal?: number;\n trades24h?: number; tradesTotal?: number; tvl?: number; reserveKas?: string;\n};\n\nexport type Balance = { tick: string; balance: string; dec: number };\nexport type TokenUtxo = {\n outpoint: { transactionId: string; index: number };\n amount: string;\n scriptPublicKey: string;\n redeemScriptHex: string;\n ownerAddress: string;\n};\nexport type PoolHead = {\n pool: { transactionId: string; index: number };\n poolToken: { transactionId: string; index: number };\n reserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n};\nexport type LpUtxo = { outpoint: { transactionId: string; index: number }; amount: string };\nexport type LpEarnings = { tick: string; address: string; earnedKas: string };\nexport type IndexerInfo = { tokenTotal: number; daaScore: number; synced: boolean; network: string };\nexport type Trade = Record<string, unknown>;\nexport type Holder = { address: string; balance: string };\nexport type Ohlc = { t: number; o: number; h: number; l: number; c: number; v: number };\n\nasync function fetchJson<T>(url: string): Promise<T> {\n const res = await fetch(url);\n if (!res.ok) throw new Error(`${url} -> HTTP ${res.status}`);\n const body: Envelope<T> = await res.json();\n return body.result;\n}\n\nconst qs = (params: Record<string, string | number | undefined>): string => {\n const parts = Object.entries(params).filter(([, v]) => v !== undefined).map(([k, v]) => `${k}=${encodeURIComponent(String(v))}`);\n return parts.length ? `?${parts.join('&')}` : '';\n};\n\nexport class IndexerClient {\n /** @param baseUrl e.g. 'https://idx.kron.technology/v1/kcc20' (TN10) — no default baked in; pass the\n * network-appropriate URL explicitly (mainnet endpoints publish separately at launch). */\n constructor(private baseUrl: string) {}\n\n info(): Promise<IndexerInfo> { return fetchJson(`${this.baseUrl}/info`); }\n markets(opts: { kind?: 'curve' | 'pool' } = {}): Promise<TokenInfo[]> { return fetchJson(`${this.baseUrl}/markets${qs(opts)}`); }\n topTraders(): Promise<unknown[]> { return fetchJson(`${this.baseUrl}/top-traders`); }\n\n token(tick: string): Promise<TokenInfo> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}`); }\n balance(tick: string, address: string): Promise<Balance> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/address/${encodeURIComponent(address)}`);\n }\n tokenlist(address: string): Promise<Balance[]> { return fetchJson(`${this.baseUrl}/address/${encodeURIComponent(address)}/tokenlist`); }\n tokenUtxos(tick: string, address: string): Promise<TokenUtxo[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/address/${encodeURIComponent(address)}/utxos`);\n }\n\n holders(tick: string): Promise<Holder[]> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/holders`); }\n trades(tick: string, opts: { offset?: number; limit?: number } = {}): Promise<Trade[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/trades${qs(opts)}`);\n }\n ohlc(tick: string, opts: { interval: string; from?: number; to?: number }): Promise<Ohlc[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/ohlc${qs(opts)}`);\n }\n addressTrades(address: string): Promise<Trade[]> { return fetchJson(`${this.baseUrl}/address/${encodeURIComponent(address)}/trades`); }\n\n poolhead(tick: string): Promise<PoolHead> { return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/poolhead`); }\n\n lpUtxos(tick: string, address: string): Promise<LpUtxo[]> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/lp/${encodeURIComponent(address)}/utxos`);\n }\n lpEarnings(tick: string, address: string): Promise<LpEarnings> {\n return fetchJson(`${this.baseUrl}/token/${encodeURIComponent(tick)}/lp/${encodeURIComponent(address)}/earnings`);\n }\n\n /**\n * Subscribe to the SSE update stream (all tokens, or one if `tick` is given). Returns an unsubscribe\n * function. Browser: uses the native EventSource. Node: pass an EventSource-compatible constructor (e.g.\n * the `eventsource` npm package) via `EventSourceImpl` — Node has no built-in EventSource on most\n * supported versions.\n */\n stream(onUpdate: (data: unknown) => void, opts: { tick?: string; EventSourceImpl?: typeof EventSource } = {}): () => void {\n const ES = opts.EventSourceImpl ?? (globalThis as any).EventSource;\n if (!ES) throw new Error('No EventSource available — in Node, pass EventSourceImpl (e.g. from the \"eventsource\" package)');\n const es = new ES(`${this.baseUrl}/stream${qs({ tick: opts.tick })}`);\n es.addEventListener('update', (ev: MessageEvent) => {\n try { onUpdate(JSON.parse(ev.data)); } catch { /* ignore malformed events */ }\n });\n return () => es.close();\n }\n}\n","// Typed wrapper for KRON's token metadata registry (docs/INTEGRATION.md §4 \"Token metadata registry\" in the\n// kron repo). The indexer is the source of truth for amounts/trading state; this registry holds *display*\n// metadata the creator signed (name, description, image, social links, the `cp` deploy record). Read-only\n// here on purpose — registry WRITES are signature-gated to the on-chain creator key, which is out of scope\n// for a generic SDK client (a wallet/bot integrating KRON generally only needs to read this).\n\nexport type CpCurveParamsRecord = {\n creatorFeeOwner: string; platformFeeOwner: string;\n vKas: number; graduationKas: number;\n creatorFeeBps: number; platformFeeBps: number; graduationFeeBps: number;\n dexCreatorFeeBps: number; dexPlatformFeeBps: number;\n dexLpFeeBps?: number; poolLockedShares?: number; vestingCovid?: string;\n};\n\nexport type RegistryToken = {\n tick: string; name: string; creator: string; txid: string; dec: number; max: string;\n description?: string; image?: string;\n links?: { website?: string; x?: string; telegram?: string };\n cp: { curveParams: CpCurveParamsRecord; tokenCovid?: string; curveCovid?: string; poolCovid?: string; genesisTxid?: string };\n chainVerified?: boolean;\n};\n\n/** One entry of the public token list (GET /api/registry/tokenlist). tokenlists.org-shaped: the EVM-core\n * fields (network/covenantId/symbol/name/decimals/logoURI) plus a KRON `extensions` block. `covenantId`\n * (covid A) is the canonical TOKEN id (add-to-wallet / asset id); `extensions.poolCovenantId` (covid P) is\n * the POOL/PAIR id, non-null only post-graduation. `extensions.genesisTxid` is the proof pointer used by\n * verify.verifyTokenListEntry. Mirrors the `GET /api/registry/tokenlist` response contract. */\nexport type TokenListEntry = {\n network: string;\n covenantId: string;\n symbol: string; name: string; decimals: number;\n logoURI?: string;\n extensions: {\n curveCovenantId: string | null;\n poolCovenantId: string | null;\n genesisTxid: string | null;\n creator: string | null;\n creatorPubkey: string | null;\n curveParams: CpCurveParamsRecord | null;\n graduated: boolean;\n chainVerified: boolean;\n };\n};\n\n/** The token-list envelope (tokenlists.org shape). `version.minor` tracks the token count so a consumer can\n * cheaply detect list changes. */\nexport type TokenList = {\n name: string;\n timestamp: string;\n version: { major: number; minor: number; patch: number };\n network: string;\n keywords: string[];\n tokens: TokenListEntry[];\n};\n\nexport class RegistryClient {\n /** @param baseUrl e.g. 'https://api.kron.technology' (TN10) */\n constructor(private baseUrl: string) {}\n\n async tokens(): Promise<RegistryToken[]> {\n const res = await fetch(`${this.baseUrl}/api/registry/tokens`);\n if (!res.ok) throw new Error(`registry tokens -> HTTP ${res.status}`);\n const body: { tokens: RegistryToken[] } = await res.json();\n return body.tokens;\n }\n\n /** Fetch the public token list — a tokenlists.org-shaped index of KRON tokens for wallets/explorers/\n * aggregators. Default = chain-verified tokens only (anti-phishing); `{ all: true }` adds unverified ones\n * (each tagged `extensions.chainVerified:false`). Verify any entry against the chain with\n * verify.verifyTokenListEntry before trusting it. */\n async tokenlist(opts?: { all?: boolean }): Promise<TokenList> {\n const q = opts?.all ? '?all=1' : '';\n const res = await fetch(`${this.baseUrl}/api/registry/tokenlist${q}`);\n if (!res.ok) throw new Error(`registry tokenlist -> HTTP ${res.status}`);\n return (await res.json()) as TokenList;\n }\n}\n","// Typed wrapper for KRON's sequencer (docs/INTEGRATION.md §6 in the kron repo). A non-custodial batcher\n// that orders signed txs into a valid mempool chain — it never holds keys. Covers BOTH markets:\n// • graduated-pool swaps (`/head` + `/submit`, keyed by the pool P2SH), and\n// • pre-graduation bonding-curve buys/sells (`/curve/head` + `/curve/submit`, keyed by the curve covid) —\n// the curve is also a single mutable UTXO, so trades chain exactly like pool swaps.\n// Direct node submission also works under low contention; the sequencer is a convenience for hot markets.\n// `health()` reports which markets the deployed sequencer supports (`markets: ['pool','curve']`).\n\nexport type SequencerHead = {\n head: {\n poolOutpoint: { transactionId: string; index: number };\n poolTokenOutpoint: { transactionId: string; index: number };\n reserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n };\n depth: number;\n};\n\nexport type SubmitResult =\n | { ok: true; txid: string; position: number }\n | { ok: false; reason: string; retry: boolean };\n\n/** The curve head a client builds a pre-graduation buy/sell against: the curve covenant UTXO\n * (`poolOutpoint` slot) + the curve-owned token inventory (`poolTokenOutpoint` slot). `head` is null when\n * no chain is in flight (depth 0) — resolve your own live head from the node/indexer in that case. */\nexport type CurveSequencerHead = {\n poolOutpoint: { transactionId: string; index: number };\n poolTokenOutpoint: { transactionId: string; index: number };\n reserves: { realKas: string; tokenReserve: string; vKas: string };\n};\nexport type CurveHeadResult =\n | { ok: true; head: CurveSequencerHead | null; depth: number }\n | { ok: false; reason: string };\n\nexport class SequencerClient {\n /** @param baseUrl e.g. 'https://seq.kron.technology' (TN10) */\n constructor(private baseUrl: string) {}\n\n async health(): Promise<{ ok: boolean; markets?: ('pool' | 'curve')[]; attribution?: boolean }> {\n const res = await fetch(`${this.baseUrl}/health`);\n return res.json();\n }\n\n /** The in-flight head + queue depth for a pool — use this instead of the indexer's confirmed `poolhead`\n * when the pool is busy, so you build on the latest unconfirmed state. */\n async head(poolP2sh: string): Promise<SequencerHead> {\n const res = await fetch(`${this.baseUrl}/head?pool=${encodeURIComponent(poolP2sh)}`);\n if (!res.ok) throw new Error(`sequencer head -> HTTP ${res.status}`);\n return res.json();\n }\n\n /** Enqueue a signed swap tx built against a `head()` snapshot. A 409-shaped `{ok:false, retry:true}`\n * means `prevHead` is stale — re-fetch `head()` and rebuild.\n *\n * `ref` (optional) — your wallet-integrator partner tag (kron.technology/wallets): 2–32 chars of\n * `a-z 0-9 - _`, case-insensitive. Tagged trades are recorded server-side per-trade and count toward\n * your revenue share; a malformed tag is rejected with 400 so a misconfigured integration fails on the\n * first submit rather than silently at settlement. Only sequencer-routed trades carry attribution. */\n async submit(body: {\n pool: string;\n signedTx: string;\n prevHead: SequencerHead['head'];\n declaredReserves: { kasReserve: string; tokenReserve: string; totalShares: string; lpCovid: string | null };\n ref?: string;\n }): Promise<SubmitResult> {\n const res = await fetch(`${this.baseUrl}/submit`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return res.json();\n }\n\n /** The in-flight curve head + queue depth for a pre-graduation token, keyed by its curve covenant id\n * (hex). `head: null` with `ok: true` means no chain is in flight — build against the confirmed state\n * from the node/indexer instead. A `{ok:false}` gate (unknown/full/unreachable) → submit direct. */\n async curveHead(curveCovid: string): Promise<CurveHeadResult> {\n const res = await fetch(`${this.baseUrl}/curve/head?covid=${encodeURIComponent(curveCovid)}`);\n if (!res.ok && res.status !== 409) throw new Error(`sequencer curve head -> HTTP ${res.status}`);\n return res.json();\n }\n\n /** Enqueue a signed pre-graduation buy/sell built against a `curveHead()` snapshot. A 409-shaped\n * `{ok:false, retry:true}` means `prevHead` is stale — re-fetch `curveHead()` and rebuild.\n * `ref` — optional partner tag, same contract as `submit()`. */\n async curveSubmit(body: {\n covid: string;\n signedTx: string;\n prevHead: CurveSequencerHead;\n declaredReserves: { realKas: string; tokenReserve: string; vKas: string };\n ref?: string;\n }): Promise<SubmitResult> {\n const res = await fetch(`${this.baseUrl}/curve/submit`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return res.json();\n }\n\n /** SSE: head changes for a pool. Same Node-EventSource caveat as IndexerClient.stream. */\n events(poolP2sh: string, onEvent: (data: unknown) => void, EventSourceImpl?: typeof EventSource): () => void {\n const ES = EventSourceImpl ?? (globalThis as any).EventSource;\n if (!ES) throw new Error('No EventSource available — in Node, pass EventSourceImpl (e.g. from the \"eventsource\" package)');\n const es = new ES(`${this.baseUrl}/events?pool=${encodeURIComponent(poolP2sh)}`);\n es.onmessage = (ev: MessageEvent) => { try { onEvent(JSON.parse(ev.data)); } catch { /* ignore malformed events */ } };\n return () => es.close();\n }\n}\n","export { verifyTokenListEntry, kaspaRestFetchTx } from './tokenList.js';\nexport type { VerifyResult, FetchedTx, FetchTx } from './tokenList.js';\n","// Verify a token-list entry against the chain. The token list (RegistryClient.tokenlist) is self-verifiable\n// by design: each entry carries its covenantId (covid A) + a genesisTxid proof pointer, so a consumer can\n// confirm the token is a genuine on-chain covenant and not a registry spoof — WITHOUT trusting KRON's\n// backend. This is the anti-phishing check every wallet/explorer/aggregator should run before listing an\n// entry.\n//\n// The check: fetch the entry's genesis tx and confirm its covenantId appears as a `covenant_id` on one of\n// the tx's outputs (that is exactly where a KIP-20 covenant is created — proven against api-tn10). A forged\n// entry claiming a covenantId that isn't on its declared genesis tx fails.\n//\n// `fetchTx` is INJECTED: this SDK ships no Kaspa node/REST client (its own clients only talk to KRON's\n// backend/indexer). Use `kaspaRestFetchTx(baseUrl)` for the common Kaspa REST shape, or pass your own\n// (node RPC, a proxy, a fixture). NOTE: this does not re-derive the curve P2SH from params — the SDK has no\n// covenant compiler. For a full cryptographic re-derivation, feed the init tx's outpoint + authorized\n// outputs to `genesis.genesisCovenantId` (see src/native/genesis.ts).\nimport type { TokenListEntry } from '../client/registryClient.js';\n\n/** Minimal shape of a fetched Kaspa transaction — only what the verifier reads. `covenant_id` is the\n * Kaspa REST field; `covenantId` is accepted too for node/proxy shapes that camel-case it. */\nexport type FetchedTx = { outputs?: Array<{ covenant_id?: string | null; covenantId?: string | null } | null> };\nexport type FetchTx = (txid: string) => Promise<FetchedTx>;\n\nexport type VerifyResult = { ok: boolean; covenantIdPresent: boolean; reason?: string };\n\nconst lc = (s?: string | null): string => String(s ?? '').toLowerCase();\n\n/** Verify a single token-list entry against the chain via an injected tx fetcher. Never throws — a fetch\n * failure or a missing field is returned as `{ ok: false, reason }` so callers can filter a whole list. */\nexport async function verifyTokenListEntry(entry: TokenListEntry, fetchTx: FetchTx): Promise<VerifyResult> {\n const covid = lc(entry?.covenantId);\n const txid = entry?.extensions?.genesisTxid ?? null;\n if (!covid) return { ok: false, covenantIdPresent: false, reason: 'entry has no covenantId' };\n if (!txid) return { ok: false, covenantIdPresent: false, reason: 'entry has no genesisTxid to verify against' };\n\n let tx: FetchedTx;\n try {\n tx = await fetchTx(txid);\n } catch (e: any) {\n return { ok: false, covenantIdPresent: false, reason: `fetchTx failed for ${txid}: ${e?.message ?? e}` };\n }\n\n const outs = Array.isArray(tx?.outputs) ? tx.outputs : [];\n const present = outs.some((o) => lc(o?.covenant_id ?? o?.covenantId) === covid);\n return present\n ? { ok: true, covenantIdPresent: true }\n : { ok: false, covenantIdPresent: false, reason: `covenantId ${entry.covenantId} not found on any output of genesis tx ${txid}` };\n}\n\n/** A `fetchTx` for the common Kaspa REST shape: `GET {baseUrl}/transactions/{txid}?outputs=true`. Uses the\n * global `fetch` (Node ≥20 / browsers). Pass your own fetcher instead for a node RPC or a proxy. */\nexport function kaspaRestFetchTx(baseUrl: string): FetchTx {\n const base = baseUrl.replace(/\\/+$/, '');\n return async (txid: string): Promise<FetchedTx> => {\n const res = await fetch(`${base}/transactions/${encodeURIComponent(txid)}?outputs=true`);\n if (!res.ok) throw new Error(`kaspa REST tx ${txid} -> HTTP ${res.status}`);\n return (await res.json()) as FetchedTx;\n };\n}\n"],"mappings":";;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,IAAM,QAAQ;AAGd,IAAM,cAAc;AAC3B,IAAM,SAAS,CAAC,MAAe,IAAI,cAAc,IAAI;AAI9C,IAAM,UAAU;AAYvB,IAAM,UAAU,CAAC,GAAW,OAAe,IAAI,IAAI,MAAM;AAQlD,IAAM,uBAAuB;AAE7B,IAAM,qBAAqB,CAAC,KAAa,QAAwB,MAAO,MAAM,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,GAAG,CAAC,CAAC,IAAK;AAMtH,SAAS,WAAW,GAAY,YAAuC;AAC5E,QAAM,KAAK,aAAa;AACxB,QAAM,QAAQ,KAAK;AACnB,MAAI,SAAS,GAAI,QAAO;AACxB,QAAM,aAAa,EAAE,UAAU;AAC/B,MAAI,aAAa,QAAS,QAAO;AACjC,QAAM,KAAK,EAAE,UAAU;AACvB,QAAM,KAAK,EAAE,OAAO,MAAM,EAAE;AAC5B,QAAM,WAAW,QAAQ,GAAG,EAAE,OAAO,KAAK,EAAE;AAC5C,QAAM,WAAW,EAAE,e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