@secondlayer/stacks 5.0.1 → 5.1.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.
Files changed (46) hide show
  1. package/README.md +22 -2
  2. package/dist/shared/{stacks-6gavarmy.js → stacks-1m3m1agc.js} +2 -2
  3. package/dist/shared/{stacks-db3kwavg.cjs → stacks-37kz5t9f.cjs} +4 -6
  4. package/dist/shared/{stacks-db3kwavg.cjs.map → stacks-37kz5t9f.cjs.map} +3 -3
  5. package/dist/shared/{stacks-e3nwm1dz.js → stacks-gyp5ax89.js} +3 -3
  6. package/dist/shared/{stacks-7bqkf3b0.js → stacks-mbt36bzt.js} +3 -3
  7. package/dist/shared/{stacks-ga026yxz.js → stacks-qex691bh.js} +11 -4
  8. package/dist/shared/stacks-qex691bh.js.map +11 -0
  9. package/dist/shared/{stacks-n4d8j8q3.js → stacks-v03zef3g.js} +5 -7
  10. package/dist/shared/{stacks-n4d8j8q3.js.map → stacks-v03zef3g.js.map} +3 -3
  11. package/dist/shared/{stacks-ggdz96r1.cjs → stacks-wk8yp13j.cjs} +10 -3
  12. package/dist/shared/stacks-wk8yp13j.cjs.map +11 -0
  13. package/dist/src/actions/index.js +5 -5
  14. package/dist/src/bitcoin/index.cjs +7 -1
  15. package/dist/src/bitcoin/index.cjs.map +3 -3
  16. package/dist/src/bitcoin/index.d.cts +18 -0
  17. package/dist/src/bitcoin/index.d.ts +18 -0
  18. package/dist/src/bitcoin/index.js +8 -2
  19. package/dist/src/bitcoin/index.js.map +3 -3
  20. package/dist/src/bns/index.js +3 -3
  21. package/dist/src/index.cjs +2 -1
  22. package/dist/src/index.cjs.map +2 -2
  23. package/dist/src/index.d.cts +5 -1
  24. package/dist/src/index.d.ts +5 -1
  25. package/dist/src/index.js +7 -5
  26. package/dist/src/index.js.map +2 -2
  27. package/dist/src/pox/index.js +3 -3
  28. package/dist/src/pox5/index.js +4 -4
  29. package/dist/src/sbtc/index.js +3 -3
  30. package/dist/src/simnet/index.cjs +1675 -0
  31. package/dist/src/simnet/index.cjs.map +38 -0
  32. package/dist/src/simnet/index.d.cts +133 -0
  33. package/dist/src/simnet/index.d.ts +133 -0
  34. package/dist/src/simnet/index.js +1637 -0
  35. package/dist/src/simnet/index.js.map +38 -0
  36. package/dist/src/stackingdao/index.js +3 -3
  37. package/dist/src/tools/index.cjs +11 -6
  38. package/dist/src/tools/index.cjs.map +5 -5
  39. package/dist/src/tools/index.js +11 -6
  40. package/dist/src/tools/index.js.map +5 -5
  41. package/package.json +14 -1
  42. package/dist/shared/stacks-ga026yxz.js.map +0 -11
  43. package/dist/shared/stacks-ggdz96r1.cjs.map +0 -11
  44. /package/dist/shared/{stacks-6gavarmy.js.map → stacks-1m3m1agc.js.map} +0 -0
  45. /package/dist/shared/{stacks-e3nwm1dz.js.map → stacks-gyp5ax89.js.map} +0 -0
  46. /package/dist/shared/{stacks-7bqkf3b0.js.map → stacks-mbt36bzt.js.map} +0 -0
@@ -0,0 +1,38 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/errors/base.ts", "../../../src/errors/http.ts", "../../../src/utils/encoding.ts", "../../../src/utils/hash.ts", "../../../src/transactions/authorization.ts", "../../../src/transactions/types.ts", "../../../src/transactions/multisig.ts", "../../../src/utils/c32.ts", "../../../src/clarity/types.ts", "../../../src/clarity/serialize.ts", "../../../src/transactions/wire/serialize.ts", "../../../src/transactions/signer.ts", "../../../src/errors/transaction.ts", "../../../src/utils/bytes-reader.ts", "../../../src/utils/constants.ts", "../../../src/utils/address.ts", "../../../src/clarity/values.ts", "../../../src/clarity/deserialize.ts", "../../../src/transactions/wire/deserialize.ts", "../../../src/transports/createTransport.ts", "../../../src/simnet/cv.ts", "../../../src/clarity/structuredData.ts", "../../../src/clarity/abi/standards.ts", "../../../src/clarity/abi/classify.ts", "../../../src/clarity/bridge.ts", "../../../src/simnet/errors.ts", "../../../src/simnet/transport.ts", "../../../src/chains/definitions.ts", "../../../src/simnet/chain.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Derive a stable machine-readable code from an error's `name` field:\n * `HttpRequestError` becomes `HTTP_REQUEST_ERROR`. `name` is a string\n * literal each class sets, so the code survives a bundler that mangles\n * class names. Branch on `code` instead of parsing `message`, which is\n * free to change.\n */\nfunction codeFromName(name: string): string {\n\treturn name\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n\t\t.replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n\t\t.toUpperCase();\n}\n\nexport class BaseError extends Error {\n\toverride name = \"StacksError\";\n\t#code?: string;\n\tshortMessage: string;\n\tdetails?: string;\n\n\tconstructor(\n\t\tshortMessage: string,\n\t\toptions?: { cause?: Error; details?: string; code?: string },\n\t) {\n\t\tconst message = [\n\t\t\tshortMessage,\n\t\t\toptions?.details ? `\\n${options.details}` : \"\",\n\t\t].join(\"\");\n\n\t\tsuper(message, { cause: options?.cause });\n\t\tif (options?.code !== undefined) this.#code = options.code;\n\t\tthis.shortMessage = shortMessage;\n\t\tthis.details = options?.details;\n\t}\n\n\t/**\n\t * Stable identifier for programmatic handling; survives message\n\t * rewording and minification. An explicit `code` option wins, else it\n\t * is derived from `name` (`TimeoutError` gives `TIMEOUT_ERROR`).\n\t */\n\tget code(): string {\n\t\treturn this.#code ?? codeFromName(this.name);\n\t}\n\n\tset code(value: string) {\n\t\tthis.#code = value;\n\t}\n\n\ttoJSON(): {\n\t\tname: string;\n\t\tcode: string;\n\t\tmessage: string;\n\t\tshortMessage: string;\n\t\tdetails: string | undefined;\n\t\tcause: string | undefined;\n\t} {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tcode: this.code,\n\t\t\tmessage: this.message,\n\t\t\tshortMessage: this.shortMessage,\n\t\t\tdetails: this.details,\n\t\t\tcause: this.cause instanceof Error ? this.cause.message : undefined,\n\t\t};\n\t}\n}\n",
6
+ "import { BaseError } from \"./base.ts\";\n\n/** Thrown by the HTTP transport when a response's status isn't 2xx. */\nexport class HttpRequestError extends BaseError {\n\toverride name = \"HttpRequestError\";\n\tstatus: number;\n\t/** Request URL, when the transport knows it. */\n\turl?: string;\n\t/** Request method, when the transport knows it. */\n\tmethod?: string;\n\n\tconstructor(\n\t\tstatus: number,\n\t\toptions?: {\n\t\t\tcause?: Error;\n\t\t\tdetails?: string;\n\t\t\turl?: string;\n\t\t\tmethod?: string;\n\t\t},\n\t) {\n\t\tconst where =\n\t\t\toptions?.url !== undefined\n\t\t\t\t? ` (${options.method ?? \"GET\"} ${options.url})`\n\t\t\t\t: \"\";\n\t\tsuper(`HTTP request failed with status ${status}${where}`, options);\n\t\tthis.status = status;\n\t\tthis.url = options?.url;\n\t\tthis.method = options?.method;\n\t}\n}\n",
7
+ "const hexes = Array.from({ length: 256 }, (_, i) =>\n\ti.toString(16).padStart(2, \"0\"),\n);\n\nexport function bytesToHex(bytes: Uint8Array): string {\n\tlet hex = \"\";\n\tfor (const b of bytes) {\n\t\thex += hexes[b];\n\t}\n\treturn hex;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n\tlet h = without0x(hex);\n\tif (h.length % 2) h = `0${h}`;\n\n\tconst array = new Uint8Array(h.length / 2);\n\tfor (let i = 0; i < array.length; i++) {\n\t\tconst j = i * 2;\n\t\tconst byte = Number.parseInt(h.slice(j, j + 2), 16);\n\t\tif (Number.isNaN(byte) || byte < 0)\n\t\t\tthrow new Error(\"Invalid byte sequence\");\n\t\tarray[i] = byte;\n\t}\n\treturn array;\n}\n\nexport function with0x(value: string): string {\n\treturn /^0x/i.test(value) ? value : `0x${value}`;\n}\n\nexport function without0x(value: string): string {\n\treturn /^0x/i.test(value) ? value.slice(2) : value;\n}\n\nexport function utf8ToBytes(str: string): Uint8Array {\n\treturn new TextEncoder().encode(str);\n}\n\nexport function bytesToUtf8(bytes: Uint8Array): string {\n\treturn new TextDecoder().decode(bytes);\n}\n\nexport function asciiToBytes(str: string): Uint8Array {\n\tconst bytes = new Uint8Array(str.length);\n\tfor (let i = 0; i < str.length; i++) {\n\t\tbytes[i] = str.charCodeAt(i) & 0xff;\n\t}\n\treturn bytes;\n}\n\nexport function bytesToAscii(bytes: Uint8Array): string {\n\treturn String.fromCharCode(...bytes);\n}\n\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\tif (arrays.length === 1) return arrays[0]!;\n\tconst length = arrays.reduce((a, arr) => a + arr.length, 0);\n\tconst result = new Uint8Array(length);\n\tlet pad = 0;\n\tfor (const arr of arrays) {\n\t\tresult.set(arr, pad);\n\t\tpad += arr.length;\n\t}\n\treturn result;\n}\n\nexport type IntegerType = number | string | bigint | Uint8Array;\n\nexport function intToBigInt(value: IntegerType): bigint {\n\tif (typeof value === \"bigint\") return value;\n\tif (typeof value === \"string\") return BigInt(value);\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isInteger(value))\n\t\t\tthrow new RangeError(\"Values of type 'number' must be an integer.\");\n\t\tif (value > Number.MAX_SAFE_INTEGER)\n\t\t\tthrow new RangeError(\n\t\t\t\t`Values of type 'number' must be <= ${Number.MAX_SAFE_INTEGER}. Use BigInt instead.`,\n\t\t\t);\n\t\treturn BigInt(value);\n\t}\n\tif (value instanceof Uint8Array) return BigInt(`0x${bytesToHex(value)}`);\n\tthrow new TypeError(\"Must be a number, bigint, string, or Uint8Array.\");\n}\n\nexport function intToBytes(value: IntegerType, byteLength: number): Uint8Array {\n\treturn bigIntToBytes(intToBigInt(value), byteLength);\n}\n\nexport function bigIntToBytes(value: bigint, length = 16): Uint8Array {\n\tconst hex = value.toString(16).padStart(length * 2, \"0\");\n\treturn hexToBytes(hex);\n}\n\nexport function intToHex(integer: IntegerType, byteLength = 8): string {\n\tconst value = typeof integer === \"bigint\" ? integer : intToBigInt(integer);\n\treturn value.toString(16).padStart(byteLength * 2, \"0\");\n}\n\nexport function toTwos(value: bigint, width: bigint): bigint {\n\tconst limit = BigInt(1) << (width - BigInt(1));\n\tif (value < -limit || value > limit - BigInt(1)) {\n\t\tthrow new Error(`Unable to represent integer in width: ${width}`);\n\t}\n\tif (value >= BigInt(0)) return value;\n\treturn value + (BigInt(1) << width);\n}\n\nexport function fromTwos(value: bigint, width: bigint): bigint {\n\tif (value & (BigInt(1) << (width - BigInt(1)))) {\n\t\treturn value - (BigInt(1) << width);\n\t}\n\treturn value;\n}\n\nexport function bytesToTwosBigInt(bytes: Uint8Array): bigint {\n\tif (bytes.length === 0) return 0n;\n\tconst hex = bytesToHex(bytes);\n\tif (hex.length === 0) return 0n;\n\treturn fromTwos(BigInt(`0x${hex}`), BigInt(bytes.byteLength * 8));\n}\n\nexport function writeUInt32BE(value: number): Uint8Array {\n\tconst buf = new Uint8Array(4);\n\tbuf[0] = (value >>> 24) & 0xff;\n\tbuf[1] = (value >>> 16) & 0xff;\n\tbuf[2] = (value >>> 8) & 0xff;\n\tbuf[3] = value & 0xff;\n\treturn buf;\n}\n\nexport function readUInt32BE(bytes: Uint8Array, offset = 0): number {\n\treturn (\n\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t((bytes[offset]! << 24) |\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\t(bytes[offset + 1]! << 16) |\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\t(bytes[offset + 2]! << 8) |\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\tbytes[offset + 3]!) >>>\n\t\t0\n\t);\n}\n\nexport function writeUInt16BE(value: number): Uint8Array {\n\tconst buf = new Uint8Array(2);\n\tbuf[0] = (value >>> 8) & 0xff;\n\tbuf[1] = value & 0xff;\n\treturn buf;\n}\n\nexport function readUInt16BE(bytes: Uint8Array, offset = 0): number {\n\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\treturn ((bytes[offset]! << 8) | bytes[offset + 1]!) >>> 0;\n}\n\nexport function writeUInt8(value: number): Uint8Array {\n\treturn new Uint8Array([value & 0xff]);\n}\n",
8
+ "import { ripemd160 } from \"@noble/hashes/legacy.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { sha512_256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex } from \"./encoding.ts\";\n\nexport { sha256, sha512_256, ripemd160 };\n\n/** RIPEMD160(SHA256(input)) — standard Bitcoin/Stacks address hash */\nexport function hash160(input: Uint8Array): Uint8Array {\n\treturn ripemd160(sha256(input));\n}\n\n/** Hash used for transaction IDs */\nexport function txidFromBytes(data: Uint8Array): string {\n\treturn bytesToHex(sha512_256(data));\n}\n\n/** hash160 as hex — used for P2PKH address derivation */\nexport function hashP2PKH(input: Uint8Array): string {\n\treturn bytesToHex(hash160(input));\n}\n",
9
+ "import { hmac } from \"@noble/hashes/hmac.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { etc, getPublicKey as nobleGetPublicKey, sign } from \"@noble/secp256k1\";\nimport {\n\tbytesToHex,\n\tconcatBytes,\n\thexToBytes,\n\tintToBytes,\n\tintToHex,\n} from \"../utils/encoding.ts\";\nimport { hashP2PKH, txidFromBytes } from \"../utils/hash.ts\";\nimport {\n\tAddressHashMode,\n\tAuthType,\n\ttype Authorization,\n\tPubKeyEncoding,\n\tRECOVERABLE_ECDSA_SIG_LENGTH_BYTES,\n\ttype SingleSigSpendingCondition,\n\ttype SpendingCondition,\n\ttype SponsoredAuthorization,\n\ttype StandardAuthorization,\n} from \"./types.ts\";\n\n// Ensure sync signing is available\netc.hmacSha256Sync = (key: Uint8Array, ...msgs: Uint8Array[]) => {\n\tconst h = hmac.create(sha256, key);\n\tfor (const msg of msgs) h.update(msg);\n\treturn h.digest();\n};\n\nconst EMPTY_SIG = bytesToHex(\n\tnew Uint8Array(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES),\n);\n\nexport function createSingleSigSpendingCondition(\n\tpublicKey: string,\n\tnonce: bigint,\n\tfee: bigint,\n): SingleSigSpendingCondition {\n\tconst pubKeyBytes = hexToBytes(publicKey);\n\tconst signer = hashP2PKH(pubKeyBytes);\n\tconst isCompressed = pubKeyBytes.length === 33;\n\n\treturn {\n\t\thashMode: AddressHashMode.P2PKH,\n\t\tsigner,\n\t\tnonce,\n\t\tfee,\n\t\tkeyEncoding: isCompressed\n\t\t\t? PubKeyEncoding.Compressed\n\t\t\t: PubKeyEncoding.Uncompressed,\n\t\tsignature: EMPTY_SIG,\n\t};\n}\n\nexport function createStandardAuth(\n\tspendingCondition: SpendingCondition,\n): StandardAuthorization {\n\treturn { authType: AuthType.Standard, spendingCondition };\n}\n\nexport function createSponsoredAuth(\n\tspendingCondition: SpendingCondition,\n\tsponsorSpendingCondition?: SpendingCondition,\n): SponsoredAuthorization {\n\treturn {\n\t\tauthType: AuthType.Sponsored,\n\t\tspendingCondition,\n\t\tsponsorSpendingCondition:\n\t\t\tsponsorSpendingCondition ??\n\t\t\tcreateSingleSigSpendingCondition(\"0\".repeat(66), 0n, 0n),\n\t};\n}\n\nfunction clearCondition(condition: SpendingCondition): SpendingCondition {\n\tif (\"signature\" in condition) {\n\t\treturn {\n\t\t\t...condition,\n\t\t\tnonce: 0n,\n\t\t\tfee: 0n,\n\t\t\tsignature: EMPTY_SIG,\n\t\t};\n\t}\n\treturn {\n\t\t...condition,\n\t\tnonce: 0n,\n\t\tfee: 0n,\n\t\tfields: [],\n\t};\n}\n\n/**\n * The sponsor \"signing sentinel\" used in the initial sighash of a sponsored tx.\n * Its `signer` MUST be 20 zero bytes (an empty address hash160) — NOT the\n * hash160 of a zero public key. Matching the reference (`newInitialSigHash` in\n * @stacks/transactions) is load-bearing: this exact byte layout is folded into\n * the origin's sighash, so any deviation makes the origin signature invalid and\n * the node rejects the tx with `SignatureValidation`.\n */\nfunction sponsorSigningSentinel(): SingleSigSpendingCondition {\n\treturn {\n\t\thashMode: AddressHashMode.P2PKH,\n\t\tsigner: \"00\".repeat(20),\n\t\tnonce: 0n,\n\t\tfee: 0n,\n\t\tkeyEncoding: PubKeyEncoding.Compressed,\n\t\tsignature: EMPTY_SIG,\n\t};\n}\n\nexport function intoInitialSighashAuth(auth: Authorization): Authorization {\n\tif (auth.authType === AuthType.Standard) {\n\t\treturn createStandardAuth(clearCondition(auth.spendingCondition));\n\t}\n\treturn createSponsoredAuth(\n\t\tclearCondition(auth.spendingCondition),\n\t\tsponsorSigningSentinel(),\n\t);\n}\n\n/** Compute pre-sign sighash = sha512/256(prevSigHash + authType + fee + nonce) */\nexport function sigHashPreSign(\n\tcurSigHash: string,\n\tauthType: number,\n\tfee: bigint,\n\tnonce: bigint,\n): string {\n\tconst data = concatBytes(\n\t\thexToBytes(curSigHash),\n\t\tnew Uint8Array([authType]),\n\t\tintToBytes(fee, 8),\n\t\tintToBytes(nonce, 8),\n\t);\n\treturn txidFromBytes(data);\n}\n\n/** Compute post-sign sighash = sha512/256(preSigHash + pubKeyEncoding + signature) */\nexport function sigHashPostSign(\n\tcurSigHash: string,\n\tpubKeyEncoding: number,\n\tsignature: string,\n): string {\n\tconst data = concatBytes(\n\t\thexToBytes(curSigHash),\n\t\tnew Uint8Array([pubKeyEncoding]),\n\t\thexToBytes(signature),\n\t);\n\treturn txidFromBytes(data);\n}\n\n/** Sign with private key and return VRS signature (recoveryId + r + s) */\nfunction signWithKey(privateKey: string, messageHash: string): string {\n\tconst keyBytes = hexToBytes(privateKey).slice(0, 32);\n\tconst sig = sign(messageHash, keyBytes, { lowS: true });\n\tconst recoveryIdHex = intToHex(sig.recovery, 1);\n\treturn recoveryIdHex + sig.toCompactHex();\n}\n\nexport function nextSignature(\n\tcurSigHash: string,\n\tauthType: number,\n\tfee: bigint,\n\tnonce: bigint,\n\tprivateKey: string,\n): { nextSig: string; nextSigHash: string } {\n\tconst sigHashPre = sigHashPreSign(curSigHash, authType, fee, nonce);\n\n\tconst keyBytes = hexToBytes(privateKey).slice(0, 32);\n\tconst pubKey = nobleGetPublicKey(keyBytes, true);\n\tconst isCompressed = pubKey.length === 33;\n\tconst pubKeyEncoding = isCompressed\n\t\t? PubKeyEncoding.Compressed\n\t\t: PubKeyEncoding.Uncompressed;\n\n\tconst nextSig = signWithKey(privateKey, sigHashPre);\n\tconst nextSigHash = sigHashPostSign(sigHashPre, pubKeyEncoding, nextSig);\n\n\treturn { nextSig, nextSigHash };\n}\n",
10
+ "import type { ClarityValue } from \"../clarity/types.ts\";\n\n// Auth types\nexport const AuthType = {\n\tStandard: 0x04,\n\tSponsored: 0x05,\n} as const;\nexport type AuthType = (typeof AuthType)[keyof typeof AuthType];\n\n// Payload types\nexport const PayloadType = {\n\tTokenTransfer: 0x00,\n\tSmartContract: 0x01,\n\tContractCall: 0x02,\n\tPoisonMicroblock: 0x03,\n\tCoinbase: 0x04,\n\tCoinbaseToAltRecipient: 0x05,\n\tVersionedSmartContract: 0x06,\n\tTenureChange: 0x07,\n\tNakamotoCoinbase: 0x08,\n} as const;\nexport type PayloadType = (typeof PayloadType)[keyof typeof PayloadType];\n\n// Clarity version\nexport const ClarityVersion = {\n\tClarity1: 1,\n\tClarity2: 2,\n\tClarity3: 3,\n\tClarity4: 4,\n\tClarity5: 5,\n\tClarity6: 6, // SIP-044, Epoch 4.0\n} as const;\nexport type ClarityVersion =\n\t(typeof ClarityVersion)[keyof typeof ClarityVersion];\n\n// Anchor mode (deprecated post-Nakamoto, but needed for wire format)\nexport const AnchorMode = {\n\tOnChainOnly: 0x01,\n\tOffChainOnly: 0x02,\n\tAny: 0x03,\n} as const;\nexport type AnchorMode = (typeof AnchorMode)[keyof typeof AnchorMode];\n\n// Post condition mode\nexport const PostConditionModeWire = {\n\tAllow: 0x01,\n\tDeny: 0x02,\n\tOriginator: 0x03, // SIP-040, Epoch 3.4\n} as const;\nexport type PostConditionModeWire =\n\t(typeof PostConditionModeWire)[keyof typeof PostConditionModeWire];\n\n// Address hash modes\nexport const AddressHashMode = {\n\tP2PKH: 0x00,\n\tP2SH: 0x01,\n\tP2WPKH: 0x02,\n\tP2WSH: 0x03,\n\tP2SH_NonSequential: 0x05, // SIP-027\n\tP2WSH_P2SH_NonSequential: 0x07, // SIP-027\n} as const;\nexport type AddressHashMode =\n\t(typeof AddressHashMode)[keyof typeof AddressHashMode];\n\n// Pub key encoding\nexport const PubKeyEncoding = {\n\tCompressed: 0x00,\n\tUncompressed: 0x01,\n} as const;\nexport type PubKeyEncoding =\n\t(typeof PubKeyEncoding)[keyof typeof PubKeyEncoding];\n\n// Fungible condition codes (wire format)\nexport const FungibleConditionCode = {\n\tEqual: 0x01,\n\tGreater: 0x02,\n\tGreaterEqual: 0x03,\n\tLess: 0x04,\n\tLessEqual: 0x05,\n} as const;\n\n// Non-fungible condition codes (wire format)\nexport const NonFungibleConditionCode = {\n\tSends: 0x10,\n\tDoesNotSend: 0x11,\n\tMaybeSent: 0x12, // SIP-040, Epoch 3.4\n} as const;\n\n// PoX condition codes (wire format, SIP-045)\nexport const PoxConditionCode = {\n\tWillNotPerform: 0x30,\n\tMayPerform: 0x31,\n\tWillPerform: 0x32,\n} as const;\nexport type PoxConditionCode =\n\t(typeof PoxConditionCode)[keyof typeof PoxConditionCode];\n\n// Post condition principal types\nexport const PostConditionPrincipalId = {\n\tOrigin: 0x01,\n\tStandard: 0x02,\n\tContract: 0x03,\n} as const;\n\n// Post condition asset types\nexport const AssetType = {\n\tSTX: 0x00,\n\tFungible: 0x01,\n\tNonFungible: 0x02,\n\tStaking: 0x03, // SIP-045\n\tPox: 0x04, // SIP-045\n} as const;\n\n// Auth field types\nexport const AuthFieldType = {\n\tPublicKeyCompressed: 0x00,\n\tPublicKeyUncompressed: 0x01,\n\tSignatureCompressed: 0x02,\n\tSignatureUncompressed: 0x03,\n} as const;\n\nexport const RECOVERABLE_ECDSA_SIG_LENGTH_BYTES = 65;\nexport const MEMO_MAX_LENGTH_BYTES = 34;\nexport const MAX_STRING_LENGTH_BYTES = 128;\nexport const COINBASE_BYTES_LENGTH = 32;\nexport const VRF_PROOF_BYTES_LENGTH = 80;\nexport const MICROBLOCK_HEADER_BYTES_LENGTH = 132; // 1 + 2 + 32 + 32 + 65\n\n// Tenure change cause\nexport const TenureChangeCause = {\n\tBlockFound: 0x00,\n\tExtended: 0x01,\n\tExtendedRuntime: 0x02,\n\tExtendedReadCount: 0x03,\n\tExtendedReadLength: 0x04,\n\tExtendedWriteCount: 0x05,\n\tExtendedWriteLength: 0x06,\n} as const;\nexport type TenureChangeCause =\n\t(typeof TenureChangeCause)[keyof typeof TenureChangeCause];\n\n// Token transfer payload\nexport type TokenTransferPayload = {\n\tpayloadType: typeof PayloadType.TokenTransfer;\n\trecipient: ClarityValue; // PrincipalCV\n\tamount: bigint;\n\tmemo: string;\n};\n\n// Contract call payload\nexport type ContractCallPayload = {\n\tpayloadType: typeof PayloadType.ContractCall;\n\tcontractAddress: string;\n\tcontractName: string;\n\tfunctionName: string;\n\tfunctionArgs: ClarityValue[];\n};\n\n// Smart contract deploy payload\nexport type SmartContractPayload = {\n\tpayloadType:\n\t\t| typeof PayloadType.SmartContract\n\t\t| typeof PayloadType.VersionedSmartContract;\n\tclarityVersion?: ClarityVersion;\n\tcontractName: string;\n\tcodeBody: string;\n};\n\n// Coinbase payload (appears in every pre-Nakamoto block)\nexport type CoinbasePayload = {\n\tpayloadType: typeof PayloadType.Coinbase;\n\tcoinbaseBuffer: string; // 32 bytes hex\n};\n\n// Coinbase to alt recipient payload\nexport type CoinbaseToAltRecipientPayload = {\n\tpayloadType: typeof PayloadType.CoinbaseToAltRecipient;\n\tcoinbaseBuffer: string; // 32 bytes hex\n\trecipient: ClarityValue; // PrincipalCV\n};\n\n// Poison microblock payload\nexport type PoisonMicroblockPayload = {\n\tpayloadType: typeof PayloadType.PoisonMicroblock;\n\theader1: string; // 132 bytes hex (raw microblock header)\n\theader2: string; // 132 bytes hex (raw microblock header)\n};\n\n// Tenure change payload (Nakamoto)\nexport type TenureChangePayload = {\n\tpayloadType: typeof PayloadType.TenureChange;\n\ttenureConsensusHash: string; // 20 bytes hex\n\tprevTenureConsensusHash: string; // 20 bytes hex\n\tburnViewConsensusHash: string; // 20 bytes hex\n\tpreviousTenureEnd: string; // 32 bytes hex\n\tpreviousTenureBlocks: number; // u32\n\tcause: TenureChangeCause;\n\tpubkeyHash: string; // 20 bytes hex\n};\n\n// Nakamoto coinbase payload\nexport type NakamotoCoinbasePayload = {\n\tpayloadType: typeof PayloadType.NakamotoCoinbase;\n\tcoinbaseBuffer: string; // 32 bytes hex\n\trecipient: ClarityValue | null; // Optional PrincipalCV\n\tvrfProof: string; // 80 bytes hex\n};\n\nexport type TransactionPayload =\n\t| TokenTransferPayload\n\t| ContractCallPayload\n\t| SmartContractPayload\n\t| CoinbasePayload\n\t| CoinbaseToAltRecipientPayload\n\t| PoisonMicroblockPayload\n\t| TenureChangePayload\n\t| NakamotoCoinbasePayload;\n\n// Spending condition\nexport type SingleSigSpendingCondition = {\n\thashMode: typeof AddressHashMode.P2PKH | typeof AddressHashMode.P2WPKH;\n\tsigner: string; // hash160 hex\n\tnonce: bigint;\n\tfee: bigint;\n\tkeyEncoding: PubKeyEncoding;\n\tsignature: string; // 65-byte recoverable sig hex\n};\n\nexport type TransactionAuthField = {\n\tpubKeyEncoding: PubKeyEncoding;\n\ttype: \"publicKey\" | \"signature\";\n\tdata: string; // hex\n};\n\nexport type MultiSigHashMode =\n\t| typeof AddressHashMode.P2SH\n\t| typeof AddressHashMode.P2WSH\n\t| typeof AddressHashMode.P2SH_NonSequential\n\t| typeof AddressHashMode.P2WSH_P2SH_NonSequential;\n\nexport type MultiSigSpendingCondition = {\n\thashMode: MultiSigHashMode;\n\tsigner: string;\n\tnonce: bigint;\n\tfee: bigint;\n\tfields: TransactionAuthField[];\n\tsignaturesRequired: number;\n};\n\nexport type SpendingCondition =\n\t| SingleSigSpendingCondition\n\t| MultiSigSpendingCondition;\n\nexport type StandardAuthorization = {\n\tauthType: typeof AuthType.Standard;\n\tspendingCondition: SpendingCondition;\n};\n\nexport type SponsoredAuthorization = {\n\tauthType: typeof AuthType.Sponsored;\n\tspendingCondition: SpendingCondition;\n\tsponsorSpendingCondition: SpendingCondition;\n};\n\nexport type Authorization = StandardAuthorization | SponsoredAuthorization;\n\n// Full transaction\nexport type StacksTransaction = {\n\tversion: number;\n\tchainId: number;\n\tauth: Authorization;\n\tanchorMode: AnchorMode;\n\tpostConditionMode: PostConditionModeWire;\n\tpostConditions: PostConditionWire[];\n\tpayload: TransactionPayload;\n\t/** Multi-sig signer metadata — not part of the wire format, preserved\n\t * through serialize/deserialize round-trip for auto-detection. */\n\t_multisig?: { publicKeys: string[] };\n};\n\n// Wire post condition types\nexport type PostConditionWire =\n\t| StxPostConditionWire\n\t| FtPostConditionWire\n\t| NftPostConditionWire\n\t| StakingPostConditionWire\n\t| PoxPostConditionWire;\n\nexport type StxPostConditionWire = {\n\ttype: \"stx\";\n\tprincipal: PostConditionPrincipalWire;\n\tconditionCode: number;\n\tamount: bigint;\n};\n\nexport type FtPostConditionWire = {\n\ttype: \"ft\";\n\tprincipal: PostConditionPrincipalWire;\n\tasset: AssetInfoWire;\n\tconditionCode: number;\n\tamount: bigint;\n};\n\nexport type NftPostConditionWire = {\n\ttype: \"nft\";\n\tprincipal: PostConditionPrincipalWire;\n\tasset: AssetInfoWire;\n\tconditionCode: number;\n\tassetId: ClarityValue;\n};\n\n// SIP-045: gates stake/register-for-bond/stake-update; same shape as STX\nexport type StakingPostConditionWire = {\n\ttype: \"staking\";\n\tprincipal: PostConditionPrincipalWire;\n\tconditionCode: number;\n\tamount: bigint;\n};\n\n// SIP-045: gates non-locking PoX state changes (unstake, announce-l1-early-exit, …); no amount\nexport type PoxPostConditionWire = {\n\ttype: \"pox\";\n\tprincipal: PostConditionPrincipalWire;\n\tconditionCode: PoxConditionCode;\n};\n\nexport type PostConditionPrincipalWire =\n\t| { type: \"origin\" }\n\t| { type: \"standard\"; address: string }\n\t| { type: \"contract\"; address: string; contractName: string };\n\nexport type AssetInfoWire = {\n\taddress: string;\n\tcontractName: string;\n\tassetName: string;\n};\n",
11
+ "import {\n\tgetPublicKey as nobleGetPublicKey,\n\tsign as nobleSign,\n} from \"@noble/secp256k1\";\nimport type { CustomAccount, LocalAccount } from \"../accounts/types.ts\";\nimport type { StacksChain } from \"../chains/types.ts\";\nimport { c32address } from \"../utils/c32.ts\";\nimport {\n\tbytesToHex,\n\tconcatBytes,\n\thexToBytes,\n\tintToHex,\n} from \"../utils/encoding.ts\";\nimport { hash160 } from \"../utils/hash.ts\";\nimport { txidFromBytes } from \"../utils/hash.ts\";\nimport {\n\tintoInitialSighashAuth,\n\tnextSignature,\n\tsigHashPostSign,\n\tsigHashPreSign,\n} from \"./authorization.ts\";\nimport {\n\tAddressHashMode,\n\tAuthType,\n\ttype MultiSigHashMode,\n\ttype MultiSigSpendingCondition,\n\tPubKeyEncoding,\n\ttype StacksTransaction,\n\ttype TransactionAuthField,\n} from \"./types.ts\";\nimport { serializeTransaction } from \"./wire/serialize.ts\";\n\n// OP codes for redeem script\nconst OP_CHECKMULTISIG = 0xae;\n\n/** Check if hash mode is non-sequential (SIP-027) */\nexport function isNonSequential(hashMode: number): boolean {\n\treturn (hashMode & 0x04) !== 0;\n}\n\n/** Build a Bitcoin-style redeem script for m-of-n multi-sig */\nfunction makeRedeemScript(\n\tpublicKeys: string[],\n\tsignaturesRequired: number,\n): Uint8Array {\n\tconst parts: Uint8Array[] = [];\n\tparts.push(new Uint8Array([0x50 + signaturesRequired])); // OP_n\n\tfor (const pk of publicKeys) {\n\t\tconst pkBytes = hexToBytes(pk);\n\t\tparts.push(new Uint8Array([pkBytes.length])); // length prefix (0x21 for compressed)\n\t\tparts.push(pkBytes);\n\t}\n\tparts.push(new Uint8Array([0x50 + publicKeys.length])); // OP_m\n\tparts.push(new Uint8Array([OP_CHECKMULTISIG]));\n\treturn concatBytes(...parts);\n}\n\n/** Derive a multi-sig address from public keys */\nexport function makeMultiSigAddress(\n\tpublicKeys: string[],\n\tsignaturesRequired: number,\n\tchain?: StacksChain,\n): string {\n\tif (signaturesRequired < 1 || signaturesRequired > publicKeys.length) {\n\t\tthrow new Error(\n\t\t\t`signaturesRequired must be between 1 and ${publicKeys.length}`,\n\t\t);\n\t}\n\tconst redeemScript = makeRedeemScript(publicKeys, signaturesRequired);\n\tconst signer = hash160(redeemScript);\n\tconst version = chain?.addressVersion?.multiSig ?? 20; // mainnet default\n\treturn c32address(version, bytesToHex(signer));\n}\n\n/** Create an empty multi-sig spending condition */\nexport function createMultiSigSpendingCondition(\n\tpublicKeys: string[],\n\tsignaturesRequired: number,\n\tnonce: bigint,\n\tfee: bigint,\n\thashMode: MultiSigHashMode = AddressHashMode.P2SH,\n): MultiSigSpendingCondition {\n\tconst redeemScript = makeRedeemScript(publicKeys, signaturesRequired);\n\tconst signer = bytesToHex(hash160(redeemScript));\n\n\treturn {\n\t\thashMode,\n\t\tsigner,\n\t\tnonce,\n\t\tfee,\n\t\tfields: [],\n\t\tsignaturesRequired,\n\t};\n}\n\n/** Compute the initial sighash for a transaction (same as signBegin) */\nfunction initialSigHash(tx: StacksTransaction): string {\n\tconst cleared: StacksTransaction = {\n\t\t...tx,\n\t\tauth: intoInitialSighashAuth(tx.auth),\n\t};\n\treturn txidFromBytes(serializeTransaction(cleared));\n}\n\n/** Compute the presign-sighash used by all non-sequential signers */\nfunction nonSequentialPreSignHash(tx: StacksTransaction): string {\n\tconst condition = tx.auth.spendingCondition as MultiSigSpendingCondition;\n\tconst initHash = initialSigHash(tx);\n\treturn sigHashPreSign(\n\t\tinitHash,\n\t\tAuthType.Standard,\n\t\tcondition.fee,\n\t\tcondition.nonce,\n\t);\n}\n\n/** Replay sighash through existing auth fields of a multi-sig tx */\nexport function replayMultiSigSigHash(tx: StacksTransaction): string {\n\tconst condition = tx.auth.spendingCondition as MultiSigSpendingCondition;\n\n\t// Non-sequential: all signers sign the same presign-sighash, no field chaining\n\tif (isNonSequential(condition.hashMode)) {\n\t\tconst preSign = nonSequentialPreSignHash(tx);\n\t\t// Chain through all fields to get the final sighash\n\t\tlet curSigHash = preSign;\n\t\tfor (const field of condition.fields) {\n\t\t\tcurSigHash = sigHashPostSign(\n\t\t\t\tcurSigHash,\n\t\t\t\tfield.pubKeyEncoding,\n\t\t\t\tfield.data,\n\t\t\t);\n\t\t}\n\t\treturn curSigHash;\n\t}\n\n\t// Sequential: chain through all fields\n\tlet curSigHash = initialSigHash(tx);\n\tfor (const field of condition.fields) {\n\t\tconst preSign = sigHashPreSign(\n\t\t\tcurSigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tcurSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);\n\t}\n\treturn curSigHash;\n}\n\n/** Sign one position of a multi-sig transaction with a private key */\nexport function signMultiSig(\n\ttx: StacksTransaction,\n\tprivateKey: string,\n\tpublicKeys: string[],\n): StacksTransaction {\n\tconst keyBytes = hexToBytes(privateKey).slice(0, 32);\n\tconst signerPubKey = bytesToHex(nobleGetPublicKey(keyBytes, true));\n\n\tconst signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);\n\tif (signerIndex === -1) {\n\t\tthrow new Error(\n\t\t\t\"Private key does not correspond to any signer in the multi-sig\",\n\t\t);\n\t}\n\n\tconst condition = {\n\t\t...(tx.auth.spendingCondition as MultiSigSpendingCondition),\n\t};\n\n\t// Non-sequential: all signers sign the same presign-sighash independently\n\tif (isNonSequential(condition.hashMode)) {\n\t\treturn signNonSequential(tx, condition, privateKey);\n\t}\n\n\t// Sequential: existing P2SH behavior\n\treturn signSequential(tx, condition, privateKey, publicKeys, signerIndex);\n}\n\n/** Non-sequential signing: compute presign-sighash from initial tx, sign, append */\nfunction signNonSequential(\n\ttx: StacksTransaction,\n\tcondition: MultiSigSpendingCondition,\n\tprivateKey: string,\n): StacksTransaction {\n\tconst fields = [...condition.fields];\n\tconst preSignHash = nonSequentialPreSignHash(tx);\n\n\t// Sign the presign-sighash directly\n\tconst keyBytes = hexToBytes(privateKey).slice(0, 32);\n\tconst sig = nobleSign(preSignHash, keyBytes, { lowS: true });\n\tconst recoveryIdHex = intToHex(sig.recovery, 1);\n\tconst nextSig = recoveryIdHex + sig.toCompactHex();\n\n\tfields.push({\n\t\ttype: \"signature\",\n\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\tdata: nextSig,\n\t});\n\n\tconst newCondition: MultiSigSpendingCondition = { ...condition, fields };\n\tconst sigCount = fields.filter((f) => f.type === \"signature\").length;\n\n\t// Auto-finalize: non-sequential needs no pubkey gap-filling\n\tif (sigCount >= condition.signaturesRequired) {\n\t\treturn {\n\t\t\t...tx,\n\t\t\tauth: { ...tx.auth, spendingCondition: newCondition },\n\t\t};\n\t}\n\n\treturn {\n\t\t...tx,\n\t\tauth: { ...tx.auth, spendingCondition: newCondition },\n\t};\n}\n\n/** Sequential signing: existing P2SH behavior */\nfunction signSequential(\n\ttx: StacksTransaction,\n\tcondition: MultiSigSpendingCondition,\n\tprivateKey: string,\n\tpublicKeys: string[],\n\tsignerIndex: number,\n): StacksTransaction {\n\tconst fields = [...condition.fields];\n\n\t// Replay sighash through existing fields\n\tlet curSigHash = initialSigHash(tx);\n\tfor (const field of fields) {\n\t\tconst preSign = sigHashPreSign(\n\t\t\tcurSigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tcurSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);\n\t}\n\n\t// Fill intervening positions with pubkey fields\n\tfor (let i = fields.length; i < signerIndex; i++) {\n\t\tconst pubKeyField: TransactionAuthField = {\n\t\t\ttype: \"publicKey\",\n\t\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tdata: publicKeys[i]!,\n\t\t};\n\t\tfields.push(pubKeyField);\n\t\tconst preSign = sigHashPreSign(\n\t\t\tcurSigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tcurSigHash = sigHashPostSign(\n\t\t\tpreSign,\n\t\t\tpubKeyField.pubKeyEncoding,\n\t\t\tpubKeyField.data,\n\t\t);\n\t}\n\n\t// Sign at signerIndex\n\tconst { nextSig, nextSigHash } = nextSignature(\n\t\tcurSigHash,\n\t\tAuthType.Standard,\n\t\tcondition.fee,\n\t\tcondition.nonce,\n\t\tprivateKey,\n\t);\n\n\tfields.push({\n\t\ttype: \"signature\",\n\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\tdata: nextSig,\n\t});\n\tcurSigHash = nextSigHash;\n\n\tconst newCondition: MultiSigSpendingCondition = { ...condition, fields };\n\n\t// Count signatures so far\n\tconst sigCount = fields.filter((f) => f.type === \"signature\").length;\n\tlet finalCondition = newCondition;\n\n\t// Auto-finalize if enough signatures collected\n\tif (sigCount >= condition.signaturesRequired) {\n\t\tfinalCondition = finalizeMultiSigCondition(\n\t\t\tnewCondition,\n\t\t\tpublicKeys,\n\t\t\tcurSigHash,\n\t\t);\n\t}\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...tx.auth,\n\t\t\tspendingCondition: finalCondition,\n\t\t},\n\t};\n}\n\n/** Sign one position of a multi-sig transaction with an account */\nexport async function signMultiSigWithAccount(\n\ttx: StacksTransaction,\n\taccount: LocalAccount | CustomAccount,\n\tpublicKeys: string[],\n): Promise<StacksTransaction> {\n\tconst signerPubKey = account.publicKey;\n\n\tconst signerIndex = publicKeys.findIndex((pk) => pk === signerPubKey);\n\tif (signerIndex === -1) {\n\t\tthrow new Error(\n\t\t\t\"Account does not correspond to any signer in the multi-sig\",\n\t\t);\n\t}\n\n\tconst condition = {\n\t\t...(tx.auth.spendingCondition as MultiSigSpendingCondition),\n\t};\n\n\t// Non-sequential: all signers sign the same presign-sighash independently\n\tif (isNonSequential(condition.hashMode)) {\n\t\treturn signNonSequentialWithAccount(tx, condition, account);\n\t}\n\n\t// Sequential: existing behavior\n\treturn signSequentialWithAccount(\n\t\ttx,\n\t\tcondition,\n\t\taccount,\n\t\tpublicKeys,\n\t\tsignerIndex,\n\t);\n}\n\n/** Non-sequential signing with account */\nasync function signNonSequentialWithAccount(\n\ttx: StacksTransaction,\n\tcondition: MultiSigSpendingCondition,\n\taccount: LocalAccount | CustomAccount,\n): Promise<StacksTransaction> {\n\tconst fields = [...condition.fields];\n\tconst preSignHash = nonSequentialPreSignHash(tx);\n\n\tconst sigBytes = await account.sign(hexToBytes(preSignHash));\n\tconst nextSig = bytesToHex(sigBytes);\n\n\tfields.push({\n\t\ttype: \"signature\",\n\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\tdata: nextSig,\n\t});\n\n\tconst newCondition: MultiSigSpendingCondition = { ...condition, fields };\n\n\treturn {\n\t\t...tx,\n\t\tauth: { ...tx.auth, spendingCondition: newCondition },\n\t};\n}\n\n/** Sequential signing with account */\nasync function signSequentialWithAccount(\n\ttx: StacksTransaction,\n\tcondition: MultiSigSpendingCondition,\n\taccount: LocalAccount | CustomAccount,\n\tpublicKeys: string[],\n\tsignerIndex: number,\n): Promise<StacksTransaction> {\n\tconst fields = [...condition.fields];\n\n\t// Replay sighash through existing fields\n\tlet curSigHash = initialSigHash(tx);\n\tfor (const field of fields) {\n\t\tconst preSign = sigHashPreSign(\n\t\t\tcurSigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tcurSigHash = sigHashPostSign(preSign, field.pubKeyEncoding, field.data);\n\t}\n\n\t// Fill intervening positions with pubkey fields\n\tfor (let i = fields.length; i < signerIndex; i++) {\n\t\tconst pubKeyField: TransactionAuthField = {\n\t\t\ttype: \"publicKey\",\n\t\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tdata: publicKeys[i]!,\n\t\t};\n\t\tfields.push(pubKeyField);\n\t\tconst preSign = sigHashPreSign(\n\t\t\tcurSigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tcurSigHash = sigHashPostSign(\n\t\t\tpreSign,\n\t\t\tpubKeyField.pubKeyEncoding,\n\t\t\tpubKeyField.data,\n\t\t);\n\t}\n\n\t// Sign at signerIndex\n\tconst preSign = sigHashPreSign(\n\t\tcurSigHash,\n\t\tAuthType.Standard,\n\t\tcondition.fee,\n\t\tcondition.nonce,\n\t);\n\tconst sigBytes = await account.sign(hexToBytes(preSign));\n\tconst nextSig = bytesToHex(sigBytes);\n\tconst nextSigHash = sigHashPostSign(\n\t\tpreSign,\n\t\tPubKeyEncoding.Compressed,\n\t\tnextSig,\n\t);\n\n\tfields.push({\n\t\ttype: \"signature\",\n\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\tdata: nextSig,\n\t});\n\tcurSigHash = nextSigHash;\n\n\tconst newCondition: MultiSigSpendingCondition = { ...condition, fields };\n\n\t// Count signatures so far\n\tconst sigCount = fields.filter((f) => f.type === \"signature\").length;\n\tlet finalCondition = newCondition;\n\n\t// Auto-finalize if enough signatures collected\n\tif (sigCount >= condition.signaturesRequired) {\n\t\tfinalCondition = finalizeMultiSigCondition(\n\t\t\tnewCondition,\n\t\t\tpublicKeys,\n\t\t\tcurSigHash,\n\t\t);\n\t}\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...tx.auth,\n\t\t\tspendingCondition: finalCondition,\n\t\t},\n\t};\n}\n\n/** Fill remaining slots with pubkey fields after all signatures are collected */\nexport function finalizeMultiSig(\n\ttx: StacksTransaction,\n\tpublicKeys: string[],\n): StacksTransaction {\n\tconst condition = tx.auth.spendingCondition as MultiSigSpendingCondition;\n\n\t// Non-sequential: no pubkey gap-filling needed\n\tif (isNonSequential(condition.hashMode)) {\n\t\treturn tx;\n\t}\n\n\tconst curSigHash = replayMultiSigSigHash(tx);\n\tconst finalCondition = finalizeMultiSigCondition(\n\t\tcondition,\n\t\tpublicKeys,\n\t\tcurSigHash,\n\t);\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...tx.auth,\n\t\t\tspendingCondition: finalCondition,\n\t\t},\n\t};\n}\n\n/** Internal: finalize remaining pubkey slots (sequential only) */\nfunction finalizeMultiSigCondition(\n\tcondition: MultiSigSpendingCondition,\n\tpublicKeys: string[],\n\tcurSigHash: string,\n): MultiSigSpendingCondition {\n\tconst fields = [...condition.fields];\n\tlet sigHash = curSigHash;\n\n\t// Fill remaining positions\n\tfor (let i = fields.length; i < publicKeys.length; i++) {\n\t\tconst pubKeyField: TransactionAuthField = {\n\t\t\ttype: \"publicKey\",\n\t\t\tpubKeyEncoding: PubKeyEncoding.Compressed,\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\tdata: publicKeys[i]!,\n\t\t};\n\t\tfields.push(pubKeyField);\n\t\tconst preSign = sigHashPreSign(\n\t\t\tsigHash,\n\t\t\tAuthType.Standard,\n\t\t\tcondition.fee,\n\t\t\tcondition.nonce,\n\t\t);\n\t\tsigHash = sigHashPostSign(\n\t\t\tpreSign,\n\t\t\tpubKeyField.pubKeyEncoding,\n\t\t\tpubKeyField.data,\n\t\t);\n\t}\n\n\treturn { ...condition, fields };\n}\n\n/** Combine independently-signed non-sequential multi-sig transactions */\nexport function combineMultiSigSignatures(\n\tbaseTx: StacksTransaction,\n\tsignedTxs: StacksTransaction[],\n): StacksTransaction {\n\tconst condition = baseTx.auth.spendingCondition as MultiSigSpendingCondition;\n\n\tif (!isNonSequential(condition.hashMode)) {\n\t\tthrow new Error(\n\t\t\t\"combineMultiSigSignatures only works with non-sequential hash modes (SIP-027)\",\n\t\t);\n\t}\n\n\t// Collect all signature fields from each signed tx\n\tconst seenSigs = new Set<string>();\n\tconst signatures: TransactionAuthField[] = [];\n\n\tfor (const stx of signedTxs) {\n\t\tconst stxCondition = stx.auth\n\t\t\t.spendingCondition as MultiSigSpendingCondition;\n\t\tfor (const field of stxCondition.fields) {\n\t\t\tif (field.type === \"signature\" && !seenSigs.has(field.data)) {\n\t\t\t\tseenSigs.add(field.data);\n\t\t\t\tsignatures.push(field);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (signatures.length === 0) {\n\t\tthrow new Error(\"No signatures found in the provided transactions\");\n\t}\n\n\tconst newCondition: MultiSigSpendingCondition = {\n\t\t...condition,\n\t\tfields: signatures,\n\t};\n\n\treturn {\n\t\t...baseTx,\n\t\tauth: { ...baseTx.auth, spendingCondition: newCondition },\n\t};\n}\n",
12
+ "import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, hexToBytes } from \"./encoding.ts\";\n\nconst C32 = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\nconst HEX = \"0123456789abcdef\";\n\nfunction c32normalize(input: string): string {\n\treturn input.toUpperCase().replace(/O/g, \"0\").replace(/L|I/g, \"1\");\n}\n\nfunction c32encode(inputHex: string): string {\n\tlet hex = inputHex;\n\tif (hex.length % 2 !== 0) hex = `0${hex}`;\n\thex = hex.toLowerCase();\n\n\tconst res: string[] = [];\n\tlet carry = 0;\n\tfor (let i = hex.length - 1; i >= 0; i--) {\n\t\tif (carry < 4) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\tconst currentCode = HEX.indexOf(hex[i]!) >> carry;\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\tconst nextCode = i !== 0 ? HEX.indexOf(hex[i - 1]!) : 0;\n\t\t\tconst nextBits = 1 + carry;\n\t\t\tconst nextLowBits = (nextCode % (1 << nextBits)) << (5 - nextBits);\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\tres.unshift(C32[currentCode + nextLowBits]!);\n\t\t\tcarry = nextBits;\n\t\t} else {\n\t\t\tcarry = 0;\n\t\t}\n\t}\n\n\t// Strip leading c32 zeros\n\tlet leadingZeros = 0;\n\twhile (leadingZeros < res.length && res[leadingZeros] === \"0\") leadingZeros++;\n\tconst stripped = res.slice(leadingZeros);\n\n\t// Preserve leading zero bytes from hex\n\tconst bytes = hexToBytes(hex);\n\tlet zeroBytesCount = 0;\n\twhile (zeroBytesCount < bytes.length && bytes[zeroBytesCount] === 0)\n\t\tzeroBytesCount++;\n\tconst prefix = Array(zeroBytesCount).fill(C32[0]) as string[];\n\n\treturn [...prefix, ...stripped].join(\"\");\n}\n\nfunction c32decode(c32input: string): string {\n\tconst input = c32normalize(c32input);\n\tif (!input.match(`^[${C32}]*$`)) throw new Error(\"Not a c32-encoded string\");\n\n\tconst zeroPrefix = input.match(`^${C32[0]}*`);\n\tconst numLeadingZeroBytes = zeroPrefix ? zeroPrefix[0]?.length : 0;\n\n\tconst res: string[] = [];\n\tlet carry = 0;\n\tlet carryBits = 0;\n\tfor (let i = input.length - 1; i >= 0; i--) {\n\t\tif (carryBits === 4) {\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\t\tres.unshift(HEX[carry]!);\n\t\t\tcarryBits = 0;\n\t\t\tcarry = 0;\n\t\t}\n\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\tconst currentValue = (C32.indexOf(input[i]!) << carryBits) + carry;\n\t\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\t\tres.unshift(HEX[currentValue % 16]!);\n\t\tcarryBits += 1;\n\t\tcarry = currentValue >> 4;\n\t\tif (carry > 1 << carryBits) throw new Error(\"Panic error in c32 decoding\");\n\t}\n\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\tres.unshift(HEX[carry]!);\n\n\tif (res.length % 2 === 1) res.unshift(\"0\");\n\n\t// Strip leading hex zeros\n\tlet hexLeadingZeros = 0;\n\twhile (hexLeadingZeros < res.length && res[hexLeadingZeros] === \"0\")\n\t\thexLeadingZeros++;\n\tlet hexStr = res.slice(hexLeadingZeros - (hexLeadingZeros % 2)).join(\"\");\n\n\tfor (let i = 0; i < numLeadingZeroBytes; i++) hexStr = `00${hexStr}`;\n\n\treturn hexStr;\n}\n\nfunction c32checksum(dataHex: string): string {\n\treturn bytesToHex(sha256(sha256(hexToBytes(dataHex))).slice(0, 4));\n}\n\nfunction c32checkEncode(version: number, data: string): string {\n\tif (version < 0 || version >= 32)\n\t\tthrow new Error(\"Invalid version (must be between 0 and 31)\");\n\tif (!data.match(/^[0-9a-fA-F]*$/))\n\t\tthrow new Error(\"Invalid data (not a hex string)\");\n\n\tlet d = data.toLowerCase();\n\tif (d.length % 2 !== 0) d = `0${d}`;\n\n\tlet versionHex = version.toString(16);\n\tif (versionHex.length === 1) versionHex = `0${versionHex}`;\n\n\tconst checksumHex = c32checksum(`${versionHex}${d}`);\n\treturn `${C32[version]}${c32encode(`${d}${checksumHex}`)}`;\n}\n\nfunction c32checkDecode(c32data: string): [number, string] {\n\tconst normalized = c32normalize(c32data);\n\tconst dataHex = c32decode(normalized.slice(1));\n\t// biome-ignore lint/style/noNonNullAssertion: bit-encoding routine where index is provably bounded by surrounding loop/length checks\n\tconst version = C32.indexOf(normalized[0]!);\n\tconst checksum = dataHex.slice(-8);\n\n\tlet versionHex = version.toString(16);\n\tif (versionHex.length === 1) versionHex = `0${versionHex}`;\n\n\tif (\n\t\tc32checksum(`${versionHex}${dataHex.substring(0, dataHex.length - 8)}`) !==\n\t\tchecksum\n\t) {\n\t\tthrow new Error(\"Invalid c32check string: checksum mismatch\");\n\t}\n\n\treturn [version, dataHex.substring(0, dataHex.length - 8)];\n}\n\nexport function c32address(version: number, hash160hex: string): string {\n\tif (!hash160hex.match(/^[0-9a-fA-F]{40}$/)) {\n\t\tthrow new Error(\"Invalid argument: not a hash160 hex string\");\n\t}\n\treturn `S${c32checkEncode(version, hash160hex)}`;\n}\n\nexport function c32addressDecode(c32addr: string): [number, string] {\n\tif (c32addr.length <= 5)\n\t\tthrow new Error(\"Invalid c32 address: invalid length\");\n\tif (c32addr[0] !== \"S\")\n\t\tthrow new Error('Invalid c32 address: must start with \"S\"');\n\treturn c32checkDecode(c32addr.slice(1));\n}\n",
13
+ "export type ClarityType =\n\t| \"int\"\n\t| \"uint\"\n\t| \"buffer\"\n\t| \"true\"\n\t| \"false\"\n\t| \"address\"\n\t| \"contract\"\n\t| \"ok\"\n\t| \"err\"\n\t| \"none\"\n\t| \"some\"\n\t| \"list\"\n\t| \"tuple\"\n\t| \"ascii\"\n\t| \"utf8\";\n\n/** Wire type IDs matching the Stacks binary format (SIP-005) */\nexport const ClarityWireType = {\n\tint: 0x00,\n\tuint: 0x01,\n\tbuffer: 0x02,\n\ttrue: 0x03,\n\tfalse: 0x04,\n\taddress: 0x05,\n\tcontract: 0x06,\n\tok: 0x07,\n\terr: 0x08,\n\tnone: 0x09,\n\tsome: 0x0a,\n\tlist: 0x0b,\n\ttuple: 0x0c,\n\tascii: 0x0d,\n\tutf8: 0x0e,\n} as const satisfies Record<ClarityType, number>;\n\n/** Reverse lookup: wire byte → ClarityType string */\nconst wireTypeToClarity = Object.fromEntries(\n\tObject.entries(ClarityWireType).map(([k, v]) => [v, k]),\n) as Record<number, ClarityType>;\n\nexport function clarityTypeFromByte(byte: number): ClarityType {\n\tconst type = wireTypeToClarity[byte];\n\tif (!type) throw new Error(`Unknown clarity wire type: ${byte}`);\n\treturn type;\n}\n\n// CV types\n\nexport type IntCV = { readonly type: \"int\"; readonly value: bigint };\nexport type UIntCV = { readonly type: \"uint\"; readonly value: bigint };\nexport type BooleanCV = TrueCV | FalseCV;\nexport type TrueCV = { readonly type: \"true\" };\nexport type FalseCV = { readonly type: \"false\" };\nexport type BufferCV = { readonly type: \"buffer\"; readonly value: string }; // hex\nexport type NoneCV = { readonly type: \"none\" };\nexport type SomeCV = {\n\treadonly type: \"some\";\n\treadonly value: ClarityValue;\n};\nexport type OptionalCV = NoneCV | SomeCV;\nexport type ResponseOkCV = {\n\treadonly type: \"ok\";\n\treadonly value: ClarityValue;\n};\nexport type ResponseErrorCV = {\n\treadonly type: \"err\";\n\treadonly value: ClarityValue;\n};\nexport type ResponseCV = ResponseOkCV | ResponseErrorCV;\nexport type StandardPrincipalCV = {\n\treadonly type: \"address\";\n\treadonly value: string;\n};\nexport type ContractPrincipalCV = {\n\treadonly type: \"contract\";\n\treadonly value: string; // \"address.name\"\n};\nexport type PrincipalCV = StandardPrincipalCV | ContractPrincipalCV;\nexport type ListCV = {\n\ttype: \"list\";\n\tvalue: ClarityValue[];\n};\nexport type TupleData = {\n\t[key: string]: ClarityValue;\n};\nexport type TupleCV = {\n\ttype: \"tuple\";\n\tvalue: TupleData;\n};\nexport type StringAsciiCV = {\n\treadonly type: \"ascii\";\n\treadonly value: string;\n};\nexport type StringUtf8CV = {\n\treadonly type: \"utf8\";\n\treadonly value: string;\n};\n\nexport type ClarityValue =\n\t| IntCV\n\t| UIntCV\n\t| BooleanCV\n\t| BufferCV\n\t| NoneCV\n\t| SomeCV\n\t| ResponseOkCV\n\t| ResponseErrorCV\n\t| StandardPrincipalCV\n\t| ContractPrincipalCV\n\t| ListCV\n\t| TupleCV\n\t| StringAsciiCV\n\t| StringUtf8CV;\n",
14
+ "import { c32addressDecode } from \"../utils/c32.ts\";\nimport {\n\tasciiToBytes,\n\tbigIntToBytes,\n\tbytesToHex,\n\tconcatBytes,\n\thexToBytes,\n\tintToHex,\n\ttoTwos,\n\tutf8ToBytes,\n\twriteUInt32BE,\n} from \"../utils/encoding.ts\";\nimport {\n\ttype ClarityType,\n\ttype ClarityValue,\n\tClarityWireType,\n} from \"./types.ts\";\n\nconst CLARITY_INT_SIZE = 128n;\nconst CLARITY_INT_BYTE_SIZE = 16;\n\nfunction typeIdByte(type: ClarityType): number {\n\treturn ClarityWireType[type];\n}\n\nfunction withTypeId(type: ClarityType, bytes: Uint8Array): Uint8Array {\n\treturn concatBytes(new Uint8Array([typeIdByte(type)]), bytes);\n}\n\nfunction serializeAddress(c32Address: string): Uint8Array {\n\tconst [version, hash160] = c32addressDecode(c32Address);\n\treturn concatBytes(new Uint8Array([version]), hexToBytes(hash160));\n}\n\nfunction serializeLPString(str: string, prefixBytes = 1): Uint8Array {\n\tconst content = utf8ToBytes(str);\n\tconst lengthPrefix = hexToBytes(intToHex(content.byteLength, prefixBytes));\n\treturn concatBytes(lengthPrefix, content);\n}\n\nexport function serializeCVBytes(value: ClarityValue): Uint8Array {\n\tswitch (value.type) {\n\t\tcase \"true\":\n\t\tcase \"false\":\n\t\t\treturn new Uint8Array([typeIdByte(value.type)]);\n\n\t\tcase \"int\": {\n\t\t\tconst bytes = bigIntToBytes(\n\t\t\t\ttoTwos(BigInt(value.value), CLARITY_INT_SIZE),\n\t\t\t\tCLARITY_INT_BYTE_SIZE,\n\t\t\t);\n\t\t\treturn withTypeId(value.type, bytes);\n\t\t}\n\n\t\tcase \"uint\": {\n\t\t\tconst bytes = bigIntToBytes(BigInt(value.value), CLARITY_INT_BYTE_SIZE);\n\t\t\treturn withTypeId(value.type, bytes);\n\t\t}\n\n\t\tcase \"buffer\": {\n\t\t\tconst bufBytes = hexToBytes(value.value);\n\t\t\treturn withTypeId(\n\t\t\t\tvalue.type,\n\t\t\t\tconcatBytes(writeUInt32BE(bufBytes.length), bufBytes),\n\t\t\t);\n\t\t}\n\n\t\tcase \"none\":\n\t\t\treturn new Uint8Array([typeIdByte(value.type)]);\n\n\t\tcase \"some\":\n\t\t\treturn withTypeId(value.type, serializeCVBytes(value.value));\n\n\t\tcase \"ok\":\n\t\tcase \"err\":\n\t\t\treturn withTypeId(value.type, serializeCVBytes(value.value));\n\n\t\tcase \"address\":\n\t\t\treturn withTypeId(value.type, serializeAddress(value.value));\n\n\t\tcase \"contract\": {\n\t\t\tconst [addr, name] = value.value.split(\".\");\n\t\t\tif (!addr || !name)\n\t\t\t\tthrow new Error(`Invalid contract principal: ${value.value}`);\n\t\t\treturn withTypeId(\n\t\t\t\tvalue.type,\n\t\t\t\tconcatBytes(serializeAddress(addr), serializeLPString(name)),\n\t\t\t);\n\t\t}\n\n\t\tcase \"list\": {\n\t\t\tconst parts: Uint8Array[] = [writeUInt32BE(value.value.length)];\n\t\t\tfor (const item of value.value) {\n\t\t\t\tparts.push(serializeCVBytes(item));\n\t\t\t}\n\t\t\treturn withTypeId(value.type, concatBytes(...parts));\n\t\t}\n\n\t\tcase \"tuple\": {\n\t\t\t// Clarity orders tuple fields as a BTreeMap over the raw name bytes.\n\t\t\t// Code-unit comparison equals byte order for the ASCII name grammar;\n\t\t\t// localeCompare does not, and would change the SIP-018 hash.\n\t\t\tconst keys = Object.keys(value.value).sort((a, b) =>\n\t\t\t\ta < b ? -1 : a > b ? 1 : 0,\n\t\t\t);\n\t\t\tconst parts: Uint8Array[] = [writeUInt32BE(keys.length)];\n\t\t\tfor (const key of keys) {\n\t\t\t\tparts.push(serializeLPString(key));\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: value is non-null after preceding check or by construction; TS narrowing limitation\n\t\t\t\tparts.push(serializeCVBytes(value.value[key]!));\n\t\t\t}\n\t\t\treturn withTypeId(value.type, concatBytes(...parts));\n\t\t}\n\n\t\tcase \"ascii\": {\n\t\t\tconst strBytes = asciiToBytes(value.value);\n\t\t\treturn withTypeId(\n\t\t\t\tvalue.type,\n\t\t\t\tconcatBytes(writeUInt32BE(strBytes.length), strBytes),\n\t\t\t);\n\t\t}\n\n\t\tcase \"utf8\": {\n\t\t\tconst strBytes = utf8ToBytes(value.value);\n\t\t\treturn withTypeId(\n\t\t\t\tvalue.type,\n\t\t\t\tconcatBytes(writeUInt32BE(strBytes.length), strBytes),\n\t\t\t);\n\t\t}\n\n\t\tdefault:\n\t\t\tthrow new Error(\"Cannot serialize unknown clarity type\");\n\t}\n}\n\nexport function serializeCV(value: ClarityValue): string {\n\treturn bytesToHex(serializeCVBytes(value));\n}\n",
15
+ "import { serializeCVBytes } from \"../../clarity/serialize.ts\";\nimport { c32addressDecode } from \"../../utils/c32.ts\";\nimport {\n\tasciiToBytes,\n\tbytesToHex,\n\tconcatBytes,\n\thexToBytes,\n\tintToBytes,\n\tintToHex,\n\tutf8ToBytes,\n\twriteUInt8,\n\twriteUInt16BE,\n\twriteUInt32BE,\n} from \"../../utils/encoding.ts\";\nimport {\n\ttype AssetInfoWire,\n\tAssetType,\n\tAuthType,\n\ttype Authorization,\n\ttype CoinbasePayload,\n\ttype CoinbaseToAltRecipientPayload,\n\tMEMO_MAX_LENGTH_BYTES,\n\ttype MultiSigSpendingCondition,\n\ttype NakamotoCoinbasePayload,\n\tPayloadType,\n\ttype PoisonMicroblockPayload,\n\tPostConditionPrincipalId,\n\ttype PostConditionPrincipalWire,\n\ttype PostConditionWire,\n\ttype SingleSigSpendingCondition,\n\ttype SpendingCondition,\n\ttype StacksTransaction,\n\ttype TenureChangePayload as TenureChangePayloadType,\n\ttype TransactionAuthField,\n\ttype TransactionPayload,\n} from \"../types.ts\";\n\n// Address serialization: version (1 byte) + hash160 (20 bytes)\nfunction serializeAddress(c32Address: string): Uint8Array {\n\tconst [version, hash160] = c32addressDecode(c32Address);\n\treturn concatBytes(new Uint8Array([version]), hexToBytes(hash160));\n}\n\n// LP string: length prefix (n bytes) + content bytes\nfunction serializeLPString(str: string, prefixBytes = 1): Uint8Array {\n\tconst content = utf8ToBytes(str);\n\tconst prefix = hexToBytes(intToHex(content.byteLength, prefixBytes));\n\treturn concatBytes(prefix, content);\n}\n\n// LP string for code body (4-byte prefix)\nfunction serializeLPStringLong(str: string): Uint8Array {\n\treturn serializeLPString(str, 4);\n}\n\n// Memo: flat 34-byte field (no length prefix) per SIP-005\nfunction serializeMemo(memo: string): Uint8Array {\n\tconst content = asciiToBytes(memo);\n\tconst padded = new Uint8Array(MEMO_MAX_LENGTH_BYTES);\n\tpadded.set(content.slice(0, MEMO_MAX_LENGTH_BYTES));\n\treturn padded;\n}\n\nfunction serializeSpendingCondition(condition: SpendingCondition): Uint8Array {\n\tconst parts: Uint8Array[] = [\n\t\twriteUInt8(condition.hashMode),\n\t\thexToBytes(condition.signer), // 20 bytes\n\t\tintToBytes(condition.nonce, 8),\n\t\tintToBytes(condition.fee, 8),\n\t];\n\n\tif (\"signature\" in condition) {\n\t\t// Single sig\n\t\tconst sc = condition as SingleSigSpendingCondition;\n\t\tparts.push(writeUInt8(sc.keyEncoding));\n\t\tparts.push(hexToBytes(sc.signature)); // 65 bytes\n\t} else {\n\t\t// Multi sig\n\t\tconst mc = condition as MultiSigSpendingCondition;\n\t\t// Fields as LP list\n\t\tparts.push(writeUInt32BE(mc.fields.length));\n\t\tfor (const field of mc.fields) {\n\t\t\tparts.push(serializeAuthField(field));\n\t\t}\n\t\tparts.push(writeUInt16BE(mc.signaturesRequired));\n\t}\n\n\treturn concatBytes(...parts);\n}\n\nfunction serializeAuthField(field: TransactionAuthField): Uint8Array {\n\tif (field.type === \"publicKey\") {\n\t\tconst typeId = field.pubKeyEncoding === 0x00 ? 0x00 : 0x01;\n\t\treturn concatBytes(writeUInt8(typeId), hexToBytes(field.data));\n\t}\n\tconst typeId = field.pubKeyEncoding === 0x00 ? 0x02 : 0x03;\n\treturn concatBytes(writeUInt8(typeId), hexToBytes(field.data));\n}\n\nfunction serializeAuthorization(auth: Authorization): Uint8Array {\n\tconst parts: Uint8Array[] = [writeUInt8(auth.authType)];\n\tparts.push(serializeSpendingCondition(auth.spendingCondition));\n\tif (auth.authType === AuthType.Sponsored) {\n\t\tparts.push(serializeSpendingCondition(auth.sponsorSpendingCondition));\n\t}\n\treturn concatBytes(...parts);\n}\n\nfunction serializePrincipal(principal: PostConditionPrincipalWire): Uint8Array {\n\tswitch (principal.type) {\n\t\tcase \"origin\":\n\t\t\treturn writeUInt8(PostConditionPrincipalId.Origin);\n\t\tcase \"standard\":\n\t\t\treturn concatBytes(\n\t\t\t\twriteUInt8(PostConditionPrincipalId.Standard),\n\t\t\t\tserializeAddress(principal.address),\n\t\t\t);\n\t\tcase \"contract\":\n\t\t\treturn concatBytes(\n\t\t\t\twriteUInt8(PostConditionPrincipalId.Contract),\n\t\t\t\tserializeAddress(principal.address),\n\t\t\t\tserializeLPString(principal.contractName),\n\t\t\t);\n\t}\n}\n\nfunction serializeAssetInfo(asset: AssetInfoWire): Uint8Array {\n\treturn concatBytes(\n\t\tserializeAddress(asset.address),\n\t\tserializeLPString(asset.contractName),\n\t\tserializeLPString(asset.assetName),\n\t);\n}\n\nexport function serializePostConditionWire(pc: PostConditionWire): Uint8Array {\n\t// Wire order: asset_type first, then principal (per SIP-005)\n\tconst parts: Uint8Array[] = [];\n\n\tswitch (pc.type) {\n\t\tcase \"stx\":\n\t\t\tparts.push(writeUInt8(AssetType.STX));\n\t\t\tparts.push(serializePrincipal(pc.principal));\n\t\t\tparts.push(writeUInt8(pc.conditionCode));\n\t\t\tparts.push(intToBytes(pc.amount, 8));\n\t\t\tbreak;\n\t\tcase \"ft\":\n\t\t\tparts.push(writeUInt8(AssetType.Fungible));\n\t\t\tparts.push(serializePrincipal(pc.principal));\n\t\t\tparts.push(serializeAssetInfo(pc.asset));\n\t\t\tparts.push(writeUInt8(pc.conditionCode));\n\t\t\tparts.push(intToBytes(pc.amount, 8));\n\t\t\tbreak;\n\t\tcase \"nft\":\n\t\t\tparts.push(writeUInt8(AssetType.NonFungible));\n\t\t\tparts.push(serializePrincipal(pc.principal));\n\t\t\tparts.push(serializeAssetInfo(pc.asset));\n\t\t\tparts.push(serializeCVBytes(pc.assetId));\n\t\t\tparts.push(writeUInt8(pc.conditionCode));\n\t\t\tbreak;\n\t\tcase \"staking\":\n\t\t\t// SIP-045: same body as STX (fungible condition code + amount)\n\t\t\tparts.push(writeUInt8(AssetType.Staking));\n\t\t\tparts.push(serializePrincipal(pc.principal));\n\t\t\tparts.push(writeUInt8(pc.conditionCode));\n\t\t\tparts.push(intToBytes(pc.amount, 8));\n\t\t\tbreak;\n\t\tcase \"pox\":\n\t\t\t// SIP-045: PoX condition code only, no amount\n\t\t\tparts.push(writeUInt8(AssetType.Pox));\n\t\t\tparts.push(serializePrincipal(pc.principal));\n\t\t\tparts.push(writeUInt8(pc.conditionCode));\n\t\t\tbreak;\n\t}\n\n\treturn concatBytes(...parts);\n}\n\nfunction serializePostConditions(pcs: PostConditionWire[]): Uint8Array {\n\tconst parts: Uint8Array[] = [writeUInt32BE(pcs.length)];\n\tfor (const pc of pcs) parts.push(serializePostConditionWire(pc));\n\treturn concatBytes(...parts);\n}\n\nexport function serializePayload(payload: TransactionPayload): Uint8Array {\n\tconst parts: Uint8Array[] = [writeUInt8(payload.payloadType)];\n\n\tswitch (payload.payloadType) {\n\t\tcase PayloadType.TokenTransfer:\n\t\t\tparts.push(serializeCVBytes(payload.recipient));\n\t\t\tparts.push(intToBytes(payload.amount, 8));\n\t\t\tparts.push(serializeMemo(payload.memo));\n\t\t\tbreak;\n\n\t\tcase PayloadType.ContractCall:\n\t\t\tparts.push(serializeAddress(payload.contractAddress));\n\t\t\tparts.push(serializeLPString(payload.contractName));\n\t\t\tparts.push(serializeLPString(payload.functionName));\n\t\t\tparts.push(writeUInt32BE(payload.functionArgs.length));\n\t\t\tfor (const arg of payload.functionArgs) {\n\t\t\t\tparts.push(serializeCVBytes(arg));\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase PayloadType.SmartContract:\n\t\t\tparts.push(serializeLPString(payload.contractName));\n\t\t\tparts.push(serializeLPStringLong(payload.codeBody));\n\t\t\tbreak;\n\n\t\tcase PayloadType.VersionedSmartContract:\n\t\t\tparts.push(writeUInt8(payload.clarityVersion ?? 2));\n\t\t\tparts.push(serializeLPString(payload.contractName));\n\t\t\tparts.push(serializeLPStringLong(payload.codeBody));\n\t\t\tbreak;\n\n\t\tcase PayloadType.Coinbase:\n\t\t\tparts.push(hexToBytes((payload as CoinbasePayload).coinbaseBuffer));\n\t\t\tbreak;\n\n\t\tcase PayloadType.CoinbaseToAltRecipient: {\n\t\t\tconst cbAlt = payload as CoinbaseToAltRecipientPayload;\n\t\t\tparts.push(hexToBytes(cbAlt.coinbaseBuffer));\n\t\t\tparts.push(serializeCVBytes(cbAlt.recipient));\n\t\t\tbreak;\n\t\t}\n\n\t\tcase PayloadType.PoisonMicroblock: {\n\t\t\tconst pm = payload as PoisonMicroblockPayload;\n\t\t\tparts.push(hexToBytes(pm.header1));\n\t\t\tparts.push(hexToBytes(pm.header2));\n\t\t\tbreak;\n\t\t}\n\n\t\tcase PayloadType.TenureChange: {\n\t\t\tconst tc = payload as TenureChangePayloadType;\n\t\t\tparts.push(hexToBytes(tc.tenureConsensusHash));\n\t\t\tparts.push(hexToBytes(tc.prevTenureConsensusHash));\n\t\t\tparts.push(hexToBytes(tc.burnViewConsensusHash));\n\t\t\tparts.push(hexToBytes(tc.previousTenureEnd));\n\t\t\tparts.push(writeUInt32BE(tc.previousTenureBlocks));\n\t\t\tparts.push(writeUInt8(tc.cause));\n\t\t\tparts.push(hexToBytes(tc.pubkeyHash));\n\t\t\tbreak;\n\t\t}\n\n\t\tcase PayloadType.NakamotoCoinbase: {\n\t\t\tconst nc = payload as NakamotoCoinbasePayload;\n\t\t\tparts.push(hexToBytes(nc.coinbaseBuffer));\n\t\t\tif (nc.recipient) {\n\t\t\t\tparts.push(serializeCVBytes({ type: \"some\", value: nc.recipient }));\n\t\t\t} else {\n\t\t\t\tparts.push(serializeCVBytes({ type: \"none\" }));\n\t\t\t}\n\t\t\tparts.push(hexToBytes(nc.vrfProof));\n\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn concatBytes(...parts);\n}\n\n// Memoization cache: transactions are immutable in practice (fields are set\n// once during build/signing), so the serialized bytes for a given transaction\n// object never change. The signing flow serializes the same object several\n// times (txid, sighash, sponsor sighash); caching avoids that redundant work.\n// Any in-place mutation MUST call clearTxCache — see setUnsignedFee.\nconst _txCache = new WeakMap<StacksTransaction, Uint8Array>();\n\n/** Invalidate the memoized serialization of a mutated transaction */\nexport function clearTxCache(tx: StacksTransaction): void {\n\t_txCache.delete(tx);\n}\n\nexport function serializeTransaction(tx: StacksTransaction): Uint8Array {\n\tconst cached = _txCache.get(tx);\n\tif (cached) return cached;\n\tconst bytes = concatBytes(\n\t\twriteUInt8(tx.version),\n\t\twriteUInt32BE(tx.chainId),\n\t\tserializeAuthorization(tx.auth),\n\t\twriteUInt8(tx.anchorMode),\n\t\twriteUInt8(tx.postConditionMode),\n\t\tserializePostConditions(tx.postConditions),\n\t\tserializePayload(tx.payload),\n\t);\n\t_txCache.set(tx, bytes);\n\treturn bytes;\n}\n\nexport function serializeTransactionHex(tx: StacksTransaction): string {\n\treturn bytesToHex(serializeTransaction(tx));\n}\n\n/** Serialize a transaction, returning the wire bytes plus the out-of-band\n * `_multisig` metadata so callers can preserve it across a round-trip\n * (the wire format itself does not carry it). */\nexport function serializeTransactionWithMeta(tx: StacksTransaction): {\n\tbytes: Uint8Array;\n\t_multisig?: { publicKeys: string[] };\n} {\n\treturn { bytes: serializeTransaction(tx), _multisig: tx._multisig };\n}\n",
16
+ "import type { CustomAccount, LocalAccount } from \"../accounts/types.ts\";\nimport { bytesToHex, hexToBytes } from \"../utils/encoding.ts\";\nimport { txidFromBytes } from \"../utils/hash.ts\";\nimport {\n\tintoInitialSighashAuth,\n\tnextSignature,\n\tsigHashPostSign,\n\tsigHashPreSign,\n} from \"./authorization.ts\";\nimport { replayMultiSigSigHash } from \"./multisig.ts\";\nimport {\n\tAuthType,\n\ttype SingleSigSpendingCondition,\n\ttype SponsoredAuthorization,\n\ttype StacksTransaction,\n} from \"./types.ts\";\nimport { serializeTransaction } from \"./wire/serialize.ts\";\n\nfunction txid(tx: StacksTransaction): string {\n\treturn txidFromBytes(serializeTransaction(tx));\n}\n\n/** Compute the initial sighash for a transaction */\nexport function signBegin(tx: StacksTransaction): string {\n\tconst cleared: StacksTransaction = {\n\t\t...tx,\n\t\tauth: intoInitialSighashAuth(tx.auth),\n\t};\n\treturn txid(cleared);\n}\n\n/** Sign a single-sig transaction with a private key, returning the signed transaction */\nexport function signTransaction(\n\ttx: StacksTransaction,\n\tprivateKey: string,\n): StacksTransaction {\n\tconst sigHash = signBegin(tx);\n\tconst condition = tx.auth.spendingCondition as SingleSigSpendingCondition;\n\n\t// Origin always signs with AuthType.Standard (even for sponsored txs)\n\tconst { nextSig } = nextSignature(\n\t\tsigHash,\n\t\tAuthType.Standard,\n\t\tcondition.fee,\n\t\tcondition.nonce,\n\t\tprivateKey,\n\t);\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...tx.auth,\n\t\t\tspendingCondition: {\n\t\t\t\t...condition,\n\t\t\t\tsignature: nextSig,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** Sign a single-sig transaction using an account (LocalAccount or CustomAccount) */\nexport async function signTransactionWithAccount(\n\ttx: StacksTransaction,\n\taccount: LocalAccount | CustomAccount,\n): Promise<StacksTransaction> {\n\tconst sigHash = signBegin(tx);\n\tconst condition = tx.auth.spendingCondition as SingleSigSpendingCondition;\n\n\t// Origin always signs with AuthType.Standard (even for sponsored txs)\n\tconst sigHashPre = sigHashPreSign(\n\t\tsigHash,\n\t\tAuthType.Standard,\n\t\tcondition.fee,\n\t\tcondition.nonce,\n\t);\n\n\t// account.sign returns 65-byte VRS (recovery + r + s)\n\tconst sigBytes = await account.sign(hexToBytes(sigHashPre));\n\tconst nextSig = bytesToHex(sigBytes);\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...tx.auth,\n\t\t\tspendingCondition: {\n\t\t\t\t...condition,\n\t\t\t\tsignature: nextSig,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** Get the txid of a transaction */\nexport function getTransactionId(tx: StacksTransaction): string {\n\treturn txid(tx);\n}\n\n/** Reconstruct the sighash after origin signing (needed for sponsor signing) */\nexport function getOriginSigHash(tx: StacksTransaction): string {\n\tconst condition = tx.auth.spendingCondition;\n\n\t// Multi-sig: replay through all fields\n\tif (\"fields\" in condition) {\n\t\treturn replayMultiSigSigHash(tx);\n\t}\n\n\t// Single-sig\n\tconst initialSigHash = signBegin(tx);\n\tconst sc = condition as SingleSigSpendingCondition;\n\tconst preSign = sigHashPreSign(\n\t\tinitialSigHash,\n\t\tAuthType.Standard,\n\t\tsc.fee,\n\t\tsc.nonce,\n\t);\n\treturn sigHashPostSign(preSign, sc.keyEncoding, sc.signature);\n}\n\n/** Sign a sponsored transaction as the sponsor with a private key */\nexport function signSponsor(\n\ttx: StacksTransaction,\n\tprivateKey: string,\n): StacksTransaction {\n\tif (tx.auth.authType !== AuthType.Sponsored) {\n\t\tthrow new Error(\"Transaction must be sponsored\");\n\t}\n\tconst auth = tx.auth as SponsoredAuthorization;\n\tconst sponsorCondition =\n\t\tauth.sponsorSpendingCondition as SingleSigSpendingCondition;\n\tconst originSigHash = getOriginSigHash(tx);\n\n\tconst { nextSig } = nextSignature(\n\t\toriginSigHash,\n\t\tAuthType.Sponsored,\n\t\tsponsorCondition.fee,\n\t\tsponsorCondition.nonce,\n\t\tprivateKey,\n\t);\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...auth,\n\t\t\tsponsorSpendingCondition: {\n\t\t\t\t...sponsorCondition,\n\t\t\t\tsignature: nextSig,\n\t\t\t},\n\t\t},\n\t};\n}\n\n/** Sign a sponsored transaction as the sponsor using an account */\nexport async function signSponsorWithAccount(\n\ttx: StacksTransaction,\n\taccount: LocalAccount | CustomAccount,\n): Promise<StacksTransaction> {\n\tif (tx.auth.authType !== AuthType.Sponsored) {\n\t\tthrow new Error(\"Transaction must be sponsored\");\n\t}\n\tconst auth = tx.auth as SponsoredAuthorization;\n\tconst sponsorCondition =\n\t\tauth.sponsorSpendingCondition as SingleSigSpendingCondition;\n\tconst originSigHash = getOriginSigHash(tx);\n\n\tconst sigHashPre = sigHashPreSign(\n\t\toriginSigHash,\n\t\tAuthType.Sponsored,\n\t\tsponsorCondition.fee,\n\t\tsponsorCondition.nonce,\n\t);\n\n\tconst sigBytes = await account.sign(hexToBytes(sigHashPre));\n\tconst nextSig = bytesToHex(sigBytes);\n\n\treturn {\n\t\t...tx,\n\t\tauth: {\n\t\t\t...auth,\n\t\t\tsponsorSpendingCondition: {\n\t\t\t\t...sponsorCondition,\n\t\t\t\tsignature: nextSig,\n\t\t\t},\n\t\t},\n\t};\n}\n",
17
+ "import { BaseError } from \"./base.ts\";\n\nexport class TransactionError extends BaseError {\n\toverride name = \"TransactionError\";\n}\n\n/**\n * Rejection reasons a stacks-node returns from `POST /v2/transactions`.\n * Wire strings from stacks-core `MemPoolRejection::into_json`\n * (`stackslib/src/chainstate/stacks/db/blocks.rs`).\n */\nexport type TxRejectionReason =\n\t| \"Serialization\"\n\t| \"Deserialization\"\n\t| \"SignatureValidation\"\n\t| \"BadNonce\"\n\t| \"ConflictingNonceInMempool\"\n\t| \"TooMuchChaining\"\n\t| \"FeeTooLow\"\n\t| \"NotEnoughFunds\"\n\t| \"NoSuchContract\"\n\t| \"NoSuchPublicFunction\"\n\t| \"BadFunctionArgument\"\n\t| \"ContractAlreadyExists\"\n\t| \"BadTransactionVersion\"\n\t| \"TransferRecipientCannotEqualSender\"\n\t| \"TransferAmountMustBePositive\"\n\t| \"PoisonMicroblocksDoNotConflict\"\n\t| \"PoisonMicroblockHasUnknownPubKeyHash\"\n\t| \"PoisonMicroblockIsInvalid\"\n\t| \"BadAddressVersionByte\"\n\t| \"NoCoinbaseViaMempool\"\n\t| \"NoTenureChangeViaMempool\"\n\t| \"EstimatorError\"\n\t| \"TemporarilyBlacklisted\"\n\t| \"ServerFailureNoSuchChainTip\"\n\t| \"ServerFailureDatabase\"\n\t| \"ServerFailureOther\";\n\nexport class BroadcastError extends BaseError {\n\toverride name = \"BroadcastError\";\n\ttxid?: string;\n\t// `(string & {})` keeps forward-compat with reasons newer nodes may add\n\t// while preserving literal-union completions.\n\treason?: TxRejectionReason | (string & {});\n\t/** Node-provided detail; shape varies per reason (see stacks-core RPC docs). */\n\treasonData?: unknown;\n\n\tconstructor(\n\t\tmessage: string,\n\t\toptions?: {\n\t\t\tcause?: Error;\n\t\t\ttxid?: string;\n\t\t\treason?: string;\n\t\t\treasonData?: unknown;\n\t\t},\n\t) {\n\t\tsuper(message, options);\n\t\tthis.txid = options?.txid;\n\t\tthis.reason = options?.reason;\n\t\tthis.reasonData = options?.reasonData;\n\t}\n}\n\n/** The transaction was mined but its execution aborted (runtime error or failed post-condition). */\nexport class TransactionAbortedError extends BaseError {\n\toverride name = \"TransactionAbortedError\";\n\t/** The abort receipt (status, block info, raw source response). */\n\treceipt: unknown;\n\n\tconstructor(message: string, options: { receipt: unknown; cause?: Error }) {\n\t\tsuper(message, options);\n\t\tthis.receipt = options.receipt;\n\t}\n}\n\n/** The transaction left the mempool without being mined (dropped/replaced). */\nexport class TransactionDroppedError extends BaseError {\n\toverride name = \"TransactionDroppedError\";\n\ttxid: string;\n\n\tconstructor(message: string, options: { txid: string; cause?: Error }) {\n\t\tsuper(message, options);\n\t\tthis.txid = options.txid;\n\t}\n}\n\n/** waitForTransactionReceipt gave up before the tx reached the requested state. */\nexport class WaitForTransactionTimeoutError extends BaseError {\n\toverride name = \"WaitForTransactionTimeoutError\";\n\ttxid: string;\n\n\tconstructor(message: string, options: { txid: string; cause?: Error }) {\n\t\tsuper(message, options);\n\t\tthis.txid = options.txid;\n\t}\n}\n\nexport class SerializationError extends BaseError {\n\toverride name = \"SerializationError\";\n}\n\nexport class SigningError extends BaseError {\n\toverride name = \"SigningError\";\n}\n",
18
+ "import { SerializationError } from \"../errors/transaction.ts\";\nimport { bytesToHex } from \"./encoding.ts\";\n\nexport class BytesReader {\n\tprivate data: Uint8Array;\n\tpublic offset = 0;\n\n\tconstructor(data: Uint8Array) {\n\t\tthis.data = data;\n\t}\n\n\t/** Bytes left after the cursor. */\n\tremaining(): number {\n\t\treturn this.data.length - this.offset;\n\t}\n\n\tprivate ensure(length: number): void {\n\t\tif (this.offset + length > this.data.length) {\n\t\t\tthrow new SerializationError(\n\t\t\t\t`Buffer underflow: need ${length} bytes at offset ${this.offset}, have ${this.data.length}`,\n\t\t\t);\n\t\t}\n\t}\n\n\treadUInt8(): number {\n\t\tthis.ensure(1);\n\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\treturn this.data[this.offset++]!;\n\t}\n\n\treadUInt16BE(): number {\n\t\tthis.ensure(2);\n\t\tconst val =\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\t\t((this.data[this.offset]! << 8) | this.data[this.offset + 1]!) >>> 0;\n\t\tthis.offset += 2;\n\t\treturn val;\n\t}\n\n\treadUInt32BE(): number {\n\t\tthis.ensure(4);\n\t\tconst val =\n\t\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\t\t((this.data[this.offset]! << 24) |\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\t\t\t(this.data[this.offset + 1]! << 16) |\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\t\t\t(this.data[this.offset + 2]! << 8) |\n\t\t\t\t// biome-ignore lint/style/noNonNullAssertion: bounds checked by ensure()\n\t\t\t\tthis.data[this.offset + 3]!) >>>\n\t\t\t0;\n\t\tthis.offset += 4;\n\t\treturn val;\n\t}\n\n\treadBytes(length: number): Uint8Array {\n\t\tthis.ensure(length);\n\t\tconst slice = this.data.slice(this.offset, this.offset + length);\n\t\tthis.offset += length;\n\t\treturn slice;\n\t}\n\n\treadBigUInt64BE(): bigint {\n\t\tconst hex = bytesToHex(this.readBytes(8));\n\t\treturn hex.length > 0 ? BigInt(`0x${hex}`) : 0n;\n\t}\n}\n",
19
+ "// Clarity integer bounds\nexport const MAX_U128: bigint = (1n << 128n) - 1n;\nexport const MAX_I128: bigint = (1n << 127n) - 1n;\nexport const MIN_I128: bigint = -(1n << 127n);\n\n/** C32-encoded address version bytes for single-sig and multi-sig on each network. */\nexport const AddressVersion = {\n\tMainnetSingleSig: 22,\n\tMainnetMultiSig: 20,\n\tTestnetSingleSig: 26,\n\tTestnetMultiSig: 21,\n} as const;\nexport type AddressVersion =\n\t(typeof AddressVersion)[keyof typeof AddressVersion];\n\n/** Mainnet burn address (all-zero hash160). */\nexport const ZERO_ADDRESS = \"SP000000000000000000002Q6VF78\";\n/** Testnet burn address (all-zero hash160). */\nexport const TESTNET_ZERO_ADDRESS = \"ST000000000000000000002AMW42H\";\n\n/** Number of microSTX per 1 STX (10^6). */\nexport const MICROSTX_PER_STX = 1_000_000n;\n",
20
+ "import { c32address, c32addressDecode } from \"./c32.ts\";\nimport { AddressVersion } from \"./constants.ts\";\nimport { bytesToHex, hexToBytes, without0x } from \"./encoding.ts\";\nimport { hash160 } from \"./hash.ts\";\n\nexport { c32address, c32addressDecode };\n\n/**\n * Derive the single-sig Stacks address for a compressed public key.\n */\nexport function publicKeyToAddress(\n\tpublicKey: string | Uint8Array,\n\tnetwork: \"mainnet\" | \"testnet\" = \"mainnet\",\n): string {\n\tconst bytes =\n\t\ttypeof publicKey === \"string\"\n\t\t\t? hexToBytes(without0x(publicKey))\n\t\t\t: publicKey;\n\tconst version =\n\t\tnetwork === \"mainnet\"\n\t\t\t? AddressVersion.MainnetSingleSig\n\t\t\t: AddressVersion.TestnetSingleSig;\n\treturn c32address(version, bytesToHex(hash160(bytes)));\n}\n\n/** Clarity contract-name grammar: leading letter, then letters/digits/`-`/`_`.\n * Underscore is legal (SIP-002) and deployed contracts use it — matches the\n * pattern the Index API already accepts for contract ids. */\nexport const CONTRACT_NAME_REGEX: RegExp = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/;\n\nexport function validateStacksAddress(address: string): boolean {\n\ttry {\n\t\tc32addressDecode(address);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Alias for validateStacksAddress — matches future.md naming. */\nexport const isValidAddress: (address: string) => boolean =\n\tvalidateStacksAddress;\n\n/** Parse a principal into its parts, or null when malformed. The single\n * definition of \"valid principal\" for this package: exactly one optional\n * `.name` segment (never two), a c32-decodable address, and a contract name\n * matching the Clarity grammar. */\nexport function parsePrincipal(\n\tvalue: string,\n): { address: string; contractName?: string } | null {\n\tconst parts = value.split(\".\");\n\tif (parts.length > 2) return null;\n\tconst [address, contractName] = parts as [string, string | undefined];\n\tif (!validateStacksAddress(address)) return null;\n\tif (contractName === undefined) return { address };\n\tif (!CONTRACT_NAME_REGEX.test(contractName)) return null;\n\treturn { address, contractName };\n}\n\n/** Split `address.name` into its parts. Throws on anything `parsePrincipal`\n * rejects, and on a bare address with no contract name. */\nexport function parseContractId(contractId: string): [string, string] {\n\tconst parsed = parsePrincipal(contractId);\n\tif (!parsed?.contractName)\n\t\tthrow new Error(`Invalid contract identifier: ${contractId}`);\n\treturn [parsed.address, parsed.contractName];\n}\n\nexport function isClarityName(name: string): boolean {\n\tconst regex = /^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$/;\n\treturn regex.test(name) && name.length < 128;\n}\n\n/**\n * Compare two Stacks addresses for equality (case-insensitive, version-aware).\n * Throws if either address is invalid.\n */\nexport function isAddressEqual(a: string, b: string): boolean {\n\tconst [versionA, hashA] = c32addressDecode(a);\n\tconst [versionB, hashB] = c32addressDecode(b);\n\treturn versionA === versionB && hashA.toLowerCase() === hashB.toLowerCase();\n}\n\n/** Extract the version byte from a Stacks address (22, 20, 26, or 21). */\nexport function addressToVersion(address: string): number {\n\treturn c32addressDecode(address)[0];\n}\n\n/**\n * Build a contract address from deployer + contract name.\n * Validates both parts; returns `deployer.contractName`.\n */\nexport function getContractAddress(\n\tdeployer: string,\n\tcontractName: string,\n): string {\n\tif (!validateStacksAddress(deployer)) {\n\t\tthrow new Error(`Invalid deployer address: ${deployer}`);\n\t}\n\tif (!isClarityName(contractName)) {\n\t\tthrow new Error(`Invalid contract name: ${contractName}`);\n\t}\n\treturn `${deployer}.${contractName}`;\n}\n",
21
+ "import { isClarityName, parsePrincipal } from \"../utils/address.ts\";\nimport { c32address, c32addressDecode } from \"../utils/c32.ts\";\nimport {\n\ttype IntegerType,\n\tasciiToBytes,\n\tbytesToHex,\n\tbytesToTwosBigInt,\n\thexToBytes,\n\tintToBigInt,\n\tutf8ToBytes,\n} from \"../utils/encoding.ts\";\nimport { deserializeCVBytes } from \"./deserialize.ts\";\nimport { serializeCVBytes } from \"./serialize.ts\";\nimport type {\n\tBooleanCV,\n\tBufferCV,\n\tClarityValue,\n\tContractPrincipalCV,\n\tFalseCV,\n\tIntCV,\n\tListCV,\n\tNoneCV,\n\tResponseErrorCV,\n\tResponseOkCV,\n\tSomeCV,\n\tStandardPrincipalCV,\n\tStringAsciiCV,\n\tStringUtf8CV,\n\tTrueCV,\n\tTupleCV,\n\tTupleData,\n\tUIntCV,\n} from \"./types.ts\";\n\nconst MAX_U128 = BigInt(\"0xffffffffffffffffffffffffffffffff\");\nconst MIN_I128 = BigInt(\"-170141183460469231731687303715884105728\");\nconst MAX_I128 = BigInt(\"0x7fffffffffffffffffffffffffffffff\");\n\n// Primitives\n\nexport function intCV(value: IntegerType): IntCV {\n\tlet v: IntegerType = value;\n\tif (typeof v === \"string\" && v.toLowerCase().startsWith(\"0x\")) {\n\t\tv = bytesToTwosBigInt(hexToBytes(v));\n\t}\n\tif (v instanceof Uint8Array) v = bytesToTwosBigInt(v);\n\tconst n = intToBigInt(v);\n\tif (n > MAX_I128) throw new RangeError(`Int exceeds max i128: ${MAX_I128}`);\n\tif (n < MIN_I128) throw new RangeError(`Int below min i128: ${MIN_I128}`);\n\treturn { type: \"int\", value: n };\n}\n\nexport function uintCV(value: IntegerType): UIntCV {\n\tconst n = intToBigInt(value);\n\tif (n < 0n)\n\t\tthrow new RangeError(\"Cannot construct unsigned int from negative value\");\n\tif (n > MAX_U128) throw new RangeError(`UInt exceeds max u128: ${MAX_U128}`);\n\treturn { type: \"uint\", value: n };\n}\n\nexport const trueCV = (): TrueCV => ({ type: \"true\" });\nexport const falseCV = (): FalseCV => ({ type: \"false\" });\nexport const boolCV = (v: boolean): BooleanCV => (v ? trueCV() : falseCV());\n\nexport function bufferCV(buffer: Uint8Array): BufferCV {\n\tif (buffer.byteLength > 1_048_576) {\n\t\tthrow new Error(\"Buffer exceeds max size of 1MB\");\n\t}\n\treturn { type: \"buffer\", value: bytesToHex(buffer) };\n}\n\nexport function standardPrincipalCV(address: string): StandardPrincipalCV {\n\t// Validate by decoding\n\tconst [version, hash160] = c32addressDecode(address);\n\tconst normalized = c32address(version, hash160);\n\treturn { type: \"address\", value: normalized };\n}\n\nexport function contractPrincipalCV(\n\taddress: string,\n\tcontractName: string,\n): ContractPrincipalCV {\n\tconst [version, hash160] = c32addressDecode(address);\n\tconst normalized = c32address(version, hash160);\n\tif (utf8ToBytes(contractName).byteLength >= 128) {\n\t\tthrow new Error(\"Contract name must be less than 128 bytes\");\n\t}\n\treturn { type: \"contract\", value: `${normalized}.${contractName}` };\n}\n\nexport function noneCV(): NoneCV {\n\treturn { type: \"none\" };\n}\n\nexport function someCV(value: ClarityValue): SomeCV {\n\treturn { type: \"some\", value };\n}\n\nexport function responseOkCV(value: ClarityValue): ResponseOkCV {\n\treturn { type: \"ok\", value };\n}\n\nexport function responseErrorCV(value: ClarityValue): ResponseErrorCV {\n\treturn { type: \"err\", value };\n}\n\nexport function listCV(values: ClarityValue[]): ListCV {\n\treturn { type: \"list\", value: values };\n}\n\nexport function tupleCV(data: TupleData): TupleCV {\n\tfor (const key in data) {\n\t\tif (!isClarityName(key)) {\n\t\t\tthrow new Error(`\"${key}\" is not a valid Clarity name`);\n\t\t}\n\t}\n\treturn { type: \"tuple\", value: data };\n}\n\nexport function stringAsciiCV(value: string): StringAsciiCV {\n\treturn { type: \"ascii\", value };\n}\n\nexport function stringUtf8CV(value: string): StringUtf8CV {\n\treturn { type: \"utf8\", value };\n}\n\n// Cl namespace — clean API\n\nexport const Cl: {\n\treadonly int: (value: IntegerType) => IntCV;\n\treadonly uint: (value: IntegerType) => UIntCV;\n\treadonly bool: (v: boolean) => BooleanCV;\n\tprincipal(address: string): StandardPrincipalCV | ContractPrincipalCV;\n\taddress(address: string): StandardPrincipalCV | ContractPrincipalCV;\n\treadonly contractPrincipal: (\n\t\taddress: string,\n\t\tcontractName: string,\n\t) => ContractPrincipalCV;\n\treadonly standardPrincipal: (address: string) => StandardPrincipalCV;\n\treadonly buffer: (buffer: Uint8Array) => BufferCV;\n\treadonly bufferFromHex: (hex: string) => BufferCV;\n\treadonly bufferFromAscii: (ascii: string) => BufferCV;\n\treadonly bufferFromUtf8: (utf8: string) => BufferCV;\n\treadonly none: () => NoneCV;\n\treadonly some: (value: ClarityValue) => SomeCV;\n\treadonly ok: (value: ClarityValue) => ResponseOkCV;\n\treadonly error: (value: ClarityValue) => ResponseErrorCV;\n\treadonly list: (values: ClarityValue[]) => ListCV;\n\treadonly tuple: (data: TupleData) => TupleCV;\n\treadonly stringAscii: (value: string) => StringAsciiCV;\n\treadonly stringUtf8: (value: string) => StringUtf8CV;\n\tserialize(value: ClarityValue): string;\n\treadonly deserialize: (bytes: Uint8Array) => ClarityValue;\n} = {\n\tint: intCV,\n\tuint: uintCV,\n\tbool: boolCV,\n\tprincipal(address: string): StandardPrincipalCV | ContractPrincipalCV {\n\t\tconst parsed = parsePrincipal(address);\n\t\tif (!parsed) throw new Error(`Invalid principal: ${address}`);\n\t\treturn parsed.contractName\n\t\t\t? contractPrincipalCV(parsed.address, parsed.contractName)\n\t\t\t: standardPrincipalCV(parsed.address);\n\t},\n\taddress(address: string): StandardPrincipalCV | ContractPrincipalCV {\n\t\treturn Cl.principal(address);\n\t},\n\tcontractPrincipal: contractPrincipalCV,\n\tstandardPrincipal: standardPrincipalCV,\n\tbuffer: bufferCV,\n\tbufferFromHex: (hex: string): BufferCV => bufferCV(hexToBytes(hex)),\n\tbufferFromAscii: (ascii: string): BufferCV => bufferCV(asciiToBytes(ascii)),\n\tbufferFromUtf8: (utf8: string): BufferCV => bufferCV(utf8ToBytes(utf8)),\n\tnone: noneCV,\n\tsome: someCV,\n\tok: responseOkCV,\n\terror: responseErrorCV,\n\tlist: listCV,\n\ttuple: tupleCV,\n\tstringAscii: stringAsciiCV,\n\tstringUtf8: stringUtf8CV,\n\tserialize(value: ClarityValue): string {\n\t\treturn bytesToHex(serializeCVBytes(value));\n\t},\n\tdeserialize: deserializeCVBytes,\n} as const;\n",
22
+ "import { SerializationError } from \"../errors/transaction.ts\";\nimport { BytesReader } from \"../utils/bytes-reader.ts\";\nimport { c32address } from \"../utils/c32.ts\";\nimport {\n\tbytesToAscii,\n\tbytesToHex,\n\tbytesToTwosBigInt,\n\tbytesToUtf8,\n\thexToBytes,\n\twithout0x,\n} from \"../utils/encoding.ts\";\nimport { type ClarityValue, clarityTypeFromByte } from \"./types.ts\";\nimport {\n\tbufferCV,\n\tcontractPrincipalCV,\n\tfalseCV,\n\tintCV,\n\tlistCV,\n\tnoneCV,\n\tresponseErrorCV,\n\tresponseOkCV,\n\tsomeCV,\n\tstandardPrincipalCV,\n\tstringAsciiCV,\n\tstringUtf8CV,\n\ttrueCV,\n\ttupleCV,\n\tuintCV,\n} from \"./values.ts\";\n\nexport function readAddress(reader: BytesReader): string {\n\tconst version = reader.readUInt8();\n\tconst hash160 = bytesToHex(reader.readBytes(20));\n\treturn c32address(version, hash160);\n}\n\nexport function readLPString(reader: BytesReader, prefixBytes = 1): string {\n\tlet length = 0;\n\tfor (let i = 0; i < prefixBytes; i++) {\n\t\tlength = (length << 8) | reader.readUInt8();\n\t}\n\treturn bytesToUtf8(reader.readBytes(length));\n}\n\n/** Deepest nesting the deserializer follows before refusing the input. Clarity\n * itself caps value nesting far below this, so honest data never hits it;\n * hostile bytes that repeat `some`/`ok`/`list` would otherwise blow the stack. */\nexport const MAX_CV_DEPTH = 64;\n\n/** Every list item and tuple entry costs at least this many bytes on the wire\n * (a type byte, plus a name-length byte for tuple entries), so a declared\n * count that outruns the remaining bytes is corrupt before any allocation. */\nconst MIN_LIST_ITEM_BYTES = 1;\nconst MIN_TUPLE_ENTRY_BYTES = 2;\n\nfunction checkCount(reader: BytesReader, count: number, minBytes: number) {\n\tif (count * minBytes > reader.remaining()) {\n\t\tthrow new SerializationError(\n\t\t\t`Clarity value declares ${count} elements but only ${reader.remaining()} bytes remain`,\n\t\t);\n\t}\n}\n\nexport function readCV(reader: BytesReader, depth = 0): ClarityValue {\n\tif (depth > MAX_CV_DEPTH) {\n\t\tthrow new SerializationError(\n\t\t\t`Clarity value nests deeper than ${MAX_CV_DEPTH} levels`,\n\t\t);\n\t}\n\tconst typeByte = reader.readUInt8();\n\tconst type = clarityTypeFromByte(typeByte);\n\n\tswitch (type) {\n\t\tcase \"int\":\n\t\t\treturn intCV(bytesToTwosBigInt(reader.readBytes(16)));\n\n\t\tcase \"uint\":\n\t\t\treturn uintCV(reader.readBytes(16));\n\n\t\tcase \"true\":\n\t\t\treturn trueCV();\n\n\t\tcase \"false\":\n\t\t\treturn falseCV();\n\n\t\tcase \"buffer\": {\n\t\t\tconst len = reader.readUInt32BE();\n\t\t\treturn bufferCV(reader.readBytes(len));\n\t\t}\n\n\t\tcase \"none\":\n\t\t\treturn noneCV();\n\n\t\tcase \"some\":\n\t\t\treturn someCV(readCV(reader, depth + 1));\n\n\t\tcase \"ok\":\n\t\t\treturn responseOkCV(readCV(reader, depth + 1));\n\n\t\tcase \"err\":\n\t\t\treturn responseErrorCV(readCV(reader, depth + 1));\n\n\t\tcase \"address\":\n\t\t\treturn standardPrincipalCV(readAddress(reader));\n\n\t\tcase \"contract\": {\n\t\t\tconst addr = readAddress(reader);\n\t\t\tconst name = readLPString(reader);\n\t\t\treturn contractPrincipalCV(addr, name);\n\t\t}\n\n\t\tcase \"list\": {\n\t\t\tconst len = reader.readUInt32BE();\n\t\t\tcheckCount(reader, len, MIN_LIST_ITEM_BYTES);\n\t\t\tconst items: ClarityValue[] = [];\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\titems.push(readCV(reader, depth + 1));\n\t\t\t}\n\t\t\treturn listCV(items);\n\t\t}\n\n\t\tcase \"tuple\": {\n\t\t\tconst len = reader.readUInt32BE();\n\t\t\tcheckCount(reader, len, MIN_TUPLE_ENTRY_BYTES);\n\t\t\tconst data: Record<string, ClarityValue> = {};\n\t\t\tfor (let i = 0; i < len; i++) {\n\t\t\t\tconst key = readLPString(reader);\n\t\t\t\tdata[key] = readCV(reader, depth + 1);\n\t\t\t}\n\t\t\treturn tupleCV(data);\n\t\t}\n\n\t\tcase \"ascii\": {\n\t\t\tconst len = reader.readUInt32BE();\n\t\t\treturn stringAsciiCV(bytesToAscii(reader.readBytes(len)));\n\t\t}\n\n\t\tcase \"utf8\": {\n\t\t\tconst len = reader.readUInt32BE();\n\t\t\treturn stringUtf8CV(bytesToUtf8(reader.readBytes(len)));\n\t\t}\n\n\t\tdefault:\n\t\t\tthrow new SerializationError(\n\t\t\t\t`Cannot deserialize unknown clarity type: ${type}`,\n\t\t\t);\n\t}\n}\n\nexport function deserializeCVBytes<T extends ClarityValue = ClarityValue>(\n\tinput: Uint8Array | string,\n): T {\n\tconst bytes =\n\t\ttypeof input === \"string\" ? hexToBytes(without0x(input)) : input;\n\treturn readCV(new BytesReader(bytes)) as T;\n}\n\nexport function deserializeCV<T extends ClarityValue = ClarityValue>(\n\tinput: Uint8Array | string,\n): T {\n\treturn deserializeCVBytes(input);\n}\n",
23
+ "import {\n\treadAddress,\n\treadCV,\n\treadLPString,\n} from \"../../clarity/deserialize.ts\";\nimport type { ClarityValue } from \"../../clarity/types.ts\";\nimport { BytesReader } from \"../../utils/bytes-reader.ts\";\nimport {\n\tbytesToAscii,\n\tbytesToHex,\n\thexToBytes,\n\twithout0x,\n} from \"../../utils/encoding.ts\";\nimport {\n\tAddressHashMode,\n\ttype AnchorMode,\n\ttype AssetInfoWire,\n\tAssetType,\n\tAuthType,\n\ttype Authorization,\n\tCOINBASE_BYTES_LENGTH,\n\ttype ClarityVersion,\n\tMEMO_MAX_LENGTH_BYTES,\n\tMICROBLOCK_HEADER_BYTES_LENGTH,\n\tPayloadType,\n\ttype PostConditionModeWire,\n\tPostConditionPrincipalId,\n\ttype PostConditionPrincipalWire,\n\ttype PostConditionWire,\n\ttype PoxConditionCode,\n\tRECOVERABLE_ECDSA_SIG_LENGTH_BYTES,\n\ttype SpendingCondition,\n\ttype StacksTransaction,\n\ttype TenureChangeCause,\n\ttype TransactionAuthField,\n\ttype TransactionPayload,\n\tVRF_PROOF_BYTES_LENGTH,\n} from \"../types.ts\";\n\nfunction readSpendingCondition(r: BytesReader): SpendingCondition {\n\tconst hashMode = r.readUInt8();\n\tconst signer = bytesToHex(r.readBytes(20));\n\tconst nonce = r.readBigUInt64BE();\n\tconst fee = r.readBigUInt64BE();\n\n\tif (\n\t\thashMode === AddressHashMode.P2PKH ||\n\t\thashMode === AddressHashMode.P2WPKH\n\t) {\n\t\tconst keyEncoding = r.readUInt8();\n\t\tconst signature = bytesToHex(\n\t\t\tr.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES),\n\t\t);\n\t\treturn {\n\t\t\thashMode,\n\t\t\tsigner,\n\t\t\tnonce,\n\t\t\tfee,\n\t\t\tkeyEncoding,\n\t\t\tsignature,\n\t\t} as SpendingCondition;\n\t}\n\n\tconst fieldCount = r.readUInt32BE();\n\tconst fields: TransactionAuthField[] = [];\n\tfor (let i = 0; i < fieldCount; i++) {\n\t\tconst fieldType = r.readUInt8();\n\t\tif (fieldType <= 0x01) {\n\t\t\tconst keyLen = fieldType === 0x00 ? 33 : 65;\n\t\t\tfields.push({\n\t\t\t\ttype: \"publicKey\",\n\t\t\t\tpubKeyEncoding: fieldType as 0x00 | 0x01,\n\t\t\t\tdata: bytesToHex(r.readBytes(keyLen)),\n\t\t\t});\n\t\t} else {\n\t\t\tfields.push({\n\t\t\t\ttype: \"signature\",\n\t\t\t\tpubKeyEncoding: (fieldType === 0x02 ? 0x00 : 0x01) as 0x00 | 0x01,\n\t\t\t\tdata: bytesToHex(r.readBytes(RECOVERABLE_ECDSA_SIG_LENGTH_BYTES)),\n\t\t\t});\n\t\t}\n\t}\n\tconst signaturesRequired = r.readUInt16BE();\n\n\treturn {\n\t\thashMode,\n\t\tsigner,\n\t\tnonce,\n\t\tfee,\n\t\tfields,\n\t\tsignaturesRequired,\n\t} as SpendingCondition;\n}\n\nfunction readAuthorization(r: BytesReader): Authorization {\n\tconst authType = r.readUInt8();\n\tconst spendingCondition = readSpendingCondition(r);\n\n\tif (authType === AuthType.Standard) {\n\t\treturn { authType: AuthType.Standard, spendingCondition };\n\t}\n\n\tconst sponsorSpendingCondition = readSpendingCondition(r);\n\treturn {\n\t\tauthType: AuthType.Sponsored,\n\t\tspendingCondition,\n\t\tsponsorSpendingCondition,\n\t};\n}\n\nfunction readAssetInfo(r: BytesReader): AssetInfoWire {\n\treturn {\n\t\taddress: readAddress(r),\n\t\tcontractName: readLPString(r),\n\t\tassetName: readLPString(r),\n\t};\n}\n\nfunction readPostConditionPrincipal(\n\tr: BytesReader,\n): PostConditionPrincipalWire {\n\tconst type = r.readUInt8();\n\tswitch (type) {\n\t\tcase PostConditionPrincipalId.Origin:\n\t\t\treturn { type: \"origin\" };\n\t\tcase PostConditionPrincipalId.Standard:\n\t\t\treturn { type: \"standard\", address: readAddress(r) };\n\t\tcase PostConditionPrincipalId.Contract:\n\t\t\treturn {\n\t\t\t\ttype: \"contract\",\n\t\t\t\taddress: readAddress(r),\n\t\t\t\tcontractName: readLPString(r),\n\t\t\t};\n\t\tdefault:\n\t\t\t// Some legacy transactions may have unexpected principal types.\n\t\t\t// Treat as origin to allow deserialization to continue.\n\t\t\treturn { type: \"origin\" };\n\t}\n}\n\nfunction readPostCondition(r: BytesReader): PostConditionWire {\n\t// Wire order: asset_type, then principal (per SIP-005 and stacks.js)\n\tconst assetType = r.readUInt8();\n\tconst principal = readPostConditionPrincipal(r);\n\tswitch (assetType) {\n\t\tcase AssetType.STX:\n\t\t\treturn {\n\t\t\t\ttype: \"stx\",\n\t\t\t\tprincipal,\n\t\t\t\tconditionCode: r.readUInt8(),\n\t\t\t\tamount: r.readBigUInt64BE(),\n\t\t\t};\n\t\tcase AssetType.Fungible:\n\t\t\treturn {\n\t\t\t\ttype: \"ft\",\n\t\t\t\tprincipal,\n\t\t\t\tasset: readAssetInfo(r),\n\t\t\t\tconditionCode: r.readUInt8(),\n\t\t\t\tamount: r.readBigUInt64BE(),\n\t\t\t};\n\t\tcase AssetType.NonFungible:\n\t\t\treturn {\n\t\t\t\ttype: \"nft\",\n\t\t\t\tprincipal,\n\t\t\t\tasset: readAssetInfo(r),\n\t\t\t\tassetId: readCV(r),\n\t\t\t\tconditionCode: r.readUInt8(),\n\t\t\t};\n\t\tcase AssetType.Staking:\n\t\t\treturn {\n\t\t\t\ttype: \"staking\",\n\t\t\t\tprincipal,\n\t\t\t\tconditionCode: r.readUInt8(),\n\t\t\t\tamount: r.readBigUInt64BE(),\n\t\t\t};\n\t\tcase AssetType.Pox:\n\t\t\treturn {\n\t\t\t\ttype: \"pox\",\n\t\t\t\tprincipal,\n\t\t\t\tconditionCode: r.readUInt8() as PoxConditionCode,\n\t\t\t};\n\t\tdefault:\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown post-condition asset type: 0x${assetType.toString(16).padStart(2, \"0\")}`,\n\t\t\t);\n\t}\n}\n\nfunction readPostConditions(r: BytesReader): PostConditionWire[] {\n\tconst count = r.readUInt32BE();\n\tconst pcs: PostConditionWire[] = [];\n\tfor (let i = 0; i < count; i++) {\n\t\ttry {\n\t\t\tpcs.push(readPostCondition(r));\n\t\t} catch (e) {\n\t\t\tif (\n\t\t\t\te instanceof Error &&\n\t\t\t\te.message.startsWith(\"Unknown post-condition asset type:\")\n\t\t\t) {\n\t\t\t\tthrow new Error(`${e.message} (post-condition ${i + 1}/${count})`);\n\t\t\t}\n\t\t\tthrow e;\n\t\t}\n\t}\n\treturn pcs;\n}\n\nfunction readPayload(r: BytesReader): TransactionPayload {\n\tconst payloadType = r.readUInt8();\n\n\tswitch (payloadType) {\n\t\tcase PayloadType.TokenTransfer: {\n\t\t\tconst recipient = readCV(r);\n\t\t\tconst amount = r.readBigUInt64BE();\n\t\t\t// Memo is a flat 34-byte field (no length prefix) per SIP-005\n\t\t\tconst memoBytes = r.readBytes(MEMO_MAX_LENGTH_BYTES);\n\t\t\tconst memo = bytesToAscii(memoBytes).replace(/\\0+$/, \"\");\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.TokenTransfer,\n\t\t\t\trecipient,\n\t\t\t\tamount,\n\t\t\t\tmemo,\n\t\t\t};\n\t\t}\n\t\tcase PayloadType.ContractCall: {\n\t\t\tconst contractAddress = readAddress(r);\n\t\t\tconst contractName = readLPString(r);\n\t\t\tconst functionName = readLPString(r);\n\t\t\tconst numArgs = r.readUInt32BE();\n\t\t\tconst functionArgs: ClarityValue[] = [];\n\t\t\tfor (let i = 0; i < numArgs; i++) functionArgs.push(readCV(r));\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.ContractCall,\n\t\t\t\tcontractAddress,\n\t\t\t\tcontractName,\n\t\t\t\tfunctionName,\n\t\t\t\tfunctionArgs,\n\t\t\t};\n\t\t}\n\t\tcase PayloadType.SmartContract: {\n\t\t\tconst contractName = readLPString(r);\n\t\t\tconst codeBody = readLPString(r, 4);\n\t\t\treturn { payloadType: PayloadType.SmartContract, contractName, codeBody };\n\t\t}\n\t\tcase PayloadType.VersionedSmartContract: {\n\t\t\tconst clarityVersion = r.readUInt8() as ClarityVersion;\n\t\t\tconst contractName = readLPString(r);\n\t\t\tconst codeBody = readLPString(r, 4);\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.VersionedSmartContract,\n\t\t\t\tclarityVersion,\n\t\t\t\tcontractName,\n\t\t\t\tcodeBody,\n\t\t\t};\n\t\t}\n\t\tcase PayloadType.Coinbase: {\n\t\t\tconst coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));\n\t\t\treturn { payloadType: PayloadType.Coinbase, coinbaseBuffer };\n\t\t}\n\t\tcase PayloadType.CoinbaseToAltRecipient: {\n\t\t\tconst coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));\n\t\t\tconst recipient = readCV(r);\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.CoinbaseToAltRecipient,\n\t\t\t\tcoinbaseBuffer,\n\t\t\t\trecipient,\n\t\t\t};\n\t\t}\n\t\tcase PayloadType.PoisonMicroblock: {\n\t\t\tconst header1 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));\n\t\t\tconst header2 = bytesToHex(r.readBytes(MICROBLOCK_HEADER_BYTES_LENGTH));\n\t\t\treturn { payloadType: PayloadType.PoisonMicroblock, header1, header2 };\n\t\t}\n\t\tcase PayloadType.TenureChange: {\n\t\t\tconst tenureConsensusHash = bytesToHex(r.readBytes(20));\n\t\t\tconst prevTenureConsensusHash = bytesToHex(r.readBytes(20));\n\t\t\tconst burnViewConsensusHash = bytesToHex(r.readBytes(20));\n\t\t\tconst previousTenureEnd = bytesToHex(r.readBytes(32));\n\t\t\tconst previousTenureBlocks = r.readUInt32BE();\n\t\t\tconst cause = r.readUInt8() as TenureChangeCause;\n\t\t\tconst pubkeyHash = bytesToHex(r.readBytes(20));\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.TenureChange,\n\t\t\t\ttenureConsensusHash,\n\t\t\t\tprevTenureConsensusHash,\n\t\t\t\tburnViewConsensusHash,\n\t\t\t\tpreviousTenureEnd,\n\t\t\t\tpreviousTenureBlocks,\n\t\t\t\tcause,\n\t\t\t\tpubkeyHash,\n\t\t\t};\n\t\t}\n\t\tcase PayloadType.NakamotoCoinbase: {\n\t\t\tconst coinbaseBuffer = bytesToHex(r.readBytes(COINBASE_BYTES_LENGTH));\n\t\t\tconst optionalCV = readCV(r);\n\t\t\tconst recipient =\n\t\t\t\toptionalCV.type === \"none\"\n\t\t\t\t\t? null\n\t\t\t\t\t: optionalCV.type === \"some\"\n\t\t\t\t\t\t? optionalCV.value\n\t\t\t\t\t\t: optionalCV;\n\t\t\tconst vrfProof = bytesToHex(r.readBytes(VRF_PROOF_BYTES_LENGTH));\n\t\t\treturn {\n\t\t\t\tpayloadType: PayloadType.NakamotoCoinbase,\n\t\t\t\tcoinbaseBuffer,\n\t\t\t\trecipient,\n\t\t\t\tvrfProof,\n\t\t\t};\n\t\t}\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown payload type: ${payloadType}`);\n\t}\n}\n\nexport function deserializePostConditionWire(\n\tinput: string | Uint8Array,\n): PostConditionWire {\n\tconst bytes =\n\t\ttypeof input === \"string\" ? hexToBytes(without0x(input)) : input;\n\treturn readPostCondition(new BytesReader(bytes));\n}\n\nexport function deserializeTransaction(\n\tinput: string | Uint8Array,\n\tmeta?: { _multisig?: { publicKeys: string[] } },\n): StacksTransaction {\n\tconst bytes =\n\t\ttypeof input === \"string\" ? hexToBytes(without0x(input)) : input;\n\tconst r = new BytesReader(bytes);\n\n\tconst tx: StacksTransaction = {\n\t\tversion: r.readUInt8(),\n\t\tchainId: r.readUInt32BE(),\n\t\tauth: readAuthorization(r),\n\t\tanchorMode: r.readUInt8() as AnchorMode,\n\t\tpostConditionMode: r.readUInt8() as PostConditionModeWire,\n\t\tpostConditions: readPostConditions(r),\n\t\tpayload: readPayload(r),\n\t};\n\tif (meta?._multisig) {\n\t\ttx._multisig = meta._multisig;\n\t}\n\treturn tx;\n}\n",
24
+ "import { HttpRequestError } from \"../errors/http.ts\";\nimport { TimeoutError } from \"../errors/transport.ts\";\nimport type {\n\tRequestFn,\n\tRequestOptions,\n\tTransport,\n\tTransportConfig,\n} from \"./types.ts\";\n\n/** Bind a request function into a transport. The exposed `config` never\n * carries `apiKey`: the key lives in the request closure, so logging a\n * client or inspecting `client.transport.config` does not print it. */\nexport function createTransport(\n\ttype: string,\n\tconfig: TransportConfig & { request: RequestFn },\n): Transport {\n\tconst { request, apiKey: _apiKey, ...exposed } = config;\n\treturn {\n\t\ttype,\n\t\trequest,\n\t\tconfig: exposed,\n\t};\n}\n\n/** Longest response body kept on `HttpRequestError.details`. The body is\n * untrusted and lands in `error.message`, so a runaway HTML page or a\n * hostile reply must not become a multi-megabyte log line. */\nexport const MAX_ERROR_DETAILS_BYTES = 4096;\n\nfunction capDetails(body: string | undefined): string | undefined {\n\tif (body === undefined) return undefined;\n\tconst bytes = new TextEncoder().encode(body);\n\tif (bytes.length <= MAX_ERROR_DETAILS_BYTES) return body;\n\tconst head = new TextDecoder().decode(\n\t\tbytes.subarray(0, MAX_ERROR_DETAILS_BYTES),\n\t);\n\treturn `${head}... [truncated ${bytes.length - MAX_ERROR_DETAILS_BYTES} bytes]`;\n}\n\n/** 5xx and 429 are transient and worth a retry. Every other status is not. */\nfunction isRetryableStatus(status: number): boolean {\n\treturn status === 429 || status >= 500;\n}\n\n/** Retry-After above this cap falls back to the normal backoff: a node\n * asking for minutes should not stall a transport-level retry. */\nconst MAX_RETRY_AFTER_MS = 60_000;\n\n/** Parse a `Retry-After` header (delta-seconds or HTTP-date) into a delay,\n * or undefined when absent/unparseable/over the cap. */\nfunction retryAfterMs(response: Response): number | undefined {\n\tconst value = response.headers.get(\"Retry-After\");\n\tif (!value) return undefined;\n\tconst seconds = Number(value);\n\tconst ms = Number.isFinite(seconds)\n\t\t? seconds * 1000\n\t\t: Date.parse(value) - Date.now();\n\tif (!Number.isFinite(ms) || ms < 0 || ms > MAX_RETRY_AFTER_MS)\n\t\treturn undefined;\n\treturn ms;\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n\tconst reason = signal.reason;\n\tif (reason instanceof Error) return reason;\n\treturn new DOMException(\n\t\ttypeof reason === \"string\" ? reason : \"The operation was aborted\",\n\t\t\"AbortError\",\n\t);\n}\n\n/** Sleep that wakes early (rejecting with the abort reason) when `signal` fires. */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) return reject(abortReason(signal));\n\t\tconst onAbort = () => {\n\t\t\tclearTimeout(id);\n\t\t\treject(abortReason(signal as AbortSignal));\n\t\t};\n\t\tconst id = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nexport type FetchWithRetryOptions<T> = {\n\t/** Caller-side cancellation. Combined with the timeout; never retried. */\n\tsignal?: AbortSignal;\n\t/**\n\t * Consume the response body inside the timeout window. Defaults to\n\t * returning the `Response` untouched, in which case the caller reads the\n\t * body outside the deadline.\n\t */\n\tread?: (response: Response) => Promise<T>;\n};\n\n/**\n * Fetch with linear backoff on network errors, timeouts, 429 and 5xx.\n *\n * One timeout covers each attempt end to end, headers and body: the timer is\n * armed before `fetch` and cleared once the attempt settles (before any\n * retry sleep, and in `finally`), so a body that never arrives rejects with\n * {@link TimeoutError} rather than hanging the caller, and a rejected fetch\n * never leaves a live timer behind.\n * A caller abort (`signal`) rejects at once with the signal's reason and is\n * not retried.\n */\nexport async function fetchWithRetry<T = Response>(\n\turl: string,\n\toptions: RequestInit,\n\tretryCount: number,\n\tretryDelay: number,\n\ttimeout: number,\n\textra: FetchWithRetryOptions<T> = {},\n): Promise<T> {\n\tconst { signal } = extra;\n\tconst read =\n\t\textra.read ?? (async (response: Response) => response as unknown as T);\n\tconst method = options.method ?? \"GET\";\n\tlet lastError: Error | undefined;\n\n\tfor (let attempt = 0; attempt <= retryCount; attempt++) {\n\t\tif (signal?.aborted) throw abortReason(signal);\n\n\t\tconst controller = new AbortController();\n\t\tlet timedOut = false;\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tcontroller.abort(new TimeoutError({ method, url, timeout, attempt }));\n\t\t}, timeout);\n\t\tconst onCallerAbort = () =>\n\t\t\tcontroller.abort(abortReason(signal as AbortSignal));\n\t\tsignal?.addEventListener(\"abort\", onCallerAbort, { once: true });\n\n\t\t// Rejects the moment the attempt is aborted, whether by the timer or by\n\t\t// the caller, so a body read on a stalled stream cannot outlive the\n\t\t// deadline even when the runtime does not tie the body to the signal.\n\t\tconst aborted = new Promise<never>((_, reject) => {\n\t\t\tif (controller.signal.aborted) return reject(controller.signal.reason);\n\t\t\tcontroller.signal.addEventListener(\n\t\t\t\t\"abort\",\n\t\t\t\t() => reject(controller.signal.reason),\n\t\t\t\t{ once: true },\n\t\t\t);\n\t\t});\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\ttry {\n\t\t\t\tresponse = await Promise.race([\n\t\t\t\t\tfetch(url, { ...options, signal: controller.signal }),\n\t\t\t\t\taborted,\n\t\t\t\t]);\n\t\t\t} catch (error) {\n\t\t\t\tif (signal?.aborted) throw abortReason(signal);\n\t\t\t\tlastError = timedOut\n\t\t\t\t\t? new TimeoutError({ method, url, timeout, attempt })\n\t\t\t\t\t: error instanceof Error\n\t\t\t\t\t\t? error\n\t\t\t\t\t\t: new Error(String(error));\n\t\t\t\tif (attempt < retryCount) {\n\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\tawait sleep(retryDelay * (attempt + 1), signal);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tthrow lastError;\n\t\t\t}\n\n\t\t\tif (response.ok) {\n\t\t\t\ttry {\n\t\t\t\t\treturn await Promise.race([read(response), aborted]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tresponse.body?.cancel().catch(() => {});\n\t\t\t\t\tif (signal?.aborted) throw abortReason(signal);\n\t\t\t\t\tif (!timedOut) throw error;\n\t\t\t\t\tlastError = new TimeoutError({ method, url, timeout, attempt });\n\t\t\t\t\tif (attempt < retryCount) {\n\t\t\t\t\t\tclearTimeout(timeoutId);\n\t\t\t\t\t\tawait sleep(retryDelay * (attempt + 1), signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst retryable = isRetryableStatus(response.status);\n\t\t\tif (!retryable || attempt === retryCount) {\n\t\t\t\tconst body = await Promise.race([\n\t\t\t\t\tresponse.text().catch(() => undefined),\n\t\t\t\t\taborted.catch(() => undefined),\n\t\t\t\t]);\n\t\t\t\tthrow new HttpRequestError(response.status, {\n\t\t\t\t\tdetails: capDetails(body),\n\t\t\t\t\turl,\n\t\t\t\t\tmethod,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tlastError = new HttpRequestError(response.status, { url, method });\n\t\t\t// A server-sent Retry-After (429/503) overrides the linear backoff.\n\t\t\tconst delay = retryAfterMs(response) ?? retryDelay * (attempt + 1);\n\t\t\tresponse.body?.cancel().catch(() => {});\n\t\t\t// The attempt is over: a Retry-After longer than `timeout` must not\n\t\t\t// let the attempt timer fire mid-sleep and flag a timeout that never\n\t\t\t// happened.\n\t\t\tclearTimeout(timeoutId);\n\t\t\tawait sleep(delay, signal);\n\t\t} finally {\n\t\t\tclearTimeout(timeoutId);\n\t\t\tsignal?.removeEventListener(\"abort\", onCallerAbort);\n\t\t}\n\t}\n\n\tthrow lastError ?? new Error(\"Request failed\");\n}\n\n/** Decode a 2xx body: JSON when the content type says so, text otherwise. */\nexport async function readBody(response: Response): Promise<unknown> {\n\tconst contentType = response.headers.get(\"content-type\") ?? \"\";\n\tif (contentType.includes(\"application/json\")) {\n\t\treturn response.json();\n\t}\n\treturn response.text();\n}\n\nexport function buildRequestFn(\n\tbaseUrl: string,\n\tconfig: TransportConfig,\n): RequestFn {\n\tconst {\n\t\ttimeout = 30_000,\n\t\tretryCount = 3,\n\t\tretryDelay = 150,\n\t\tfetchOptions = {},\n\t\tapiKey,\n\t} = config;\n\n\treturn async (path: string, options?: RequestOptions) => {\n\t\tconst url = `${baseUrl.replace(/\\/$/, \"\")}${path}`;\n\t\tconst headers: Record<string, string> = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t...(fetchOptions.headers as Record<string, string>),\n\t\t\t...options?.headers,\n\t\t};\n\n\t\tif (apiKey) {\n\t\t\theaders[\"x-api-key\"] = apiKey;\n\t\t}\n\n\t\tconst init: RequestInit = {\n\t\t\t...fetchOptions,\n\t\t\tmethod: options?.method ?? \"GET\",\n\t\t\theaders,\n\t\t};\n\n\t\tif (options?.body !== undefined) {\n\t\t\tinit.body = JSON.stringify(options.body);\n\t\t}\n\n\t\treturn fetchWithRetry(\n\t\t\turl,\n\t\t\tinit,\n\t\t\toptions?.retryCount ?? retryCount,\n\t\t\tretryDelay,\n\t\t\ttimeout,\n\t\t\t{ signal: options?.signal, read: readBody },\n\t\t);\n\t};\n}\n",
25
+ "import type { Simnet } from \"@stacks/clarinet-sdk\";\nimport {\n\ttype ClarityValue as StacksCV,\n\tCl as StacksCl,\n} from \"@stacks/transactions\";\nimport {\n\ttype ClarityValue,\n\tdeserializeCV,\n\tserializeCV,\n} from \"../clarity/index.ts\";\n\n/** Our CV → clarinet-sdk / @stacks/transactions CV via consensus bytes. */\nexport function toChain(cv: ClarityValue): StacksCV {\n\treturn StacksCl.deserialize(serializeCV(cv));\n}\n\n/** clarinet-sdk CV → ours, same wire. */\nexport function fromChain(cv: StacksCV): ClarityValue {\n\treturn deserializeCV(StacksCl.serialize(cv));\n}\n\nexport function hexCv(cv: ClarityValue): string {\n\treturn `0x${serializeCV(cv)}`;\n}\n\nexport function cvFromHex(hex: string): ClarityValue {\n\treturn deserializeCV(hex);\n}\n\nexport function stxBalance(session: Simnet, address: string): bigint {\n\tconst holders = session.getAssetsMap().get(\"STX\");\n\treturn holders?.get(address) ?? 0n;\n}\n",
26
+ "import { sha256 } from \"@noble/hashes/sha2.js\";\nimport type { LocalAccount } from \"../accounts/types.ts\";\nimport { bytesToHex, concatBytes } from \"../utils/encoding.ts\";\nimport { serializeCVBytes } from \"./serialize.ts\";\nimport type { ClarityValue, TupleCV } from \"./types.ts\";\n\n/** asciiToBytes(\"SIP018\") */\nexport const SIP018_PREFIX: Uint8Array = new Uint8Array([\n\t0x53, 0x49, 0x50, 0x30, 0x31, 0x38,\n]);\n\n/** sha256(serialize(cv)) — inner hash used by SIP-018. */\nexport function hashStructuredData(structuredData: ClarityValue): Uint8Array {\n\treturn sha256(serializeCVBytes(structuredData));\n}\n\nfunction isDomain(value: ClarityValue): value is TupleCV {\n\tif (value.type !== \"tuple\") return false;\n\tconst { name, version, \"chain-id\": chainId } = value.value;\n\treturn (\n\t\tname?.type === \"ascii\" &&\n\t\tversion?.type === \"ascii\" &&\n\t\tchainId?.type === \"uint\"\n\t);\n}\n\n/**\n * SIP-018 encoding: `\"SIP018\" || sha256(serialize(domain)) || sha256(serialize(message))`.\n * The signature is over `sha256` of this buffer.\n */\nexport function encodeStructuredData(opts: {\n\tmessage: ClarityValue;\n\tdomain: ClarityValue;\n}): Uint8Array {\n\tif (!isDomain(opts.domain)) {\n\t\tthrow new Error(\n\t\t\t\"domain must be a tuple { name: ascii, version: ascii, chain-id: uint }\",\n\t\t);\n\t}\n\treturn concatBytes(\n\t\tSIP018_PREFIX,\n\t\thashStructuredData(opts.domain),\n\t\thashStructuredData(opts.message),\n\t);\n}\n\n/** SIP-018 message hash: sha256(encodeStructuredData(...)). */\nexport function structuredDataHash(opts: {\n\tmessage: ClarityValue;\n\tdomain: ClarityValue;\n}): Uint8Array {\n\treturn sha256(encodeStructuredData(opts));\n}\n\n/**\n * Sign a SIP-018 structured message. Returns a 65-byte recoverable signature\n * in RSV order (recovery byte last) — the layout contracts expect.\n */\nexport async function signStructuredData(\n\taccount: LocalAccount,\n\topts: { message: ClarityValue; domain: ClarityValue },\n): Promise<string> {\n\tconst vrs = await account.sign(structuredDataHash(opts));\n\tif (vrs.length !== 65) {\n\t\tthrow new Error(\n\t\t\t`Expected 65-byte recoverable signature, got ${vrs.length}`,\n\t\t);\n\t}\n\treturn bytesToHex(concatBytes(vrs.slice(1), vrs.slice(0, 1)));\n}\n",
27
+ "import type { AbiContract } from \"./contract.ts\";\n\nexport const SIP010_ABI = {\n\tfunctions: [\n\t\t{\n\t\t\tname: \"transfer\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{ name: \"amount\", type: \"uint128\" },\n\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t\t{ name: \"memo\", type: { optional: { buff: { length: 34 } } } },\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-balance\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"account\", type: \"principal\" }],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-total-supply\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-name\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: {\n\t\t\t\tresponse: {\n\t\t\t\t\tok: { \"string-ascii\": { length: 32 } },\n\t\t\t\t\terror: \"uint128\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"get-symbol\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: {\n\t\t\t\tresponse: {\n\t\t\t\t\tok: { \"string-ascii\": { length: 10 } },\n\t\t\t\t\terror: \"uint128\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"get-decimals\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-token-uri\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: {\n\t\t\t\tresponse: {\n\t\t\t\t\tok: { optional: { \"string-utf8\": { length: 256 } } },\n\t\t\t\t\terror: \"uint128\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t],\n\tfungible_tokens: [{ name: \"token\" }],\n} as const satisfies AbiContract;\n\nexport const SIP009_ABI = {\n\tfunctions: [\n\t\t{\n\t\t\tname: \"transfer\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{ name: \"id\", type: \"uint128\" },\n\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-owner\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"id\", type: \"uint128\" }],\n\t\t\toutputs: {\n\t\t\t\tresponse: { ok: { optional: \"principal\" }, error: \"uint128\" },\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"get-last-token-id\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-token-uri\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"id\", type: \"uint128\" }],\n\t\t\toutputs: {\n\t\t\t\tresponse: {\n\t\t\t\t\tok: { optional: { \"string-utf8\": { length: 256 } } },\n\t\t\t\t\terror: \"uint128\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t],\n\tnon_fungible_tokens: [{ name: \"nft\", type: \"uint128\" }],\n} as const satisfies AbiContract;\n\nexport const SIP013_ABI = {\n\tfunctions: [\n\t\t{\n\t\t\tname: \"transfer\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{ name: \"token-id\", type: \"uint128\" },\n\t\t\t\t{ name: \"amount\", type: \"uint128\" },\n\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"transfer-memo\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{ name: \"token-id\", type: \"uint128\" },\n\t\t\t\t{ name: \"amount\", type: \"uint128\" },\n\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t\t{ name: \"memo\", type: { buff: { length: 34 } } },\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"transfer-many\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{\n\t\t\t\t\tname: \"transfers\",\n\t\t\t\t\ttype: {\n\t\t\t\t\t\tlist: {\n\t\t\t\t\t\t\ttype: {\n\t\t\t\t\t\t\t\ttuple: [\n\t\t\t\t\t\t\t\t\t{ name: \"token-id\", type: \"uint128\" },\n\t\t\t\t\t\t\t\t\t{ name: \"amount\", type: \"uint128\" },\n\t\t\t\t\t\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t\t\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tlength: 200,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"transfer-many-memo\",\n\t\t\taccess: \"public\",\n\t\t\targs: [\n\t\t\t\t{\n\t\t\t\t\tname: \"transfers\",\n\t\t\t\t\ttype: {\n\t\t\t\t\t\tlist: {\n\t\t\t\t\t\t\ttype: {\n\t\t\t\t\t\t\t\ttuple: [\n\t\t\t\t\t\t\t\t\t{ name: \"token-id\", type: \"uint128\" },\n\t\t\t\t\t\t\t\t\t{ name: \"amount\", type: \"uint128\" },\n\t\t\t\t\t\t\t\t\t{ name: \"sender\", type: \"principal\" },\n\t\t\t\t\t\t\t\t\t{ name: \"recipient\", type: \"principal\" },\n\t\t\t\t\t\t\t\t\t{ name: \"memo\", type: { buff: { length: 34 } } },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tlength: 200,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"bool\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-balance\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [\n\t\t\t\t{ name: \"token-id\", type: \"uint128\" },\n\t\t\t\t{ name: \"account\", type: \"principal\" },\n\t\t\t],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-overall-balance\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"account\", type: \"principal\" }],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-total-supply\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"token-id\", type: \"uint128\" }],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-overall-supply\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-decimals\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"token-id\", type: \"uint128\" }],\n\t\t\toutputs: { response: { ok: \"uint128\", error: \"uint128\" } },\n\t\t},\n\t\t{\n\t\t\tname: \"get-token-uri\",\n\t\t\taccess: \"read-only\",\n\t\t\targs: [{ name: \"token-id\", type: \"uint128\" }],\n\t\t\toutputs: {\n\t\t\t\tresponse: {\n\t\t\t\t\tok: { optional: { \"string-utf8\": { length: 256 } } },\n\t\t\t\t\terror: \"uint128\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t],\n\tfungible_tokens: [],\n\tnon_fungible_tokens: [],\n} as const satisfies AbiContract;\n\n// Camel-case aliases for better DX\nexport const sip010Abi: AbiContract = SIP010_ABI;\nexport const sip009Abi: AbiContract = SIP009_ABI;\nexport const sip013Abi: AbiContract = SIP013_ABI;\n",
28
+ "import type { AbiContract, AbiFunction } from \"./contract.ts\";\nimport { SIP009_ABI, SIP010_ABI, SIP013_ABI } from \"./standards.ts\";\n\n/**\n * Static conformance classification — \"does this contract's ABI look like a\n * SIP-009/010/013 token?\". Powers trait-based discovery for the (many) contracts\n * that conform to a standard without declaring its trait. Lean match: every\n * REQUIRED standard function must be present with the same access + arg arity\n * (optional functions like get-token-uri are ignored). Loose on exact arg/return\n * types to catch real-world variants; consumers wanting certainty use the\n * `declared` traits parsed from source instead.\n */\n\n/** The canonical SIP trait standards this package can classify/scaffold against.\n * Single source of truth — the `SipStandard` type, CLI `--trait` validation, and\n * the MCP traits resource all derive from this so the vocabulary can't drift. */\nexport const TRAIT_STANDARDS = [\"sip-009\", \"sip-010\", \"sip-013\"] as const;\n\nexport type SipStandard = (typeof TRAIT_STANDARDS)[number];\n\ninterface StandardSpec {\n\tid: SipStandard;\n\tabi: AbiContract;\n\t/** Functions in the reference ABI that real tokens may omit. */\n\toptional: ReadonlySet<string>;\n}\n\nconst STANDARDS: ReadonlyArray<StandardSpec> = [\n\t{ id: \"sip-010\", abi: SIP010_ABI, optional: new Set([\"get-token-uri\"]) },\n\t{ id: \"sip-009\", abi: SIP009_ABI, optional: new Set([\"get-token-uri\"]) },\n\t{\n\t\tid: \"sip-013\",\n\t\tabi: SIP013_ABI,\n\t\toptional: new Set([\n\t\t\t\"transfer-memo\",\n\t\t\t\"transfer-many\",\n\t\t\t\"transfer-many-memo\",\n\t\t\t\"get-token-uri\",\n\t\t\t\"get-overall-balance\",\n\t\t\t\"get-overall-supply\",\n\t\t]),\n\t},\n];\n\nfunction indexByName(abi: AbiContract): Map<string, AbiFunction> {\n\tconst m = new Map<string, AbiFunction>();\n\tfor (const f of abi.functions) m.set(f.name, f);\n\treturn m;\n}\n\nfunction conformsTo(candidate: AbiContract, spec: StandardSpec): boolean {\n\tconst fns = indexByName(candidate);\n\tfor (const required of spec.abi.functions) {\n\t\tif (spec.optional.has(required.name)) continue;\n\t\tconst got = fns.get(required.name);\n\t\tif (!got) return false;\n\t\tif (got.access !== required.access) return false;\n\t\tif (got.args.length !== required.args.length) return false;\n\t}\n\treturn true;\n}\n\n/** Return the SIP standards a contract's ABI statically conforms to. */\nexport function classifyContract(abi: AbiContract): SipStandard[] {\n\tif (!abi || !Array.isArray(abi.functions)) return [];\n\treturn STANDARDS.filter((s) => conformsTo(abi, s)).map((s) => s.id);\n}\n\n/**\n * Parse the standards a contract *declares* via `(impl-trait …)` in its Clarity\n * source. Matched heuristically on the trait-reference name (robust across\n * mainnet/testnet principals + community variants) rather than an exact principal\n * allowlist. The ABI/RPC doesn't carry trait info, so source is the only declared\n * signal. `declared` is the high-confidence signal; `classifyContract` is the\n * catch-all for conforming-but-undeclared contracts.\n */\nexport function parseDeclaredStandards(claritySource: string): SipStandard[] {\n\tconst out = new Set<SipStandard>();\n\tconst matches = claritySource.matchAll(/\\(impl-trait\\s+[^)]+\\)/gi);\n\tfor (const m of matches) {\n\t\tconst ref = m[0].toLowerCase();\n\t\tif (ref.includes(\"sip-010\") || ref.includes(\".ft-trait\"))\n\t\t\tout.add(\"sip-010\");\n\t\tif (ref.includes(\"sip-009\") || ref.includes(\"nft-trait\"))\n\t\t\tout.add(\"sip-009\");\n\t\tif (ref.includes(\"sip-013\") || ref.includes(\"semi-fungible\"))\n\t\t\tout.add(\"sip-013\");\n\t}\n\treturn [...out];\n}\n",
29
+ "import {\n\tisAbiBuffer,\n\tisAbiList,\n\tisAbiOptional,\n\tisAbiResponse,\n\tisAbiStringAscii,\n\tisAbiStringUtf8,\n\tisAbiTuple,\n} from \"./abi/guards.ts\";\nimport type { AbiToTS } from \"./abi/mappings.ts\";\nimport type { AbiType } from \"./abi/types.ts\";\nimport { toCamelCase } from \"./abi/utils.ts\";\nimport type { ClarityValue } from \"./types.ts\";\nimport {\n\tboolCV,\n\tbufferCV,\n\tintCV,\n\tlistCV,\n\tnoneCV,\n\tresponseErrorCV,\n\tresponseOkCV,\n\tsomeCV,\n\tstringAsciiCV,\n\tstringUtf8CV,\n\ttupleCV,\n\tuintCV,\n} from \"./values.ts\";\nimport { Cl } from \"./values.ts\";\n\n/** CV type tags — mirrors the discriminants of `ClarityValue`. */\nconst CV_TYPE_TAGS = new Set([\n\t\"int\",\n\t\"uint\",\n\t\"true\",\n\t\"false\",\n\t\"address\",\n\t\"contract\",\n\t\"ascii\",\n\t\"utf8\",\n\t\"buffer\",\n\t\"list\",\n\t\"tuple\",\n\t\"none\",\n\t\"some\",\n\t\"ok\",\n\t\"err\",\n]);\n\n/**\n * Duck-type check: is `value` already a built ClarityValue? Tag-only CVs\n * (`true`/`false`/`none`) have no payload; every other tag carries `value`.\n */\nexport function isClarityValue(value: unknown): value is ClarityValue {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tconst type = (value as { type?: unknown }).type;\n\tif (typeof type !== \"string\" || !CV_TYPE_TAGS.has(type)) return false;\n\tif (type === \"true\" || type === \"false\" || type === \"none\") return true;\n\treturn \"value\" in value;\n}\n\nconst HEX_PAIRS_REGEX = /^(?:[0-9a-fA-F]{2})+$/;\n\n/**\n * Coerce a flexible buffer input to a BufferCV. Accepts `Uint8Array`, a\n * pre-built `BufferCV`, a tagged `{ type: 'ascii' | 'utf8' | 'hex', value }`\n * object, or a bare string (even-length hex — optionally 0x-prefixed — is\n * decoded as hex; anything else is UTF-8 encoded).\n */\nfunction coerceBuffer(value: unknown): ClarityValue {\n\tif (value instanceof Uint8Array) return bufferCV(value);\n\tif (typeof value === \"object\" && value !== null && \"type\" in value) {\n\t\tconst tagged = value as { type: string; value?: unknown };\n\t\tif (tagged.type === \"buffer\" && isClarityValue(value)) return value;\n\t\tif (typeof tagged.value === \"string\") {\n\t\t\tif (tagged.type === \"ascii\") return Cl.bufferFromAscii(tagged.value);\n\t\t\tif (tagged.type === \"utf8\") return Cl.bufferFromUtf8(tagged.value);\n\t\t\tif (tagged.type === \"hex\") return Cl.bufferFromHex(tagged.value);\n\t\t}\n\t\tthrow new Error(`Unsupported buffer input: ${JSON.stringify(value)}`);\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst hex = value.startsWith(\"0x\") ? value.slice(2) : value;\n\t\tif (HEX_PAIRS_REGEX.test(hex)) return Cl.bufferFromHex(hex);\n\t\treturn Cl.bufferFromUtf8(value);\n\t}\n\tthrow new Error(\n\t\t\"buffer arg expects Uint8Array, hex string, { type, value }, or BufferCV\",\n\t);\n}\n\n/**\n * Convert a JS value to a ClarityValue using ABI type information.\n *\n * Pre-built ClarityValues pass through unchanged (escape hatch for callers\n * that already hold a CV). Buffer args additionally accept hex strings and\n * tagged `{ type, value }` objects — matching the generated-client input\n * contract.\n */\nexport function jsToClarityValue(\n\tabiType: AbiType,\n\tvalue: unknown,\n): ClarityValue {\n\t// Buffers first: the tagged `{ type: 'ascii', value }` input form is\n\t// shape-identical to StringAsciiCV, so buffer coercion wins for buff args.\n\tif (isAbiBuffer(abiType)) return coerceBuffer(value);\n\n\tif (isClarityValue(value)) return value;\n\n\tif (abiType === \"uint128\") return uintCV(value as bigint | number);\n\tif (abiType === \"int128\") return intCV(value as bigint | number);\n\tif (abiType === \"bool\") return boolCV(value as boolean);\n\tif (abiType === \"principal\" || abiType === \"trait_reference\")\n\t\treturn Cl.principal(value as string);\n\n\tif (isAbiStringAscii(abiType)) return stringAsciiCV(value as string);\n\tif (isAbiStringUtf8(abiType)) return stringUtf8CV(value as string);\n\n\tif (isAbiList(abiType)) {\n\t\tconst arr = value as unknown[];\n\t\treturn listCV(arr.map((item) => jsToClarityValue(abiType.list.type, item)));\n\t}\n\n\tif (isAbiTuple(abiType)) {\n\t\tconst obj = value as Record<string, unknown>;\n\t\tconst data: Record<string, ClarityValue> = {};\n\t\tfor (const field of abiType.tuple) {\n\t\t\tconst camelKey = toCamelCase(field.name);\n\t\t\tconst hasOriginal = field.name in obj;\n\t\t\tconst hasCamel = camelKey in obj;\n\t\t\tconst fieldValue = hasOriginal\n\t\t\t\t? obj[field.name]\n\t\t\t\t: hasCamel\n\t\t\t\t\t? obj[camelKey]\n\t\t\t\t\t: undefined;\n\t\t\tif (fieldValue === undefined && !isAbiOptional(field.type)) {\n\t\t\t\tthrow new Error(`Missing tuple field: ${field.name}`);\n\t\t\t}\n\t\t\tdata[field.name] = jsToClarityValue(field.type, fieldValue);\n\t\t}\n\t\treturn tupleCV(data);\n\t}\n\n\tif (isAbiOptional(abiType)) {\n\t\tif (value === null || value === undefined) return noneCV();\n\t\treturn someCV(jsToClarityValue(abiType.optional, value));\n\t}\n\n\tif (isAbiResponse(abiType)) {\n\t\tconst obj = value as Record<string, unknown>;\n\t\tif (\"ok\" in obj && !(\"err\" in obj))\n\t\t\treturn responseOkCV(jsToClarityValue(abiType.response.ok, obj.ok));\n\t\tif (\"err\" in obj && !(\"ok\" in obj))\n\t\t\treturn responseErrorCV(jsToClarityValue(abiType.response.error, obj.err));\n\t\tthrow new Error(\"Response must have exactly 'ok' or 'err' property\");\n\t}\n\n\tthrow new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);\n}\n\n/**\n * Convert a ClarityValue back to a typed JS value using ABI type information.\n */\nexport function clarityValueToJS<T extends AbiType>(\n\tabiType: T,\n\tcv: ClarityValue,\n): AbiToTS<T> {\n\treturn clarityValueToJSInner(abiType, cv) as AbiToTS<T>;\n}\n\n/** Non-generic version for internal use — avoids deep type instantiation. */\nexport function clarityValueToJSUntyped(\n\tabiType: AbiType,\n\tcv: ClarityValue,\n): unknown {\n\treturn clarityValueToJSInner(abiType, cv);\n}\n\nfunction clarityValueToJSInner(abiType: AbiType, cv: ClarityValue): unknown {\n\tif (abiType === \"uint128\" || abiType === \"int128\") {\n\t\tif (cv.type !== \"int\" && cv.type !== \"uint\")\n\t\t\tthrow new Error(`Expected int/uint CV, got ${cv.type}`);\n\t\treturn cv.value;\n\t}\n\n\tif (abiType === \"bool\") {\n\t\tif (cv.type === \"true\") return true;\n\t\tif (cv.type === \"false\") return false;\n\t\tthrow new Error(`Expected bool CV, got ${cv.type}`);\n\t}\n\n\tif (abiType === \"principal\" || abiType === \"trait_reference\") {\n\t\tif (cv.type !== \"address\" && cv.type !== \"contract\")\n\t\t\tthrow new Error(`Expected principal CV, got ${cv.type}`);\n\t\treturn cv.value;\n\t}\n\n\tif (isAbiStringAscii(abiType) || isAbiStringUtf8(abiType)) {\n\t\tif (cv.type !== \"ascii\" && cv.type !== \"utf8\")\n\t\t\tthrow new Error(`Expected string CV, got ${cv.type}`);\n\t\treturn cv.value;\n\t}\n\n\tif (isAbiBuffer(abiType)) {\n\t\tif (cv.type !== \"buffer\")\n\t\t\tthrow new Error(`Expected buffer CV, got ${cv.type}`);\n\t\t// BufferCV stores hex string; convert back to Uint8Array\n\t\tconst hex = cv.value;\n\t\tconst bytes = new Uint8Array(hex.length / 2);\n\t\tfor (let i = 0; i < bytes.length; i++) {\n\t\t\tbytes[i] = Number.parseInt(hex.substring(i * 2, i * 2 + 2), 16);\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tif (isAbiList(abiType)) {\n\t\tif (cv.type !== \"list\") throw new Error(`Expected list CV, got ${cv.type}`);\n\t\treturn cv.value.map((item) =>\n\t\t\tclarityValueToJSInner(abiType.list.type, item),\n\t\t);\n\t}\n\n\tif (isAbiTuple(abiType)) {\n\t\tif (cv.type !== \"tuple\")\n\t\t\tthrow new Error(`Expected tuple CV, got ${cv.type}`);\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const field of abiType.tuple) {\n\t\t\tconst fieldCV = cv.value[field.name];\n\t\t\tif (!fieldCV) throw new Error(`Missing tuple field in CV: ${field.name}`);\n\t\t\tconst camelKey = toCamelCase(field.name);\n\t\t\tresult[camelKey] = clarityValueToJSInner(field.type, fieldCV);\n\t\t}\n\t\treturn result;\n\t}\n\n\tif (isAbiOptional(abiType)) {\n\t\tif (cv.type === \"none\") return null;\n\t\tif (cv.type === \"some\")\n\t\t\treturn clarityValueToJSInner(abiType.optional, cv.value);\n\t\tthrow new Error(`Expected optional CV, got ${cv.type}`);\n\t}\n\n\tif (isAbiResponse(abiType)) {\n\t\tif (cv.type === \"ok\")\n\t\t\treturn { ok: clarityValueToJSInner(abiType.response.ok, cv.value) };\n\t\tif (cv.type === \"err\")\n\t\t\treturn { err: clarityValueToJSInner(abiType.response.error, cv.value) };\n\t\tthrow new Error(`Expected response CV, got ${cv.type}`);\n\t}\n\n\tthrow new Error(`Unknown ABI type: ${JSON.stringify(abiType)}`);\n}\n",
30
+ "import { BaseError } from \"../errors/base.ts\";\n\n/** The simnet transport does not implement this node/API route. */\nexport class SimnetUnsupportedError extends BaseError {\n\toverride name = \"SimnetUnsupportedError\";\n\tpath: string;\n\n\tconstructor(path: string) {\n\t\tsuper(`simnet transport does not implement ${path}`);\n\t\tthis.path = path;\n\t}\n}\n",
31
+ "import type { Simnet } from \"@stacks/clarinet-sdk\";\nimport { HttpRequestError } from \"../errors/http.ts\";\nimport { getTransactionId } from \"../transactions/signer.ts\";\nimport { PayloadType } from \"../transactions/types.ts\";\nimport { deserializeTransaction } from \"../transactions/wire/deserialize.ts\";\nimport { createTransport } from \"../transports/createTransport.ts\";\nimport type {\n\tRequestFn,\n\tRequestOptions,\n\tTransportFactory,\n} from \"../transports/types.ts\";\nimport { c32address } from \"../utils/c32.ts\";\nimport { AddressVersion } from \"../utils/constants.ts\";\nimport { hexToBytes, without0x } from \"../utils/encoding.ts\";\nimport { cvFromHex, fromChain, hexCv, stxBalance, toChain } from \"./cv.ts\";\nimport { SimnetUnsupportedError } from \"./errors.ts\";\n\ntype ReceiptRow = {\n\ttx_status: string;\n\tblock_height: number;\n\ttx_result?: { hex: string };\n\tevents: unknown[];\n};\n\nfunction stripQuery(path: string): string {\n\tconst q = path.indexOf(\"?\");\n\treturn q === -1 ? path : path.slice(0, q);\n}\n\nfunction decodePath(path: string): string[] {\n\treturn stripQuery(path)\n\t\t.split(\"/\")\n\t\t.filter(Boolean)\n\t\t.map((s) => decodeURIComponent(s));\n}\n\nfunction contractId(address: string, name: string): string {\n\treturn `${address}.${name}`;\n}\n\nfunction originAddress(\n\tsignerHash160: string,\n\tnetwork: \"mainnet\" | \"testnet\",\n): string {\n\tconst version =\n\t\tnetwork === \"mainnet\"\n\t\t\t? AddressVersion.MainnetSingleSig\n\t\t\t: AddressVersion.TestnetSingleSig;\n\treturn c32address(version, signerHash160);\n}\n\nfunction normalizeTxid(txid: string): string {\n\treturn txid.startsWith(\"0x\") ? txid : `0x${txid}`;\n}\n\nfunction notFound(path: string): never {\n\tthrow new HttpRequestError(404, { url: path, method: \"GET\" });\n}\n\nfunction noEstimate(path: string): never {\n\tthrow new HttpRequestError(400, {\n\t\turl: path,\n\t\tmethod: \"POST\",\n\t\tdetails: '{\"reason\":\"NoEstimateAvailable\"}',\n\t});\n}\n\n/**\n * Map Hiro/stacks-node REST paths onto an in-process Clarinet `Simnet`.\n * `getContract` / public+wallet actions then work unchanged against simnet.\n */\nexport function simnet(session: Simnet): TransportFactory {\n\tconst nonces = new Map<string, number>();\n\tconst receipts = new Map<string, ReceiptRow>();\n\n\tconst request: RequestFn = async (path: string, options?: RequestOptions) => {\n\t\tconst method = options?.method ?? \"GET\";\n\t\tconst parts = decodePath(path);\n\n\t\tif (parts[0] === \"v2\" && parts[1] === \"info\" && method === \"GET\") {\n\t\t\treturn {\n\t\t\t\tstacks_tip_height: session.stacksBlockHeight ?? session.blockHeight,\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tparts[0] === \"v2\" &&\n\t\t\tparts[1] === \"accounts\" &&\n\t\t\tparts[2] &&\n\t\t\tmethod === \"GET\"\n\t\t) {\n\t\t\tconst address = parts[2];\n\t\t\treturn {\n\t\t\t\tnonce: nonces.get(address) ?? 0,\n\t\t\t\tbalance: String(stxBalance(session, address)),\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tparts[0] === \"v2\" &&\n\t\t\tparts[1] === \"contracts\" &&\n\t\t\tparts[2] === \"call-read\" &&\n\t\t\tparts[3] &&\n\t\t\tparts[4] &&\n\t\t\tparts[5] &&\n\t\t\tmethod === \"POST\"\n\t\t) {\n\t\t\tconst body = options?.body as\n\t\t\t\t| { sender?: string; arguments?: string[] }\n\t\t\t\t| undefined;\n\t\t\tconst id = contractId(parts[3], parts[4]);\n\t\t\tconst fn = parts[5];\n\t\t\tconst sender = body?.sender ?? parts[3];\n\t\t\tconst args = (body?.arguments ?? []).map((hex) =>\n\t\t\t\ttoChain(cvFromHex(hex)),\n\t\t\t);\n\t\t\ttry {\n\t\t\t\tconst { result } = session.callReadOnlyFn(id, fn, args, sender);\n\t\t\t\treturn { okay: true, result: hexCv(fromChain(result)) };\n\t\t\t} catch (error) {\n\t\t\t\tconst cause = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn { okay: false, cause };\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\tparts[0] === \"v2\" &&\n\t\t\tparts[1] === \"map_entry\" &&\n\t\t\tparts[2] &&\n\t\t\tparts[3] &&\n\t\t\tparts[4] &&\n\t\t\tmethod === \"POST\"\n\t\t) {\n\t\t\tconst keyHex =\n\t\t\t\ttypeof options?.body === \"string\"\n\t\t\t\t\t? options.body\n\t\t\t\t\t: String(options?.body ?? \"\");\n\t\t\tconst value = session.getMapEntry(\n\t\t\t\tcontractId(parts[2], parts[3]),\n\t\t\t\tparts[4],\n\t\t\t\ttoChain(cvFromHex(keyHex)),\n\t\t\t);\n\t\t\treturn { data: hexCv(fromChain(value)) };\n\t\t}\n\n\t\tif (\n\t\t\tparts[0] === \"v2\" &&\n\t\t\tparts[1] === \"data_var\" &&\n\t\t\tparts[2] &&\n\t\t\tparts[3] &&\n\t\t\tparts[4] &&\n\t\t\tmethod === \"GET\"\n\t\t) {\n\t\t\tconst value = session.getDataVar(\n\t\t\t\tcontractId(parts[2], parts[3]),\n\t\t\t\tparts[4],\n\t\t\t);\n\t\t\treturn { data: hexCv(fromChain(value)) };\n\t\t}\n\n\t\tif (parts[0] === \"v2\" && parts[1] === \"fees\" && method === \"POST\") {\n\t\t\tnoEstimate(path);\n\t\t}\n\n\t\tif (parts[0] === \"v2\" && parts[1] === \"transactions\" && method === \"POST\") {\n\t\t\treturn handleBroadcast(session, options?.body, nonces, receipts);\n\t\t}\n\n\t\tif (\n\t\t\tparts[0] === \"extended\" &&\n\t\t\tparts[1] === \"v1\" &&\n\t\t\tparts[2] === \"tx\" &&\n\t\t\tparts[3] &&\n\t\t\tmethod === \"GET\"\n\t\t) {\n\t\t\tconst row = receipts.get(normalizeTxid(parts[3]));\n\t\t\tif (!row) notFound(path);\n\t\t\treturn row;\n\t\t}\n\n\t\tthrow new SimnetUnsupportedError(stripQuery(path));\n\t};\n\n\treturn () => createTransport(\"simnet\", { request });\n}\n\nfunction handleBroadcast(\n\tsession: Simnet,\n\tbody: unknown,\n\tnonces: Map<string, number>,\n\treceipts: Map<string, ReceiptRow>,\n): { txid: string } {\n\tconst txHex =\n\t\ttypeof body === \"object\" && body !== null && \"tx\" in body\n\t\t\t? String((body as { tx: string }).tx)\n\t\t\t: \"\";\n\tconst tx = deserializeTransaction(hexToBytes(without0x(txHex)));\n\tconst txid = normalizeTxid(getTransactionId(tx));\n\tconst network = tx.chainId === 0x00000001 ? \"mainnet\" : \"testnet\";\n\tconst sender = originAddress(tx.auth.spendingCondition.signer, network);\n\n\tlet resultHex: string | undefined;\n\tlet events: unknown[] = [];\n\tlet aborted = false;\n\n\tif (tx.payload.payloadType === PayloadType.ContractCall) {\n\t\tconst p = tx.payload;\n\t\tconst id = contractId(p.contractAddress, p.contractName);\n\t\tconst parsed = session.callPublicFn(\n\t\t\tid,\n\t\t\tp.functionName,\n\t\t\tp.functionArgs.map(toChain),\n\t\t\tsender,\n\t\t);\n\t\tconst ours = fromChain(parsed.result);\n\t\tresultHex = hexCv(ours);\n\t\tevents = parsed.events;\n\t\taborted = ours.type === \"err\";\n\t} else if (tx.payload.payloadType === PayloadType.TokenTransfer) {\n\t\tconst recipient = tx.payload.recipient;\n\t\tconst to =\n\t\t\trecipient.type === \"address\" || recipient.type === \"contract\"\n\t\t\t\t? recipient.value\n\t\t\t\t: sender;\n\t\tconst parsed = session.transferSTX(tx.payload.amount, to, sender);\n\t\tresultHex = hexCv(fromChain(parsed.result));\n\t\tevents = parsed.events;\n\t} else {\n\t\tthrow new SimnetUnsupportedError(\n\t\t\t`POST /v2/transactions payload ${tx.payload.payloadType}`,\n\t\t);\n\t}\n\n\tnonces.set(sender, Number(tx.auth.spendingCondition.nonce) + 1);\n\treceipts.set(txid, {\n\t\ttx_status: aborted ? \"abort_by_response\" : \"success\",\n\t\tblock_height: session.stacksBlockHeight ?? session.blockHeight,\n\t\ttx_result: resultHex ? { hex: resultHex } : undefined,\n\t\tevents,\n\t});\n\treturn { txid };\n}\n",
32
+ "import type { StacksChain } from \"./types.ts\";\n\n/** Stacks mainnet chain definition (Hiro API). */\nexport const mainnet: StacksChain = {\n\tid: 0x00000001,\n\tname: \"Stacks Mainnet\",\n\tnetwork: \"mainnet\",\n\ttransactionVersion: 0x00,\n\tpeerNetworkId: 0x17000000,\n\taddressVersion: { singleSig: 22, multiSig: 20 },\n\tmagicBytes: \"X2\",\n\tbootAddress: \"SP000000000000000000002Q6VF78\",\n\tnativeCurrency: { name: \"Stacks\", symbol: \"STX\", decimals: 6 },\n\trpcUrls: {\n\t\tdefault: {\n\t\t\thttp: [\"https://api.mainnet.hiro.so\"],\n\t\t\tws: [\"wss://api.mainnet.hiro.so/extended/v1/ws\"],\n\t\t},\n\t},\n\tblockExplorers: {\n\t\tdefault: { name: \"Hiro Explorer\", url: \"https://explorer.hiro.so\" },\n\t},\n};\n\n/** Stacks testnet chain definition (Hiro API). */\nexport const testnet: StacksChain = {\n\tid: 0x80000000,\n\tname: \"Stacks Testnet\",\n\tnetwork: \"testnet\",\n\ttransactionVersion: 0x80,\n\tpeerNetworkId: 0xff000000,\n\taddressVersion: { singleSig: 26, multiSig: 21 },\n\tmagicBytes: \"T2\",\n\tbootAddress: \"ST000000000000000000002AMW42H\",\n\tnativeCurrency: { name: \"Stacks\", symbol: \"STX\", decimals: 6 },\n\trpcUrls: {\n\t\tdefault: {\n\t\t\thttp: [\"https://api.testnet.hiro.so\"],\n\t\t\tws: [\"wss://api.testnet.hiro.so/extended/v1/ws\"],\n\t\t},\n\t},\n\tblockExplorers: {\n\t\tdefault: {\n\t\t\tname: \"Hiro Explorer\",\n\t\t\turl: \"https://explorer.hiro.so/?chain=testnet\",\n\t\t},\n\t},\n};\n\n/** Local development chain definition (localhost:3999). */\nexport const devnet: StacksChain = {\n\tid: 0x80000000,\n\tname: \"Stacks Devnet\",\n\tnetwork: \"testnet\",\n\ttransactionVersion: 0x80,\n\tpeerNetworkId: 0xff000000,\n\taddressVersion: { singleSig: 26, multiSig: 21 },\n\tmagicBytes: \"id\",\n\tbootAddress: \"ST000000000000000000002AMW42H\",\n\tnativeCurrency: { name: \"Stacks\", symbol: \"STX\", decimals: 6 },\n\trpcUrls: {\n\t\tdefault: {\n\t\t\thttp: [\"http://localhost:3999\"],\n\t\t\tws: [\"ws://localhost:3999/extended/v1/ws\"],\n\t\t},\n\t},\n};\n\n/** Alias for devnet used in mock/test environments. */\nexport const mocknet: StacksChain = {\n\t...devnet,\n\tname: \"Stacks Mocknet\",\n\taddressVersion: { ...devnet.addressVersion },\n};\n",
33
+ "import { mocknet } from \"../chains/definitions.ts\";\nimport type { StacksChain } from \"../chains/types.ts\";\n\n/**\n * Chain descriptor for a Clarinet simnet session. Address versions match\n * Clarinet's testnet-style accounts (`ST…`). Boot contracts (pox-5, …) still\n * live at their mainnet principals inside the VM.\n */\nexport const simnetChain: StacksChain = {\n\t...mocknet,\n\tname: \"Clarinet Simnet\",\n\trpcUrls: {\n\t\tdefault: { http: [\"simnet://clarinet\"] },\n\t},\n};\n"
34
+ ],
35
+ "mappings": ";A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,QAAQ;AAAA,IACnD,WAAW,YAAY,EAAE,KAAK,UAAU,IAAI;AAAA,IAC5C;AAAA,EACD,CAAC;AAAA,EACD,OAAO,EAAE,YAAK;AAAA;;AC9LR,IAAM,SAAsB;AAAA,EAClC,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,SAAS;AAAA,EACT,oBAAoB;AAAA,EACpB,eAAe;AAAA,EACf,gBAAgB,EAAE,WAAW,IAAI,UAAU,GAAG;AAAA,EAC9C,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,gBAAgB,EAAE,MAAM,UAAU,QAAQ,OAAO,UAAU,EAAE;AAAA,EAC7D,SAAS;AAAA,IACR,SAAS;AAAA,MACR,MAAM,CAAC,uBAAuB;AAAA,MAC9B,IAAI,CAAC,oCAAoC;AAAA,IAC1C;AAAA,EACD;AACD;AAGO,IAAM,UAAuB;AAAA,KAChC;AAAA,EACH,MAAM;AAAA,EACN,gBAAgB,KAAK,OAAO,eAAe;AAC5C;;;ACjEO,IAAM,cAA2B;AAAA,KACpC;AAAA,EACH,MAAM;AAAA,EACN,SAAS;AAAA,IACR,SAAS,EAAE,MAAM,CAAC,mBAAmB,EAAE;AAAA,EACxC;AACD;",
36
+ "debugId": "DCCD8565D6CCBD3B64756E2164756E21",
37
+ "names": []
38
+ }
@@ -3,9 +3,9 @@ import {
3
3
  } from "../../shared/stacks-kg1npstf.js";
4
4
  import {
5
5
  getContract
6
- } from "../../shared/stacks-e3nwm1dz.js";
7
- import"../../shared/stacks-n4d8j8q3.js";
8
- import"../../shared/stacks-ga026yxz.js";
6
+ } from "../../shared/stacks-gyp5ax89.js";
7
+ import"../../shared/stacks-v03zef3g.js";
8
+ import"../../shared/stacks-qex691bh.js";
9
9
  import"../../shared/stacks-x0qqwrev.js";
10
10
  import {
11
11
  Pc
@@ -103,6 +103,10 @@ class MalformedResponseError extends BaseError {
103
103
  name = "MalformedResponseError";
104
104
  }
105
105
 
106
+ class ReadContractError extends BaseError {
107
+ name = "ReadContractError";
108
+ }
109
+
106
110
  // src/utils/c32.ts
107
111
  var import_sha2 = require("@noble/hashes/sha2.js");
108
112
 
@@ -1446,9 +1450,12 @@ async function readContract(client, params) {
1446
1450
  }
1447
1451
  });
1448
1452
  if (data.okay) {
1453
+ if (typeof data.result !== "string") {
1454
+ throw new MalformedResponseError(`readContract: /v2/contracts/call-read response is missing "result"`);
1455
+ }
1449
1456
  return deserializeCVBytes(data.result);
1450
1457
  }
1451
- throw new Error(data.cause ?? "Read-only call failed");
1458
+ throw new ReadContractError(data.cause ?? "Read-only call failed");
1452
1459
  }
1453
1460
 
1454
1461
  // src/actions/wallet/utils.ts
@@ -2301,12 +2308,10 @@ async function getMapEntry(client, params) {
2301
2308
 
2302
2309
  // src/actions/public/getNonce.ts
2303
2310
  async function getNonce(client, params) {
2304
- const data = await client.request(`/v2/accounts/${params.address}`, {
2305
- method: "GET"
2306
- });
2311
+ const data = await client.request(`/v2/accounts/${encodeURIComponent(params.address)}`, { method: "GET" });
2307
2312
  const nonce = data?.nonce;
2308
2313
  if (typeof nonce !== "number" && typeof nonce !== "string") {
2309
- throw new Error(`getNonce: unexpected /v2/accounts response for ${params.address} (missing numeric nonce)`);
2314
+ throw new MalformedResponseError(`getNonce: /v2/accounts/${params.address} response is missing "nonce"`);
2310
2315
  }
2311
2316
  return BigInt(nonce);
2312
2317
  }
@@ -3856,5 +3861,5 @@ var getAccountHistory2 = defaultTools.getAccountHistory;
3856
3861
  var getMempoolStats2 = defaultTools.getMempoolStats;
3857
3862
  var getNftHoldings2 = defaultTools.getNftHoldings;
3858
3863
 
3859
- //# debugId=BA352497F272866664756E2164756E21
3864
+ //# debugId=24BD4E2DF5A24D8B64756E2164756E21
3860
3865
  //# sourceMappingURL=index.cjs.map