@secondlayer/stacks 2.19.0 → 2.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/pox5/constants.ts", "../src/pox5/activation.ts", "../src/pox5/cycles.ts", "../src/pox5/script.ts", "../src/pox5/grants.ts", "../src/pox5/abi.ts", "../src/pox5/actions.ts", "../src/pox5/extension.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * PoX-5 (SIP-045 Bitcoin Staking) constants, pinned against the final\n * contract shipped in stacks-core 4.0.1 (`stackslib/.../boot/pox-5.clar`);\n * `scripts/ci/check-pox5-pin.ts` holds the pinned tag + content hash.\n */\n\nimport { EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET } from \"../epochs.ts\";\n\n/** Boot contract name; deployer is the chain's boot address. */\nexport const POX5_CONTRACT_NAME = \"pox-5\";\n\n/** Fully-qualified mainnet contract id (boot address + `pox-5`). */\nexport const POX5_CONTRACT_ID_MAINNET: string = `SP000000000000000000002Q6VF78.${POX5_CONTRACT_NAME}`;\n\n/**\n * All print-event topic strings emitted by `pox-5.clar`. Unlike pox-2/3/4,\n * pox-5 has NO node-synthesized events — every event is a real `(print ...)`\n * with these `topic` values and the remaining tuple fields flattened at the\n * top level via `merge` (not nested under a `data` key).\n *\n * `add-to-allowlist` and `bond-distribution` are emitted per-item inside\n * folds (`setup-bond` / `calculate-rewards`), so one transaction can carry\n * many prints.\n */\nexport const POX5_EVENT_TOPICS = [\n\t\"set-bond-admin\",\n\t\"set-pause-admin\",\n\t\"pause-rewards\",\n\t\"setup-bond\",\n\t\"add-to-allowlist\",\n\t\"register-for-bond\",\n\t\"update-bond-registration\",\n\t\"register-signer\",\n\t\"stake\",\n\t\"stake-update\",\n\t\"announce-l1-early-exit\",\n\t\"unstake-sbtc\",\n\t\"unstake\",\n\t\"calculate-rewards\",\n\t\"bond-distribution\",\n\t\"claim-rewards\",\n\t\"claim-staker-rewards-for-signer\",\n\t\"grant-signer-key\",\n\t\"revoke-signer-grant\",\n] as const;\n\nexport type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];\n\n/**\n * Epoch 4.0 hard-fork activation height on mainnet — see\n * {@link EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET}. Prefer the runtime gate in\n * `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and\n * works on every network.\n */\nexport const POX5_ACTIVATION_BURN_HEIGHT_MAINNET =\n\tEPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;\n\n/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */\nexport const BOND_LENGTH_CYCLES = 12;\n\n/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */\nexport const BOND_GAP_CYCLES = 2;\n\n/** Hard cap for STX-only stake duration, in cycles (`MAX_NUM_CYCLES`). */\nexport const MAX_NUM_CYCLES = 96;\n\n/** SIP-018 domain for signer-key grants (`POX_5_SIGNER_DOMAIN`). */\nexport const POX5_SIGNER_DOMAIN = {\n\tname: \"pox-5-signer\",\n\tversion: \"1.0.0\",\n} as const;\n\n/**\n * `serialize-c-script-num` rejects values at or above 2^39 — the ceiling of a\n * 5-byte minimally-encoded ScriptNum (`ERR_INVALID_UNLOCK_HEIGHT`).\n */\nexport const C_SCRIPT_NUM_MAX = 549_755_813_888n; // 2^39\n\n/**\n * Bitcoin treats CLTV values >= 500,000,000 as Unix timestamps (BIP-65); the\n * contract rejects unlock heights at or above this so a lockup can never\n * commit a height Bitcoin would reinterpret.\n */\nexport const BITCOIN_LOCKTIME_THRESHOLD = 500_000_000n;\n",
|
|
5
|
+
"/**\n * PoX-5 (SIP-045 Bitcoin Staking) constants, pinned against the final\n * contract shipped in stacks-core 4.0.1 (`stackslib/.../boot/pox-5.clar`);\n * `scripts/ci/check-pox5-pin.ts` holds the pinned tag + content hash.\n */\n\nimport { EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET } from \"../epochs.ts\";\n\n/** Boot contract name; deployer is the chain's boot address. */\nexport const POX5_CONTRACT_NAME = \"pox-5\";\n\n/** Fully-qualified mainnet contract id (boot address + `pox-5`). */\nexport const POX5_CONTRACT_ID_MAINNET: string = `SP000000000000000000002Q6VF78.${POX5_CONTRACT_NAME}`;\n\n/**\n * All print-event topic strings emitted by `pox-5.clar`. Unlike pox-2/3/4,\n * pox-5 has NO node-synthesized events — every event is a real `(print ...)`\n * with these `topic` values and the remaining tuple fields flattened at the\n * top level via `merge` (not nested under a `data` key).\n *\n * `add-to-allowlist` and `bond-distribution` are emitted per-item inside\n * folds (`setup-bond` / `calculate-rewards`), so one transaction can carry\n * many prints.\n */\nexport const POX5_EVENT_TOPICS = [\n\t\"set-bond-admin\",\n\t\"set-pause-admin\",\n\t\"pause-rewards\",\n\t\"setup-bond\",\n\t\"add-to-allowlist\",\n\t\"register-for-bond\",\n\t\"update-bond-registration\",\n\t\"register-signer\",\n\t\"stake\",\n\t\"stake-update\",\n\t\"announce-l1-early-exit\",\n\t\"unstake-sbtc\",\n\t\"unstake\",\n\t\"calculate-rewards\",\n\t\"bond-distribution\",\n\t\"claim-rewards\",\n\t\"claim-staker-rewards-for-signer\",\n\t\"grant-signer-key\",\n\t\"revoke-signer-grant\",\n] as const;\n\nexport type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];\n\n/**\n * Epoch 4.0 hard-fork activation height on mainnet — see\n * {@link EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET}. Prefer the runtime gate in\n * `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and\n * works on every network.\n */\nexport const POX5_ACTIVATION_BURN_HEIGHT_MAINNET: typeof EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET =\n\tEPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;\n\n/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */\nexport const BOND_LENGTH_CYCLES = 12;\n\n/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */\nexport const BOND_GAP_CYCLES = 2;\n\n/** Hard cap for STX-only stake duration, in cycles (`MAX_NUM_CYCLES`). */\nexport const MAX_NUM_CYCLES = 96;\n\n/** SIP-018 domain for signer-key grants (`POX_5_SIGNER_DOMAIN`). */\nexport const POX5_SIGNER_DOMAIN = {\n\tname: \"pox-5-signer\",\n\tversion: \"1.0.0\",\n} as const;\n\n/**\n * `serialize-c-script-num` rejects values at or above 2^39 — the ceiling of a\n * 5-byte minimally-encoded ScriptNum (`ERR_INVALID_UNLOCK_HEIGHT`).\n */\nexport const C_SCRIPT_NUM_MAX = 549_755_813_888n; // 2^39\n\n/**\n * Bitcoin treats CLTV values >= 500,000,000 as Unix timestamps (BIP-65); the\n * contract rejects unlock heights at or above this so a lockup can never\n * commit a height Bitcoin would reinterpret.\n */\nexport const BITCOIN_LOCKTIME_THRESHOLD = 500_000_000n;\n",
|
|
6
6
|
"import type { Client } from \"../clients/types.ts\";\nimport { POX5_CONTRACT_NAME } from \"./constants.ts\";\n\n/**\n * Chain-reported PoX-5 activation facts, read from the node's `/v2/pox`\n * `contract_versions[]`. Present the moment nodes run stacks-core >= 4.0.0 —\n * no hardcoded heights, works on any network.\n */\nexport type Pox5Activation = {\n\t/** Fully-qualified `pox-5` contract id (boot address differs per network). */\n\tcontractId: string;\n\t/** Bitcoin block height at which Epoch 4.0 (and pox-5) activates. */\n\tactivationBurnchainBlockHeight: number;\n\t/** First reward cycle in which pox-5 governs PoX. */\n\tfirstRewardCycleId: number;\n};\n\ntype PoxInfoResponse = {\n\tcurrent_burnchain_block_height?: number;\n\tcontract_versions?: Array<{\n\t\tcontract_id: string;\n\t\tactivation_burnchain_block_height: number;\n\t\tfirst_reward_cycle_id: number;\n\t}>;\n};\n\n/**\n * Read pox-5's activation entry from the node. Returns `undefined` when the\n * node doesn't know about pox-5 yet (pre-4.0.0 node software).\n */\nexport async function getPox5Activation(\n\tclient: Client,\n): Promise<Pox5Activation | undefined> {\n\tconst info = (await client.request(\"/v2/pox\", {\n\t\tmethod: \"GET\",\n\t})) as PoxInfoResponse;\n\tconst entry = info.contract_versions?.find((v) =>\n\t\tv.contract_id.endsWith(`.${POX5_CONTRACT_NAME}`),\n\t);\n\tif (!entry) return undefined;\n\treturn {\n\t\tcontractId: entry.contract_id,\n\t\tactivationBurnchainBlockHeight: entry.activation_burnchain_block_height,\n\t\tfirstRewardCycleId: entry.first_reward_cycle_id,\n\t};\n}\n\n/**\n * Whether pox-5 is live on the node's chain: the node software knows the\n * contract AND the burnchain has reached its activation height. One request.\n */\nexport async function isPox5Active(client: Client): Promise<boolean> {\n\tconst info = (await client.request(\"/v2/pox\", {\n\t\tmethod: \"GET\",\n\t})) as PoxInfoResponse;\n\tconst entry = info.contract_versions?.find((v) =>\n\t\tv.contract_id.endsWith(`.${POX5_CONTRACT_NAME}`),\n\t);\n\tif (!entry || typeof info.current_burnchain_block_height !== \"number\")\n\t\treturn false;\n\treturn (\n\t\tinfo.current_burnchain_block_height >=\n\t\tentry.activation_burnchain_block_height\n\t);\n}\n\n/** Throw a descriptive error unless pox-5 is active on the client's chain. */\nexport async function assertPox5Active(client: Client): Promise<void> {\n\tif (!(await isPox5Active(client))) {\n\t\tthrow new Error(\n\t\t\t\"pox-5 is not active on this chain yet (Epoch 4.0 activates at Bitcoin block 960,230 on mainnet, ~2026-07-29). \" +\n\t\t\t\t\"Check getPox5Activation(client) for this network's activation height.\",\n\t\t);\n\t}\n}\n",
|
|
7
7
|
"import { BOND_GAP_CYCLES, BOND_LENGTH_CYCLES } from \"./constants.ts\";\n\n/**\n * Pure cycle/height math, mirroring the pox-5 helper read-onlys byte-for-byte\n * (`burn-height-to-reward-cycle`, `reward-cycle-to-burn-height`,\n * `bond-period-to-reward-cycle`, `burn-height-to-distribution-index`).\n *\n * All functions anchor on chain-reported parameters — pass values from\n * `/v2/pox` (`first_burnchain_block_height`, `reward_cycle_length`,\n * `prepare_cycle_length`) and `getPox5Activation` (`firstRewardCycleId` =\n * the contract's `first-bond-period-cycle`). Nothing is hardcoded, so the\n * math is correct on mainnet, testnet, and devnet alike.\n */\nexport type PoxCycleParams = {\n\t/** `/v2/pox` `first_burnchain_block_height`. */\n\tfirstBurnchainBlockHeight: number;\n\t/** `/v2/pox` `reward_cycle_length` (mainnet 2100). */\n\trewardCycleLength: number;\n};\n\nexport type BondCycleParams = PoxCycleParams & {\n\t/** pox-5's first bond-period cycle (`getPox5Activation().firstRewardCycleId`). */\n\tfirstBondPeriodCycle: number;\n};\n\n/** Reward cycle containing `burnHeight`. Mirrors `burn-height-to-reward-cycle`. */\nexport function burnHeightToRewardCycle(\n\tburnHeight: number,\n\tparams: PoxCycleParams,\n): number {\n\tif (burnHeight < params.firstBurnchainBlockHeight) {\n\t\tthrow new Error(\n\t\t\t`burnHeight ${burnHeight} precedes first burnchain block ${params.firstBurnchainBlockHeight}`,\n\t\t);\n\t}\n\treturn Math.floor(\n\t\t(burnHeight - params.firstBurnchainBlockHeight) / params.rewardCycleLength,\n\t);\n}\n\n/** Burn height at the start of `cycle`. Mirrors `reward-cycle-to-burn-height`. */\nexport function rewardCycleToBurnHeight(\n\tcycle: number,\n\tparams: PoxCycleParams,\n): number {\n\treturn params.firstBurnchainBlockHeight + cycle * params.rewardCycleLength;\n}\n\n/** Reward cycle at which bond period `bondIndex` starts. Mirrors `bond-period-to-reward-cycle`. */\nexport function bondPeriodToRewardCycle(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn params.firstBondPeriodCycle + bondIndex * BOND_GAP_CYCLES;\n}\n\n/** Burn height at which bond period `bondIndex` starts. Mirrors `bond-period-to-burn-height`. */\nexport function bondPeriodToBurnHeight(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn rewardCycleToBurnHeight(\n\t\tbondPeriodToRewardCycle(bondIndex, params),\n\t\tparams,\n\t);\n}\n\n/** First reward cycle in which bond `bondIndex`'s STX unlock (start + 12 cycles). */\nexport function bondUnlockCycle(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn bondPeriodToRewardCycle(bondIndex, params) + BOND_LENGTH_CYCLES;\n}\n\n/**\n * Distribution-cycle index at `burnHeight` — distribution cycles are half a\n * reward cycle long. Mirrors `burn-height-to-distribution-index`.\n */\nexport function burnHeightToDistributionIndex(\n\tburnHeight: number,\n\tparams: PoxCycleParams,\n): number {\n\treturn Math.floor(\n\t\t(burnHeight - params.firstBurnchainBlockHeight) /\n\t\t\tMath.floor(params.rewardCycleLength / 2),\n\t);\n}\n\n/**\n * Whether `burnHeight` falls in a cycle's prepare phase (the final\n * `prepareCycleLength` blocks). pox-5 rejects `unstake-sbtc` and\n * `announce-l1-early-exit` during a prepare phase.\n */\nexport function isInPreparePhase(\n\tburnHeight: number,\n\tparams: PoxCycleParams & { prepareCycleLength: number },\n): boolean {\n\tconst offset =\n\t\t(burnHeight - params.firstBurnchainBlockHeight) % params.rewardCycleLength;\n\treturn offset >= params.rewardCycleLength - params.prepareCycleLength;\n}\n\nexport type BondPhase = \"too-early\" | \"open\" | \"locked\" | \"unlocked\";\n\n/**\n * Coarse lifecycle phase of bond `bondIndex` at `burnHeight`: `too-early`\n * (before the bond's start is registerable), `open`/`locked` while active,\n * `unlocked` after 12 cycles.\n */\nexport function bondPhaseAtHeight(\n\tbondIndex: number,\n\tburnHeight: number,\n\tparams: BondCycleParams,\n): BondPhase {\n\tconst cycle = burnHeightToRewardCycle(burnHeight, params);\n\tconst start = bondPeriodToRewardCycle(bondIndex, params);\n\tconst unlock = bondUnlockCycle(bondIndex, params);\n\tif (cycle < start - BOND_GAP_CYCLES) return \"too-early\";\n\tif (cycle < start) return \"open\";\n\tif (cycle < unlock) return \"locked\";\n\treturn \"unlocked\";\n}\n",
|
|
8
8
|
"import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"@scure/base\";\nimport { BITCOIN_NETWORK_PARAMS } from \"../bitcoin/address.ts\";\nimport type { BitcoinNetwork } from \"../bitcoin/constants.ts\";\nimport { serializeCVBytes } from \"../clarity/serialize.ts\";\nimport { Cl } from \"../clarity/values.ts\";\nimport { concatBytes, hexToBytes } from \"../utils/encoding.ts\";\nimport { BITCOIN_LOCKTIME_THRESHOLD, C_SCRIPT_NUM_MAX } from \"./constants.ts\";\n\n/**\n * Byte-for-byte TypeScript mirrors of pox-5's Bitcoin-script helpers\n * (`serialize-c-script-num`, `push-c-script-num`, `push-script-bytes`,\n * `construct-lockup-script`, `construct-lockup-output-script`), pinned\n * against the final contract in stacks-core 4.0.1. The contract validates a\n * staker's L1 lockup output against exactly these bytes, so any divergence\n * means a rejected registration — the read-onlys on-chain double as a\n * cross-check oracle for these functions.\n */\n\n/**\n * Minimal little-endian ScriptNum encoding of a non-negative integer\n * (`0` → empty; a `0x00` sign byte is appended when the top byte's high bit\n * is set). Mirrors `serialize-c-script-num`, including its 2^39 ceiling.\n */\nexport function serializeCScriptNum(n: number | bigint): Uint8Array {\n\tconst big = typeof n === \"bigint\" ? n : BigInt(n);\n\tif (big < 0n) throw new Error(\"serializeCScriptNum: negative value\");\n\tif (big >= C_SCRIPT_NUM_MAX) {\n\t\tthrow new Error(\n\t\t\t\"serializeCScriptNum: n >= 2^39 (contract rejects with ERR_INVALID_UNLOCK_HEIGHT)\",\n\t\t);\n\t}\n\tif (big === 0n) return new Uint8Array(0);\n\tconst out: number[] = [];\n\tlet v = big;\n\twhile (v > 0n) {\n\t\tout.push(Number(v & 0xffn));\n\t\tv >>= 8n;\n\t}\n\tif ((out[out.length - 1] as number) & 0x80) out.push(0x00);\n\treturn Uint8Array.from(out);\n}\n\n/**\n * Push arbitrary bytes onto a Bitcoin script: direct length byte under 76,\n * `OP_PUSHDATA1` under 256, `OP_PUSHDATA2` otherwise. Mirrors\n * `push-script-bytes`.\n */\nexport function pushScriptBytes(bytes: Uint8Array): Uint8Array {\n\tconst len = bytes.length;\n\tif (len > 0xffff)\n\t\tthrow new Error(`pushScriptBytes: payload too large (${len} > 65535)`);\n\tlet prefix: Uint8Array;\n\tif (len < 76) prefix = Uint8Array.of(len);\n\telse if (len < 256) prefix = Uint8Array.of(0x4c, len);\n\telse prefix = Uint8Array.of(0x4d, len & 0xff, len >> 8);\n\treturn concatBytes(prefix, bytes);\n}\n\n/**\n * Push a numeric script value: `OP_0` for zero, the single-byte ops\n * `OP_1`..`OP_16` for 1–16, else a minimal ScriptNum push. Mirrors\n * `push-c-script-num`.\n */\nexport function pushCScriptNum(n: number | bigint): Uint8Array {\n\tconst big = typeof n === \"bigint\" ? n : BigInt(n);\n\tif (big === 0n) return Uint8Array.of(0x00);\n\tif (big >= 1n && big <= 16n) return Uint8Array.of(0x50 + Number(big));\n\treturn pushScriptBytes(serializeCScriptNum(big));\n}\n\n/** `to-consensus-buff?` of a principal — the staker identity the script commits to. */\nexport function stakerConsensusBuff(stxAddress: string): Uint8Array {\n\treturn serializeCVBytes(Cl.principal(stxAddress));\n}\n\n/**\n * The 32-byte witness item the early-exit branch must reveal:\n * `sha256(to-consensus-buff? staker)`. The script stores `sha256` of THIS,\n * so revealing it proves which staker the exit is for.\n */\nexport function stakerPreimage(stxAddress: string): Uint8Array {\n\treturn sha256(stakerConsensusBuff(stxAddress));\n}\n\nexport type BuildLockupScriptOptions = {\n\t/** Staker principal (standard or contract address). */\n\tstxAddress: string;\n\t/** Burn height at which the CLTV branch becomes spendable. */\n\tunlockBurnHeight: number | bigint;\n\t/** Staker-signature subscript, run last in BOTH branches. */\n\tstakerUnlockBytes: Uint8Array | string;\n\t/** Per-bond early-unlock subscript (from `protocol-bonds.early-unlock-bytes`). */\n\tearlyUnlockBytes: Uint8Array | string;\n};\n\nfunction toBytes(input: Uint8Array | string): Uint8Array {\n\treturn typeof input === \"string\" ? hexToBytes(input) : input;\n}\n\n/**\n * The L1 lockup witness script. Mirrors `construct-lockup-script`:\n *\n * ```\n * OP_IF\n * <unlockBurnHeight> OP_CHECKLOCKTIMEVERIFY\n * OP_ELSE\n * OP_SIZE <32> OP_EQUALVERIFY OP_SHA256\n * <sha256(sha256(consensus-buff(staker)))> OP_EQUALVERIFY\n * <earlyUnlockBytes>\n * OP_ENDIF\n * OP_VERIFY\n * <stakerUnlockBytes>\n * ```\n */\nexport function buildLockupScript(opts: BuildLockupScriptOptions): Uint8Array {\n\tconst height = BigInt(opts.unlockBurnHeight);\n\tif (height >= BITCOIN_LOCKTIME_THRESHOLD) {\n\t\tthrow new Error(\n\t\t\t\"unlockBurnHeight >= 500,000,000 would be read by Bitcoin as a timestamp (contract rejects it)\",\n\t\t);\n\t}\n\tconst stakerHash = sha256(stakerPreimage(opts.stxAddress));\n\treturn concatBytes(\n\t\tUint8Array.of(0x63), // OP_IF\n\t\tpushCScriptNum(height),\n\t\tUint8Array.of(0xb1, 0x67), // OP_CHECKLOCKTIMEVERIFY, OP_ELSE\n\t\t// OP_SIZE, <0x20>, OP_EQUALVERIFY, OP_SHA256, OP_PUSHBYTES_32\n\t\thexToBytes(\"82012088a820\"),\n\t\tstakerHash,\n\t\tUint8Array.of(0x88), // OP_EQUALVERIFY\n\t\ttoBytes(opts.earlyUnlockBytes),\n\t\tUint8Array.of(0x68, 0x69), // OP_ENDIF, OP_VERIFY\n\t\ttoBytes(opts.stakerUnlockBytes),\n\t);\n}\n\n/**\n * P2WSH `scriptPubKey` for a lockup script: `0x0020 || sha256(script)`.\n * Mirrors `construct-lockup-output-script`.\n */\nexport function buildLockupOutputScript(\n\topts: BuildLockupScriptOptions,\n): Uint8Array {\n\treturn concatBytes(\n\t\tUint8Array.of(0x00, 0x20),\n\t\tsha256(buildLockupScript(opts)),\n\t);\n}\n\n/** The bech32 P2WSH address a staker sends their L1 BTC lockup to. */\nexport function buildLockupAddress(\n\topts: BuildLockupScriptOptions,\n\tnetwork: BitcoinNetwork = \"mainnet\",\n): string {\n\tconst hash = sha256(buildLockupScript(opts));\n\treturn bech32.encode(BITCOIN_NETWORK_PARAMS[network].hrp, [\n\t\t0,\n\t\t...bech32.toWords(hash),\n\t]);\n}\n\n/**\n * The default staker subscript: `<pubkey> OP_CHECKSIG` — spendable by one\n * key. Any script tail is valid as far as the contract is concerned; this is\n * the common case.\n */\nexport function buildDefaultStakerUnlockBytes(\n\tpublicKey: Uint8Array | string,\n): Uint8Array {\n\tconst pubkey = toBytes(publicKey);\n\tif (pubkey.length !== 33)\n\t\tthrow new Error(`Expected 33-byte compressed pubkey, got ${pubkey.length}`);\n\treturn concatBytes(pushScriptBytes(pubkey), Uint8Array.of(0xac)); // OP_CHECKSIG\n}\n",
|
|
@@ -211,6 +211,21 @@ declare function getPox5Activation(client: Client): Promise<Pox5Activation | und
|
|
|
211
211
|
declare function isPox5Active(client: Client): Promise<boolean>;
|
|
212
212
|
/** Throw a descriptive error unless pox-5 is active on the client's chain. */
|
|
213
213
|
declare function assertPox5Active(client: Client): Promise<void>;
|
|
214
|
+
/**
|
|
215
|
+
* Stacks hard-fork epoch activation heights, as Bitcoin burn block heights.
|
|
216
|
+
*
|
|
217
|
+
* Epoch 4.0 carries both SIP-044 (the native Bitcoin SPV built-ins / Clarity 6)
|
|
218
|
+
* and SIP-045 (`pox-5` Bitcoin Staking) — one fork, one height. Keep it here so
|
|
219
|
+
* the two modules can never disagree.
|
|
220
|
+
*/
|
|
221
|
+
/**
|
|
222
|
+
* Epoch 4.0 activation height on mainnet — Bitcoin block 960,230 (~2026-07-30
|
|
223
|
+
* AM UTC, per the stacks-core 4.0.1 release notes).
|
|
224
|
+
*
|
|
225
|
+
* Only mainnet has a fixed height. On other networks, read it from the node
|
|
226
|
+
* (`getPox5Activation` for pox-5) or pass it explicitly.
|
|
227
|
+
*/
|
|
228
|
+
declare const EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET = 960230;
|
|
214
229
|
/** Boot contract name; deployer is the chain's boot address. */
|
|
215
230
|
declare const POX5_CONTRACT_NAME = "pox-5";
|
|
216
231
|
/** Fully-qualified mainnet contract id (boot address + `pox-5`). */
|
|
@@ -233,7 +248,7 @@ type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];
|
|
|
233
248
|
* `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and
|
|
234
249
|
* works on every network.
|
|
235
250
|
*/
|
|
236
|
-
declare const POX5_ACTIVATION_BURN_HEIGHT_MAINNET:
|
|
251
|
+
declare const POX5_ACTIVATION_BURN_HEIGHT_MAINNET: typeof EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;
|
|
237
252
|
/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */
|
|
238
253
|
declare const BOND_LENGTH_CYCLES = 12;
|
|
239
254
|
/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */
|
package/dist/src/pox5/index.d.ts
CHANGED
|
@@ -211,6 +211,21 @@ declare function getPox5Activation(client: Client): Promise<Pox5Activation | und
|
|
|
211
211
|
declare function isPox5Active(client: Client): Promise<boolean>;
|
|
212
212
|
/** Throw a descriptive error unless pox-5 is active on the client's chain. */
|
|
213
213
|
declare function assertPox5Active(client: Client): Promise<void>;
|
|
214
|
+
/**
|
|
215
|
+
* Stacks hard-fork epoch activation heights, as Bitcoin burn block heights.
|
|
216
|
+
*
|
|
217
|
+
* Epoch 4.0 carries both SIP-044 (the native Bitcoin SPV built-ins / Clarity 6)
|
|
218
|
+
* and SIP-045 (`pox-5` Bitcoin Staking) — one fork, one height. Keep it here so
|
|
219
|
+
* the two modules can never disagree.
|
|
220
|
+
*/
|
|
221
|
+
/**
|
|
222
|
+
* Epoch 4.0 activation height on mainnet — Bitcoin block 960,230 (~2026-07-30
|
|
223
|
+
* AM UTC, per the stacks-core 4.0.1 release notes).
|
|
224
|
+
*
|
|
225
|
+
* Only mainnet has a fixed height. On other networks, read it from the node
|
|
226
|
+
* (`getPox5Activation` for pox-5) or pass it explicitly.
|
|
227
|
+
*/
|
|
228
|
+
declare const EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET = 960230;
|
|
214
229
|
/** Boot contract name; deployer is the chain's boot address. */
|
|
215
230
|
declare const POX5_CONTRACT_NAME = "pox-5";
|
|
216
231
|
/** Fully-qualified mainnet contract id (boot address + `pox-5`). */
|
|
@@ -233,7 +248,7 @@ type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];
|
|
|
233
248
|
* `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and
|
|
234
249
|
* works on every network.
|
|
235
250
|
*/
|
|
236
|
-
declare const POX5_ACTIVATION_BURN_HEIGHT_MAINNET:
|
|
251
|
+
declare const POX5_ACTIVATION_BURN_HEIGHT_MAINNET: typeof EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;
|
|
237
252
|
/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */
|
|
238
253
|
declare const BOND_LENGTH_CYCLES = 12;
|
|
239
254
|
/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/pox5/constants.ts", "../src/pox5/activation.ts", "../src/pox5/cycles.ts", "../src/pox5/script.ts", "../src/pox5/grants.ts", "../src/pox5/abi.ts", "../src/pox5/actions.ts", "../src/pox5/extension.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * PoX-5 (SIP-045 Bitcoin Staking) constants, pinned against the final\n * contract shipped in stacks-core 4.0.1 (`stackslib/.../boot/pox-5.clar`);\n * `scripts/ci/check-pox5-pin.ts` holds the pinned tag + content hash.\n */\n\nimport { EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET } from \"../epochs.ts\";\n\n/** Boot contract name; deployer is the chain's boot address. */\nexport const POX5_CONTRACT_NAME = \"pox-5\";\n\n/** Fully-qualified mainnet contract id (boot address + `pox-5`). */\nexport const POX5_CONTRACT_ID_MAINNET: string = `SP000000000000000000002Q6VF78.${POX5_CONTRACT_NAME}`;\n\n/**\n * All print-event topic strings emitted by `pox-5.clar`. Unlike pox-2/3/4,\n * pox-5 has NO node-synthesized events — every event is a real `(print ...)`\n * with these `topic` values and the remaining tuple fields flattened at the\n * top level via `merge` (not nested under a `data` key).\n *\n * `add-to-allowlist` and `bond-distribution` are emitted per-item inside\n * folds (`setup-bond` / `calculate-rewards`), so one transaction can carry\n * many prints.\n */\nexport const POX5_EVENT_TOPICS = [\n\t\"set-bond-admin\",\n\t\"set-pause-admin\",\n\t\"pause-rewards\",\n\t\"setup-bond\",\n\t\"add-to-allowlist\",\n\t\"register-for-bond\",\n\t\"update-bond-registration\",\n\t\"register-signer\",\n\t\"stake\",\n\t\"stake-update\",\n\t\"announce-l1-early-exit\",\n\t\"unstake-sbtc\",\n\t\"unstake\",\n\t\"calculate-rewards\",\n\t\"bond-distribution\",\n\t\"claim-rewards\",\n\t\"claim-staker-rewards-for-signer\",\n\t\"grant-signer-key\",\n\t\"revoke-signer-grant\",\n] as const;\n\nexport type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];\n\n/**\n * Epoch 4.0 hard-fork activation height on mainnet — see\n * {@link EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET}. Prefer the runtime gate in\n * `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and\n * works on every network.\n */\nexport const POX5_ACTIVATION_BURN_HEIGHT_MAINNET =\n\tEPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;\n\n/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */\nexport const BOND_LENGTH_CYCLES = 12;\n\n/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */\nexport const BOND_GAP_CYCLES = 2;\n\n/** Hard cap for STX-only stake duration, in cycles (`MAX_NUM_CYCLES`). */\nexport const MAX_NUM_CYCLES = 96;\n\n/** SIP-018 domain for signer-key grants (`POX_5_SIGNER_DOMAIN`). */\nexport const POX5_SIGNER_DOMAIN = {\n\tname: \"pox-5-signer\",\n\tversion: \"1.0.0\",\n} as const;\n\n/**\n * `serialize-c-script-num` rejects values at or above 2^39 — the ceiling of a\n * 5-byte minimally-encoded ScriptNum (`ERR_INVALID_UNLOCK_HEIGHT`).\n */\nexport const C_SCRIPT_NUM_MAX = 549_755_813_888n; // 2^39\n\n/**\n * Bitcoin treats CLTV values >= 500,000,000 as Unix timestamps (BIP-65); the\n * contract rejects unlock heights at or above this so a lockup can never\n * commit a height Bitcoin would reinterpret.\n */\nexport const BITCOIN_LOCKTIME_THRESHOLD = 500_000_000n;\n",
|
|
5
|
+
"/**\n * PoX-5 (SIP-045 Bitcoin Staking) constants, pinned against the final\n * contract shipped in stacks-core 4.0.1 (`stackslib/.../boot/pox-5.clar`);\n * `scripts/ci/check-pox5-pin.ts` holds the pinned tag + content hash.\n */\n\nimport { EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET } from \"../epochs.ts\";\n\n/** Boot contract name; deployer is the chain's boot address. */\nexport const POX5_CONTRACT_NAME = \"pox-5\";\n\n/** Fully-qualified mainnet contract id (boot address + `pox-5`). */\nexport const POX5_CONTRACT_ID_MAINNET: string = `SP000000000000000000002Q6VF78.${POX5_CONTRACT_NAME}`;\n\n/**\n * All print-event topic strings emitted by `pox-5.clar`. Unlike pox-2/3/4,\n * pox-5 has NO node-synthesized events — every event is a real `(print ...)`\n * with these `topic` values and the remaining tuple fields flattened at the\n * top level via `merge` (not nested under a `data` key).\n *\n * `add-to-allowlist` and `bond-distribution` are emitted per-item inside\n * folds (`setup-bond` / `calculate-rewards`), so one transaction can carry\n * many prints.\n */\nexport const POX5_EVENT_TOPICS = [\n\t\"set-bond-admin\",\n\t\"set-pause-admin\",\n\t\"pause-rewards\",\n\t\"setup-bond\",\n\t\"add-to-allowlist\",\n\t\"register-for-bond\",\n\t\"update-bond-registration\",\n\t\"register-signer\",\n\t\"stake\",\n\t\"stake-update\",\n\t\"announce-l1-early-exit\",\n\t\"unstake-sbtc\",\n\t\"unstake\",\n\t\"calculate-rewards\",\n\t\"bond-distribution\",\n\t\"claim-rewards\",\n\t\"claim-staker-rewards-for-signer\",\n\t\"grant-signer-key\",\n\t\"revoke-signer-grant\",\n] as const;\n\nexport type Pox5EventTopic = (typeof POX5_EVENT_TOPICS)[number];\n\n/**\n * Epoch 4.0 hard-fork activation height on mainnet — see\n * {@link EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET}. Prefer the runtime gate in\n * `activation.ts` (`getPox5Activation`), which reads the node's `/v2/pox` and\n * works on every network.\n */\nexport const POX5_ACTIVATION_BURN_HEIGHT_MAINNET: typeof EPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET =\n\tEPOCH_4_ACTIVATION_BURN_HEIGHT_MAINNET;\n\n/** Length of a paired-BTC bond, in reward cycles (`BOND_LENGTH_CYCLES`). */\nexport const BOND_LENGTH_CYCLES = 12;\n\n/** Gap between consecutive bond starts, in reward cycles (`BOND_GAP_CYCLES`). */\nexport const BOND_GAP_CYCLES = 2;\n\n/** Hard cap for STX-only stake duration, in cycles (`MAX_NUM_CYCLES`). */\nexport const MAX_NUM_CYCLES = 96;\n\n/** SIP-018 domain for signer-key grants (`POX_5_SIGNER_DOMAIN`). */\nexport const POX5_SIGNER_DOMAIN = {\n\tname: \"pox-5-signer\",\n\tversion: \"1.0.0\",\n} as const;\n\n/**\n * `serialize-c-script-num` rejects values at or above 2^39 — the ceiling of a\n * 5-byte minimally-encoded ScriptNum (`ERR_INVALID_UNLOCK_HEIGHT`).\n */\nexport const C_SCRIPT_NUM_MAX = 549_755_813_888n; // 2^39\n\n/**\n * Bitcoin treats CLTV values >= 500,000,000 as Unix timestamps (BIP-65); the\n * contract rejects unlock heights at or above this so a lockup can never\n * commit a height Bitcoin would reinterpret.\n */\nexport const BITCOIN_LOCKTIME_THRESHOLD = 500_000_000n;\n",
|
|
6
6
|
"import type { Client } from \"../clients/types.ts\";\nimport { POX5_CONTRACT_NAME } from \"./constants.ts\";\n\n/**\n * Chain-reported PoX-5 activation facts, read from the node's `/v2/pox`\n * `contract_versions[]`. Present the moment nodes run stacks-core >= 4.0.0 —\n * no hardcoded heights, works on any network.\n */\nexport type Pox5Activation = {\n\t/** Fully-qualified `pox-5` contract id (boot address differs per network). */\n\tcontractId: string;\n\t/** Bitcoin block height at which Epoch 4.0 (and pox-5) activates. */\n\tactivationBurnchainBlockHeight: number;\n\t/** First reward cycle in which pox-5 governs PoX. */\n\tfirstRewardCycleId: number;\n};\n\ntype PoxInfoResponse = {\n\tcurrent_burnchain_block_height?: number;\n\tcontract_versions?: Array<{\n\t\tcontract_id: string;\n\t\tactivation_burnchain_block_height: number;\n\t\tfirst_reward_cycle_id: number;\n\t}>;\n};\n\n/**\n * Read pox-5's activation entry from the node. Returns `undefined` when the\n * node doesn't know about pox-5 yet (pre-4.0.0 node software).\n */\nexport async function getPox5Activation(\n\tclient: Client,\n): Promise<Pox5Activation | undefined> {\n\tconst info = (await client.request(\"/v2/pox\", {\n\t\tmethod: \"GET\",\n\t})) as PoxInfoResponse;\n\tconst entry = info.contract_versions?.find((v) =>\n\t\tv.contract_id.endsWith(`.${POX5_CONTRACT_NAME}`),\n\t);\n\tif (!entry) return undefined;\n\treturn {\n\t\tcontractId: entry.contract_id,\n\t\tactivationBurnchainBlockHeight: entry.activation_burnchain_block_height,\n\t\tfirstRewardCycleId: entry.first_reward_cycle_id,\n\t};\n}\n\n/**\n * Whether pox-5 is live on the node's chain: the node software knows the\n * contract AND the burnchain has reached its activation height. One request.\n */\nexport async function isPox5Active(client: Client): Promise<boolean> {\n\tconst info = (await client.request(\"/v2/pox\", {\n\t\tmethod: \"GET\",\n\t})) as PoxInfoResponse;\n\tconst entry = info.contract_versions?.find((v) =>\n\t\tv.contract_id.endsWith(`.${POX5_CONTRACT_NAME}`),\n\t);\n\tif (!entry || typeof info.current_burnchain_block_height !== \"number\")\n\t\treturn false;\n\treturn (\n\t\tinfo.current_burnchain_block_height >=\n\t\tentry.activation_burnchain_block_height\n\t);\n}\n\n/** Throw a descriptive error unless pox-5 is active on the client's chain. */\nexport async function assertPox5Active(client: Client): Promise<void> {\n\tif (!(await isPox5Active(client))) {\n\t\tthrow new Error(\n\t\t\t\"pox-5 is not active on this chain yet (Epoch 4.0 activates at Bitcoin block 960,230 on mainnet, ~2026-07-29). \" +\n\t\t\t\t\"Check getPox5Activation(client) for this network's activation height.\",\n\t\t);\n\t}\n}\n",
|
|
7
7
|
"import { BOND_GAP_CYCLES, BOND_LENGTH_CYCLES } from \"./constants.ts\";\n\n/**\n * Pure cycle/height math, mirroring the pox-5 helper read-onlys byte-for-byte\n * (`burn-height-to-reward-cycle`, `reward-cycle-to-burn-height`,\n * `bond-period-to-reward-cycle`, `burn-height-to-distribution-index`).\n *\n * All functions anchor on chain-reported parameters — pass values from\n * `/v2/pox` (`first_burnchain_block_height`, `reward_cycle_length`,\n * `prepare_cycle_length`) and `getPox5Activation` (`firstRewardCycleId` =\n * the contract's `first-bond-period-cycle`). Nothing is hardcoded, so the\n * math is correct on mainnet, testnet, and devnet alike.\n */\nexport type PoxCycleParams = {\n\t/** `/v2/pox` `first_burnchain_block_height`. */\n\tfirstBurnchainBlockHeight: number;\n\t/** `/v2/pox` `reward_cycle_length` (mainnet 2100). */\n\trewardCycleLength: number;\n};\n\nexport type BondCycleParams = PoxCycleParams & {\n\t/** pox-5's first bond-period cycle (`getPox5Activation().firstRewardCycleId`). */\n\tfirstBondPeriodCycle: number;\n};\n\n/** Reward cycle containing `burnHeight`. Mirrors `burn-height-to-reward-cycle`. */\nexport function burnHeightToRewardCycle(\n\tburnHeight: number,\n\tparams: PoxCycleParams,\n): number {\n\tif (burnHeight < params.firstBurnchainBlockHeight) {\n\t\tthrow new Error(\n\t\t\t`burnHeight ${burnHeight} precedes first burnchain block ${params.firstBurnchainBlockHeight}`,\n\t\t);\n\t}\n\treturn Math.floor(\n\t\t(burnHeight - params.firstBurnchainBlockHeight) / params.rewardCycleLength,\n\t);\n}\n\n/** Burn height at the start of `cycle`. Mirrors `reward-cycle-to-burn-height`. */\nexport function rewardCycleToBurnHeight(\n\tcycle: number,\n\tparams: PoxCycleParams,\n): number {\n\treturn params.firstBurnchainBlockHeight + cycle * params.rewardCycleLength;\n}\n\n/** Reward cycle at which bond period `bondIndex` starts. Mirrors `bond-period-to-reward-cycle`. */\nexport function bondPeriodToRewardCycle(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn params.firstBondPeriodCycle + bondIndex * BOND_GAP_CYCLES;\n}\n\n/** Burn height at which bond period `bondIndex` starts. Mirrors `bond-period-to-burn-height`. */\nexport function bondPeriodToBurnHeight(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn rewardCycleToBurnHeight(\n\t\tbondPeriodToRewardCycle(bondIndex, params),\n\t\tparams,\n\t);\n}\n\n/** First reward cycle in which bond `bondIndex`'s STX unlock (start + 12 cycles). */\nexport function bondUnlockCycle(\n\tbondIndex: number,\n\tparams: BondCycleParams,\n): number {\n\treturn bondPeriodToRewardCycle(bondIndex, params) + BOND_LENGTH_CYCLES;\n}\n\n/**\n * Distribution-cycle index at `burnHeight` — distribution cycles are half a\n * reward cycle long. Mirrors `burn-height-to-distribution-index`.\n */\nexport function burnHeightToDistributionIndex(\n\tburnHeight: number,\n\tparams: PoxCycleParams,\n): number {\n\treturn Math.floor(\n\t\t(burnHeight - params.firstBurnchainBlockHeight) /\n\t\t\tMath.floor(params.rewardCycleLength / 2),\n\t);\n}\n\n/**\n * Whether `burnHeight` falls in a cycle's prepare phase (the final\n * `prepareCycleLength` blocks). pox-5 rejects `unstake-sbtc` and\n * `announce-l1-early-exit` during a prepare phase.\n */\nexport function isInPreparePhase(\n\tburnHeight: number,\n\tparams: PoxCycleParams & { prepareCycleLength: number },\n): boolean {\n\tconst offset =\n\t\t(burnHeight - params.firstBurnchainBlockHeight) % params.rewardCycleLength;\n\treturn offset >= params.rewardCycleLength - params.prepareCycleLength;\n}\n\nexport type BondPhase = \"too-early\" | \"open\" | \"locked\" | \"unlocked\";\n\n/**\n * Coarse lifecycle phase of bond `bondIndex` at `burnHeight`: `too-early`\n * (before the bond's start is registerable), `open`/`locked` while active,\n * `unlocked` after 12 cycles.\n */\nexport function bondPhaseAtHeight(\n\tbondIndex: number,\n\tburnHeight: number,\n\tparams: BondCycleParams,\n): BondPhase {\n\tconst cycle = burnHeightToRewardCycle(burnHeight, params);\n\tconst start = bondPeriodToRewardCycle(bondIndex, params);\n\tconst unlock = bondUnlockCycle(bondIndex, params);\n\tif (cycle < start - BOND_GAP_CYCLES) return \"too-early\";\n\tif (cycle < start) return \"open\";\n\tif (cycle < unlock) return \"locked\";\n\treturn \"unlocked\";\n}\n",
|
|
8
8
|
"import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bech32 } from \"@scure/base\";\nimport { BITCOIN_NETWORK_PARAMS } from \"../bitcoin/address.ts\";\nimport type { BitcoinNetwork } from \"../bitcoin/constants.ts\";\nimport { serializeCVBytes } from \"../clarity/serialize.ts\";\nimport { Cl } from \"../clarity/values.ts\";\nimport { concatBytes, hexToBytes } from \"../utils/encoding.ts\";\nimport { BITCOIN_LOCKTIME_THRESHOLD, C_SCRIPT_NUM_MAX } from \"./constants.ts\";\n\n/**\n * Byte-for-byte TypeScript mirrors of pox-5's Bitcoin-script helpers\n * (`serialize-c-script-num`, `push-c-script-num`, `push-script-bytes`,\n * `construct-lockup-script`, `construct-lockup-output-script`), pinned\n * against the final contract in stacks-core 4.0.1. The contract validates a\n * staker's L1 lockup output against exactly these bytes, so any divergence\n * means a rejected registration — the read-onlys on-chain double as a\n * cross-check oracle for these functions.\n */\n\n/**\n * Minimal little-endian ScriptNum encoding of a non-negative integer\n * (`0` → empty; a `0x00` sign byte is appended when the top byte's high bit\n * is set). Mirrors `serialize-c-script-num`, including its 2^39 ceiling.\n */\nexport function serializeCScriptNum(n: number | bigint): Uint8Array {\n\tconst big = typeof n === \"bigint\" ? n : BigInt(n);\n\tif (big < 0n) throw new Error(\"serializeCScriptNum: negative value\");\n\tif (big >= C_SCRIPT_NUM_MAX) {\n\t\tthrow new Error(\n\t\t\t\"serializeCScriptNum: n >= 2^39 (contract rejects with ERR_INVALID_UNLOCK_HEIGHT)\",\n\t\t);\n\t}\n\tif (big === 0n) return new Uint8Array(0);\n\tconst out: number[] = [];\n\tlet v = big;\n\twhile (v > 0n) {\n\t\tout.push(Number(v & 0xffn));\n\t\tv >>= 8n;\n\t}\n\tif ((out[out.length - 1] as number) & 0x80) out.push(0x00);\n\treturn Uint8Array.from(out);\n}\n\n/**\n * Push arbitrary bytes onto a Bitcoin script: direct length byte under 76,\n * `OP_PUSHDATA1` under 256, `OP_PUSHDATA2` otherwise. Mirrors\n * `push-script-bytes`.\n */\nexport function pushScriptBytes(bytes: Uint8Array): Uint8Array {\n\tconst len = bytes.length;\n\tif (len > 0xffff)\n\t\tthrow new Error(`pushScriptBytes: payload too large (${len} > 65535)`);\n\tlet prefix: Uint8Array;\n\tif (len < 76) prefix = Uint8Array.of(len);\n\telse if (len < 256) prefix = Uint8Array.of(0x4c, len);\n\telse prefix = Uint8Array.of(0x4d, len & 0xff, len >> 8);\n\treturn concatBytes(prefix, bytes);\n}\n\n/**\n * Push a numeric script value: `OP_0` for zero, the single-byte ops\n * `OP_1`..`OP_16` for 1–16, else a minimal ScriptNum push. Mirrors\n * `push-c-script-num`.\n */\nexport function pushCScriptNum(n: number | bigint): Uint8Array {\n\tconst big = typeof n === \"bigint\" ? n : BigInt(n);\n\tif (big === 0n) return Uint8Array.of(0x00);\n\tif (big >= 1n && big <= 16n) return Uint8Array.of(0x50 + Number(big));\n\treturn pushScriptBytes(serializeCScriptNum(big));\n}\n\n/** `to-consensus-buff?` of a principal — the staker identity the script commits to. */\nexport function stakerConsensusBuff(stxAddress: string): Uint8Array {\n\treturn serializeCVBytes(Cl.principal(stxAddress));\n}\n\n/**\n * The 32-byte witness item the early-exit branch must reveal:\n * `sha256(to-consensus-buff? staker)`. The script stores `sha256` of THIS,\n * so revealing it proves which staker the exit is for.\n */\nexport function stakerPreimage(stxAddress: string): Uint8Array {\n\treturn sha256(stakerConsensusBuff(stxAddress));\n}\n\nexport type BuildLockupScriptOptions = {\n\t/** Staker principal (standard or contract address). */\n\tstxAddress: string;\n\t/** Burn height at which the CLTV branch becomes spendable. */\n\tunlockBurnHeight: number | bigint;\n\t/** Staker-signature subscript, run last in BOTH branches. */\n\tstakerUnlockBytes: Uint8Array | string;\n\t/** Per-bond early-unlock subscript (from `protocol-bonds.early-unlock-bytes`). */\n\tearlyUnlockBytes: Uint8Array | string;\n};\n\nfunction toBytes(input: Uint8Array | string): Uint8Array {\n\treturn typeof input === \"string\" ? hexToBytes(input) : input;\n}\n\n/**\n * The L1 lockup witness script. Mirrors `construct-lockup-script`:\n *\n * ```\n * OP_IF\n * <unlockBurnHeight> OP_CHECKLOCKTIMEVERIFY\n * OP_ELSE\n * OP_SIZE <32> OP_EQUALVERIFY OP_SHA256\n * <sha256(sha256(consensus-buff(staker)))> OP_EQUALVERIFY\n * <earlyUnlockBytes>\n * OP_ENDIF\n * OP_VERIFY\n * <stakerUnlockBytes>\n * ```\n */\nexport function buildLockupScript(opts: BuildLockupScriptOptions): Uint8Array {\n\tconst height = BigInt(opts.unlockBurnHeight);\n\tif (height >= BITCOIN_LOCKTIME_THRESHOLD) {\n\t\tthrow new Error(\n\t\t\t\"unlockBurnHeight >= 500,000,000 would be read by Bitcoin as a timestamp (contract rejects it)\",\n\t\t);\n\t}\n\tconst stakerHash = sha256(stakerPreimage(opts.stxAddress));\n\treturn concatBytes(\n\t\tUint8Array.of(0x63), // OP_IF\n\t\tpushCScriptNum(height),\n\t\tUint8Array.of(0xb1, 0x67), // OP_CHECKLOCKTIMEVERIFY, OP_ELSE\n\t\t// OP_SIZE, <0x20>, OP_EQUALVERIFY, OP_SHA256, OP_PUSHBYTES_32\n\t\thexToBytes(\"82012088a820\"),\n\t\tstakerHash,\n\t\tUint8Array.of(0x88), // OP_EQUALVERIFY\n\t\ttoBytes(opts.earlyUnlockBytes),\n\t\tUint8Array.of(0x68, 0x69), // OP_ENDIF, OP_VERIFY\n\t\ttoBytes(opts.stakerUnlockBytes),\n\t);\n}\n\n/**\n * P2WSH `scriptPubKey` for a lockup script: `0x0020 || sha256(script)`.\n * Mirrors `construct-lockup-output-script`.\n */\nexport function buildLockupOutputScript(\n\topts: BuildLockupScriptOptions,\n): Uint8Array {\n\treturn concatBytes(\n\t\tUint8Array.of(0x00, 0x20),\n\t\tsha256(buildLockupScript(opts)),\n\t);\n}\n\n/** The bech32 P2WSH address a staker sends their L1 BTC lockup to. */\nexport function buildLockupAddress(\n\topts: BuildLockupScriptOptions,\n\tnetwork: BitcoinNetwork = \"mainnet\",\n): string {\n\tconst hash = sha256(buildLockupScript(opts));\n\treturn bech32.encode(BITCOIN_NETWORK_PARAMS[network].hrp, [\n\t\t0,\n\t\t...bech32.toWords(hash),\n\t]);\n}\n\n/**\n * The default staker subscript: `<pubkey> OP_CHECKSIG` — spendable by one\n * key. Any script tail is valid as far as the contract is concerned; this is\n * the common case.\n */\nexport function buildDefaultStakerUnlockBytes(\n\tpublicKey: Uint8Array | string,\n): Uint8Array {\n\tconst pubkey = toBytes(publicKey);\n\tif (pubkey.length !== 33)\n\t\tthrow new Error(`Expected 33-byte compressed pubkey, got ${pubkey.length}`);\n\treturn concatBytes(pushScriptBytes(pubkey), Uint8Array.of(0xac)); // OP_CHECKSIG\n}\n",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@secondlayer/stacks",
|
|
3
|
-
"version": "2.19.
|
|
3
|
+
"version": "2.19.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -115,9 +115,7 @@
|
|
|
115
115
|
"require": "./dist/src/x402/index.cjs"
|
|
116
116
|
}
|
|
117
117
|
},
|
|
118
|
-
"files": [
|
|
119
|
-
"dist"
|
|
120
|
-
],
|
|
118
|
+
"files": ["dist"],
|
|
121
119
|
"scripts": {
|
|
122
120
|
"build": "bunup",
|
|
123
121
|
"test": "bun test",
|