@bopen-io/color-permission-module 0.1.0 → 0.1.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["UINT32_MAX","UTF8_DECODER","toolbox"],"sources":["../src/identifiers.ts","../src/strictJson.ts","../src/ColorPlan.ts","../src/inOrder.ts","../src/overlay.ts","../src/tokenOutputs.ts","../src/ColorPermissionModule.ts","../src/index.ts"],"sourcesContent":["import { PublicKey, type WalletProtocol } from '@bsv/sdk'\nimport { toArray, toHex } from '@bsv/sdk/primitives/utils'\n\n/** Asset selector for a deploy output's key derivation before its asset ID exists. */\nexport const ISSUE = 'ISSUE'\n\n/** Fixed BRC-43 key ID for every `p color` key. */\nexport const COLOR_KEY_ID = 'color'\n\n/** `listOutputs` selector for the inventory across every per-asset basket. */\nexport const ASSETS_SELECTOR = 'p color assets'\n\n/** Basket namespace of the per-asset value and authority baskets. */\nexport const COLOR_BASKET_NAMESPACE = 'p color'\n\nexport type TokenRole = 'value' | 'authority'\n\nconst ASSET_ID = /^([0-9a-f]{64})_(0|[1-9]\\d{0,9})$/\nconst ASSET_TAG = /^([0-9a-f]{64})v(0|[1-9]\\d{0,9})$/\nconst OUTPOINT = /^([0-9a-f]{64})\\.(0|[1-9]\\d{0,9})$/\nconst HEX_TAG = /^(?:[0-9a-f]{2})+$/\nconst IDENTITY_KEY = /^0[23][0-9a-f]{64}$/\nconst WHITESPACE = /\\s/u\nconst UINT32_MAX = 0xffffffff\nconst MAX_PROTOCOL_NAME_LENGTH = 280\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\nexport interface Outpoint {\n txid: string\n vout: number\n}\n\nfunction uint32(text: string): number | undefined {\n const value = Number(text)\n return value <= UINT32_MAX ? value : undefined\n}\n\n/** Parses a canonical BRC-162 API asset ID, `<64 hex>_<vout>`. */\nexport function parseAssetId(assetId: unknown): Outpoint {\n const match = typeof assetId === 'string' ? ASSET_ID.exec(assetId) : null\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid asset ID')\n return { txid: match[1], vout }\n}\n\n/** Parses an asset ID, or `ISSUE` where a deploy output's key is meant. */\nexport function parseAssetSelector(assetId: unknown): string {\n if (assetId === ISSUE) return ISSUE\n parseAssetId(assetId)\n return assetId as string\n}\n\n/** Parses a canonical BRC-36 dot-form outpoint. */\nexport function parseOutpoint(outpoint: unknown): Outpoint {\n const match = typeof outpoint === 'string' ? OUTPOINT.exec(outpoint) : null\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid outpoint')\n return { txid: match[1], vout }\n}\n\nexport function outpointString(txid: string, vout: number): string {\n return `${txid}.${vout}`\n}\n\n/** The wire tag for an asset ID or `ISSUE` in protocol IDs and basket names. */\nexport function assetTag(assetId: string): string {\n if (assetId === ISSUE) return 'issue'\n const { txid, vout } = parseAssetId(assetId)\n return `${txid}v${vout}`\n}\n\nfunction assetIdFromTag(tag: string): string {\n if (tag === 'issue') return ISSUE\n const match = ASSET_TAG.exec(tag)\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid asset tag')\n return `${match[1]}_${vout}`\n}\n\n/** Validates a remittance string: nonempty strict UTF-8 without whitespace. */\nexport function validateRemittanceString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0 || WHITESPACE.test(value)) {\n throw new Error(`BRC-207: ${name} must be a nonempty string without whitespace`)\n }\n // Lone surrogates are not strict UTF-8; encoding replaces them, so the round trip differs.\n if (UTF8_DECODER.decode(new TextEncoder().encode(value)) !== value) {\n throw new Error(`BRC-207: ${name} must be strict UTF-8`)\n }\n return value\n}\n\n/** Validates a compressed secp256k1 public key in lowercase hex. */\nexport function validateIdentityKey(value: unknown, name: string): string {\n if (typeof value !== 'string' || !IDENTITY_KEY.test(value)) {\n throw new Error(`BRC-207: ${name} must be a compressed public key in lowercase hex`)\n }\n try {\n PublicKey.fromString(value)\n } catch (error) {\n throw new Error(`BRC-207: ${name} is not a valid public key (${(error as Error).message})`)\n }\n return value\n}\n\n/** The BRC-43 protocol ID `[2, \"p color <assetTag> <prefixTag> <suffixTag>\"]`. */\nexport function colorProtocolID(\n assetId: string,\n derivationPrefix: string,\n derivationSuffix: string\n): WalletProtocol {\n const prefixTag = toHex(\n toArray(validateRemittanceString(derivationPrefix, 'derivationPrefix'), 'utf8')\n )\n const suffixTag = toHex(\n toArray(validateRemittanceString(derivationSuffix, 'derivationSuffix'), 'utf8')\n )\n const name = `p color ${assetTag(assetId)} ${prefixTag} ${suffixTag}`\n if (name.length > MAX_PROTOCOL_NAME_LENGTH)\n throw new Error('BRC-207: protocol name exceeds 280 characters')\n return [2, name]\n}\n\n/** Parses a `p color` protocol ID back into its asset selector and remittance strings. */\nexport function parseColorProtocolID(protocolID: unknown): {\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n} {\n if (!Array.isArray(protocolID) || protocolID.length !== 2 || protocolID[0] !== 2) {\n throw new Error('BRC-207: p color protocols use security level 2')\n }\n const name = protocolID[1]\n const parts = typeof name === 'string' ? name.split(' ') : []\n if (\n parts.length !== 5 ||\n parts[0] !== 'p' ||\n parts[1] !== 'color' ||\n name.length > MAX_PROTOCOL_NAME_LENGTH\n ) {\n throw new Error('BRC-207: invalid p color protocol name')\n }\n const [, , tag, prefixTag, suffixTag] = parts\n if (!HEX_TAG.test(prefixTag) || !HEX_TAG.test(suffixTag)) {\n throw new Error('BRC-207: invalid p color remittance tags')\n }\n const derivationPrefix = validateRemittanceString(\n UTF8_DECODER.decode(new Uint8Array(toArray(prefixTag, 'hex'))),\n 'derivationPrefix'\n )\n const derivationSuffix = validateRemittanceString(\n UTF8_DECODER.decode(new Uint8Array(toArray(suffixTag, 'hex'))),\n 'derivationSuffix'\n )\n return { assetId: assetIdFromTag(tag), derivationPrefix, derivationSuffix }\n}\n\n/** The per-asset value or authority basket; there is no `issue` basket. */\nexport function assetBasket(assetId: string, role: TokenRole): string {\n parseAssetId(assetId)\n const basket = `${COLOR_BASKET_NAMESPACE} ${assetTag(assetId)}`\n return role === 'authority' ? `${basket} authority` : basket\n}\n\nfunction parseTaggedBasket(rest: string[]): { assetId: string; role: TokenRole } | undefined {\n if (rest.length === 0 || rest.length > 2 || (rest.length === 2 && rest[1] !== 'authority'))\n return undefined\n const assetId = assetIdFromTag(rest[0])\n if (assetId === ISSUE) throw new Error('BRC-207: issue is not a stored basket')\n return { assetId, role: rest.length === 2 ? 'authority' : 'value' }\n}\n\n/** Parses a per-asset value (`p color <assetTag>`) or authority (`... authority`) basket. */\nexport function parseAssetBasket(basket: string): { assetId: string; role: TokenRole } | undefined {\n const parts = basket.split(' ')\n if (parts[0] !== 'p' || parts[1] !== 'color' || parts[2] === 'balance' || parts[2] === 'assets')\n return undefined\n return parseTaggedBasket(parts.slice(2))\n}\n\n/** Parses a balance selector, `p color balance <assetTag>` or `... authority`. */\nexport function parseBalanceSelector(\n basket: string\n): { assetId: string; role: TokenRole } | undefined {\n const parts = basket.split(' ')\n if (parts[0] !== 'p' || parts[1] !== 'color' || parts[2] !== 'balance') return undefined\n return parseTaggedBasket(parts.slice(3))\n}\n\n/** The shared deployment discovery topic. */\nexport const DISCOVERY_TOPIC = 'tm_color'\n\nexport function colorTopic(assetId: string): string {\n return `tm_color_${assetId}`\n}\n","// Strict JSON for BRC-207 metadata: RFC 8259 grammar, duplicate members rejected\n// at every level, unpaired surrogate escapes rejected, bounded nesting.\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject\nexport interface JsonObject {\n [member: string]: JsonValue\n}\n\nconst MAX_DEPTH = 64\nconst UINT32_MAX = 0xffffffff\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\nconst NUMBER = /-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y\nconst ESCAPES: Record<string, string> = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n}\n\nclass Parser {\n private position = 0\n\n constructor(\n private readonly text: string,\n private readonly label: string\n ) {}\n\n fail(reason: string): never {\n throw new Error(`BRC-207: ${this.label} is not strict JSON (${reason})`)\n }\n\n parse(): JsonValue {\n const value = this.value(0)\n this.whitespace()\n if (this.position !== this.text.length) this.fail('trailing data')\n return value\n }\n\n private whitespace(): void {\n while (this.position < this.text.length && ' \\t\\n\\r'.includes(this.text[this.position]))\n this.position++\n }\n\n private literal(word: string, value: JsonValue): JsonValue {\n if (!this.text.startsWith(word, this.position)) this.fail('invalid literal')\n this.position += word.length\n return value\n }\n\n private value(depth: number): JsonValue {\n if (depth > MAX_DEPTH) this.fail('nesting too deep')\n this.whitespace()\n const next = this.text[this.position]\n if (next === '{') return this.object(depth)\n if (next === '[') return this.array(depth)\n if (next === '\"') return this.string()\n if (next === 't') return this.literal('true', true)\n if (next === 'f') return this.literal('false', false)\n if (next === 'n') return this.literal('null', null)\n return this.number()\n }\n\n private number(): number {\n NUMBER.lastIndex = this.position\n const match = NUMBER.exec(this.text)\n if (match == null) this.fail('invalid value')\n this.position += match[0].length\n const value = Number(match[0])\n // BRC-207 integer fields are integers, not fractions: 1.0 and 1e0 are not the integer 1.\n // JSON.stringify writes every integer below 1e21 as plain digits, so only a literal in that\n // range can be a non-integer spelling of an integer.\n if (Number.isInteger(value) && Math.abs(value) < 1e21 && /[.eE]/.test(match[0]))\n this.fail('an integer written as a fraction or exponent')\n return value\n }\n\n private hex4(): number {\n const digits = this.text.slice(this.position, this.position + 4)\n if (!/^[0-9a-fA-F]{4}$/.test(digits)) this.fail('invalid unicode escape')\n this.position += 4\n return Number.parseInt(digits, 16)\n }\n\n private string(): string {\n this.position++\n let result = ''\n for (;;) {\n const char = this.text[this.position++]\n if (char === undefined) this.fail('unterminated string')\n if (char === '\"') return result\n if (char < ' ') this.fail('control character in string')\n result += char === '\\\\' ? this.escape() : char\n }\n }\n\n /** Decodes the escape after a backslash; a surrogate pair decodes to its one code point. */\n private escape(): string {\n const escape = this.text[this.position++]\n if (escape !== 'u') {\n const decoded = ESCAPES[escape]\n if (decoded === undefined) this.fail('invalid escape')\n return decoded\n }\n const unit = this.hex4()\n if (unit >= 0xdc00 && unit <= 0xdfff) this.fail('unpaired surrogate')\n if (unit < 0xd800 || unit > 0xdbff) return String.fromCodePoint(unit)\n if (this.text.slice(this.position, this.position + 2) !== String.raw`\\u`)\n this.fail('unpaired surrogate')\n this.position += 2\n const low = this.hex4()\n if (low < 0xdc00 || low > 0xdfff) this.fail('unpaired surrogate')\n return String.fromCodePoint(0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00))\n }\n\n private array(depth: number): JsonValue[] {\n this.position++\n const result: JsonValue[] = []\n this.whitespace()\n if (this.text[this.position] === ']') {\n this.position++\n return result\n }\n for (;;) {\n result.push(this.value(depth + 1))\n this.whitespace()\n const next = this.text[this.position++]\n if (next === ']') return result\n if (next !== ',') this.fail('expected , or ]')\n }\n }\n\n private object(depth: number): JsonObject {\n this.position++\n const result: JsonObject = Object.create(null)\n this.whitespace()\n if (this.text[this.position] === '}') {\n this.position++\n return result\n }\n for (;;) {\n this.whitespace()\n if (this.text[this.position] !== '\"') this.fail('expected member name')\n const name = this.string()\n if (Object.hasOwn(result, name)) this.fail(`duplicate member ${name}`)\n this.whitespace()\n if (this.text[this.position++] !== ':') this.fail('expected :')\n result[name] = this.value(depth + 1)\n this.whitespace()\n const next = this.text[this.position++]\n if (next === '}') return result\n if (next !== ',') this.fail('expected , or }')\n }\n }\n}\n\n/** Parses strict JSON text; member objects have no prototype. */\nexport function parseStrictJson(text: string, label: string): JsonValue {\n return new Parser(text, label).parse()\n}\n\n/** Decodes strict UTF-8 bytes and parses them as strict JSON. */\nexport function parseStrictJsonBytes(\n bytes: readonly number[] | Uint8Array,\n label: string\n): JsonValue {\n let text: string\n try {\n text = UTF8_DECODER.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))\n } catch {\n throw new Error(`BRC-207: ${label} is not strict UTF-8`)\n }\n return parseStrictJson(text, label)\n}\n\nexport function jsonObject(value: JsonValue | undefined, label: string): JsonObject {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`BRC-207: ${label} must be a JSON object`)\n }\n return value\n}\n\n/** Requires exactly the named members: every required one, any optional ones, nothing else. */\nexport function exactMembers(\n object: JsonObject,\n required: readonly string[],\n optional: readonly string[],\n label: string\n): void {\n for (const member of required) {\n if (!Object.hasOwn(object, member)) throw new Error(`BRC-207: ${label} is missing ${member}`)\n }\n for (const member of Object.keys(object)) {\n if (!required.includes(member) && !optional.includes(member)) {\n throw new Error(`BRC-207: ${label} has unknown member ${member}`)\n }\n }\n}\n\nexport function jsonArray(value: JsonValue | undefined, label: string): JsonValue[] {\n if (!Array.isArray(value)) throw new Error(`BRC-207: ${label} must be an array`)\n return value\n}\n\nexport function jsonUint32(value: JsonValue | undefined, label: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > UINT32_MAX) {\n throw new Error(`BRC-207: ${label} must be an integer in 0..2^32-1`)\n }\n return value\n}\n\n/** A nonempty array of integer bytes, bounded before it is copied. */\nexport function jsonByteArray(\n value: JsonValue | undefined,\n label: string,\n maxBytes: number\n): number[] {\n const array = jsonArray(value, label)\n if (array.length === 0 || array.length > maxBytes) {\n throw new Error(`BRC-207: ${label} must hold 1..${maxBytes} bytes`)\n }\n for (const byte of array) {\n if (typeof byte !== 'number' || !Number.isInteger(byte) || byte < 0 || byte > 255) {\n throw new Error(`BRC-207: ${label} must contain integer bytes`)\n }\n }\n return array as number[]\n}\n","// BRC-207 action plan codec. Carried in action labels as\n// `p color plan <partIndex> <partCount> <hexChunk>`; no wallet-toolbox dependency\n// so applications can build plans with it.\nimport { toArray, toHex } from '@bsv/sdk/primitives/utils'\nimport {\n colorProtocolID,\n ISSUE,\n parseAssetId,\n parseAssetSelector,\n parseOutpoint,\n validateIdentityKey,\n validateRemittanceString\n} from './identifiers.js'\nimport {\n exactMembers,\n jsonArray,\n jsonObject,\n jsonUint32,\n parseStrictJsonBytes,\n type JsonObject,\n type JsonValue\n} from './strictJson.js'\n\nexport const COLOR_PLAN_LABEL_PREFIX = 'p color plan '\n\nconst CHUNK_HEX_LENGTH = 200\nconst MAX_PLAN_BYTES = 16 * 1024 * 1024\n// Bounds the label count before reassembly; the joined hex is then bounded exactly.\nconst MAX_PLAN_PARTS = Math.ceil((MAX_PLAN_BYTES * 2) / CHUNK_HEX_LENGTH)\nconst PLAN_LABEL = /^p color plan (0|[1-9]\\d{0,9}) ([1-9]\\d{0,9}) ([0-9a-f]+)$/\n\nexport const COLOR_OPERATIONS = [\n 'transfer',\n 'burn',\n 'deploy-fixed',\n 'deploy-authority',\n 'mint',\n 'authority-split',\n 'authority-combine',\n 'authority-transfer',\n 'authority-end',\n 'resource'\n] as const\n\nexport type ColorOperationName = (typeof COLOR_OPERATIONS)[number]\n\n/** Key derivation facts for a managed output; `assetId` is `ISSUE` for a deploy output. */\nexport interface ColorRemittance {\n outputIndex: number\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n senderIdentityKey: string\n}\n\nexport interface ColorOperation {\n assetId: string\n operation: ColorOperationName\n}\n\n/** A BRC-207 version 1 action plan. */\nexport interface ColorPlan {\n version: 1\n assets: string[]\n ownedOutputs: ColorRemittance[]\n operations: ColorOperation[]\n inputPositions: Array<{ outpoint: string; index: number }>\n changePositions: Array<{ assetId: string | null; index: number }>\n sighashTypes: Array<{ outpoint: string; sighashType: number }>\n profileData?: Record<string, Record<string, JsonValue>>\n}\n\nfunction unique<T>(values: T[], label: string): void {\n if (new Set(values).size !== values.length) throw new Error(`BRC-207: duplicate ${label}`)\n}\n\n/** Validates a remittance object, as used by plans and signature envelopes. */\nexport function parseRemittance(value: JsonValue, label: string): ColorRemittance {\n const object = jsonObject(value, label)\n exactMembers(\n object,\n ['outputIndex', 'assetId', 'derivationPrefix', 'derivationSuffix', 'senderIdentityKey'],\n [],\n label\n )\n const remittance: ColorRemittance = {\n outputIndex: jsonUint32(object.outputIndex, `${label}.outputIndex`),\n assetId: parseAssetSelector(object.assetId),\n derivationPrefix: validateRemittanceString(\n object.derivationPrefix,\n `${label}.derivationPrefix`\n ),\n derivationSuffix: validateRemittanceString(\n object.derivationSuffix,\n `${label}.derivationSuffix`\n ),\n senderIdentityKey: validateIdentityKey(object.senderIdentityKey, `${label}.senderIdentityKey`)\n }\n colorProtocolID(remittance.assetId, remittance.derivationPrefix, remittance.derivationSuffix)\n return remittance\n}\n\n/** Validates a remittance list: at most one remittance per output index. */\nexport function parseRemittances(value: JsonValue | undefined, label: string): ColorRemittance[] {\n const remittances = jsonArray(value, label).map((item, i) =>\n parseRemittance(item, `${label}[${i}]`)\n )\n unique(\n remittances.map(remittance => remittance.outputIndex),\n `${label} output index`\n )\n return remittances\n}\n\n/** Validates optional `profileData`: profile identifier, then asset ID or `ISSUE`, then profile data. */\nexport function parseProfileData(\n value: JsonValue | undefined,\n label: string\n): Record<string, Record<string, JsonValue>> | undefined {\n if (value === undefined) return undefined\n const profiles = jsonObject(value, label)\n const result: Record<string, Record<string, JsonValue>> = Object.create(null)\n for (const [profile, assets] of Object.entries(profiles)) {\n const byAsset = jsonObject(assets, `${label}.${profile}`)\n for (const assetId of Object.keys(byAsset)) parseAssetSelector(assetId)\n result[profile] = { ...byAsset }\n }\n return result\n}\n\nfunction parsePlan(value: JsonValue): ColorPlan {\n const object: JsonObject = jsonObject(value, 'plan')\n exactMembers(\n object,\n [\n 'version',\n 'assets',\n 'ownedOutputs',\n 'operations',\n 'inputPositions',\n 'changePositions',\n 'sighashTypes'\n ],\n ['profileData'],\n 'plan'\n )\n if (object.version !== 1) throw new Error('BRC-207: plan version must be 1')\n const assets = jsonArray(object.assets, 'plan.assets').map(asset => parseAssetSelector(asset))\n unique(assets, 'plan asset')\n const operations = jsonArray(object.operations, 'plan.operations').map((item, i) => {\n const operation = jsonObject(item, `plan.operations[${i}]`)\n exactMembers(operation, ['assetId', 'operation'], [], `plan.operations[${i}]`)\n if (!COLOR_OPERATIONS.includes(operation.operation as ColorOperationName)) {\n throw new Error(`BRC-207: plan.operations[${i}] has an unknown operation`)\n }\n return {\n assetId: parseAssetSelector(operation.assetId),\n operation: operation.operation as ColorOperationName\n }\n })\n unique(\n operations.map(operation => `${operation.assetId} ${operation.operation}`),\n 'plan operation'\n )\n const inputPositions = jsonArray(object.inputPositions, 'plan.inputPositions').map((item, i) => {\n const position = jsonObject(item, `plan.inputPositions[${i}]`)\n exactMembers(position, ['outpoint', 'index'], [], `plan.inputPositions[${i}]`)\n parseOutpoint(position.outpoint)\n return {\n outpoint: position.outpoint as string,\n index: jsonUint32(position.index, `plan.inputPositions[${i}].index`)\n }\n })\n unique(\n inputPositions.map(position => position.outpoint),\n 'plan input position outpoint'\n )\n unique(\n inputPositions.map(position => position.index),\n 'plan input position index'\n )\n const changePositions = jsonArray(object.changePositions, 'plan.changePositions').map(\n (item, i) => {\n const position = jsonObject(item, `plan.changePositions[${i}]`)\n exactMembers(position, ['assetId', 'index'], [], `plan.changePositions[${i}]`)\n if (position.assetId !== null) parseAssetId(position.assetId)\n return {\n assetId: position.assetId as string | null,\n index: jsonUint32(position.index, `plan.changePositions[${i}].index`)\n }\n }\n )\n unique(\n changePositions.map(position => position.assetId),\n 'plan change position asset'\n )\n unique(\n changePositions.map(position => position.index),\n 'plan change position index'\n )\n const sighashTypes = jsonArray(object.sighashTypes, 'plan.sighashTypes').map((item, i) => {\n const override = jsonObject(item, `plan.sighashTypes[${i}]`)\n exactMembers(override, ['outpoint', 'sighashType'], [], `plan.sighashTypes[${i}]`)\n parseOutpoint(override.outpoint)\n const sighashType = jsonUint32(override.sighashType, `plan.sighashTypes[${i}].sighashType`)\n if (sighashType > 255)\n throw new Error(`BRC-207: plan.sighashTypes[${i}].sighashType must be in 0..255`)\n return { outpoint: override.outpoint as string, sighashType }\n })\n unique(\n sighashTypes.map(override => override.outpoint),\n 'plan sighash override outpoint'\n )\n const plan: ColorPlan = {\n version: 1,\n assets,\n ownedOutputs: parseRemittances(object.ownedOutputs, 'plan.ownedOutputs'),\n operations,\n inputPositions,\n changePositions,\n sighashTypes\n }\n const profileData = parseProfileData(object.profileData, 'plan.profileData')\n if (profileData !== undefined) plan.profileData = profileData\n const referenced = [\n ...plan.ownedOutputs.map(remittance => remittance.assetId),\n ...plan.operations.map(operation => operation.assetId),\n ...plan.changePositions.flatMap(position =>\n position.assetId === null ? [] : [position.assetId]\n )\n ]\n for (const assetId of referenced) {\n if (!assets.includes(assetId))\n throw new Error(`BRC-207: plan references ${assetId} outside plan.assets`)\n }\n if (\n assets.includes(ISSUE) &&\n plan.operations.filter(op => op.operation.startsWith('deploy-')).length !== 1\n ) {\n throw new Error('BRC-207: a deploy plan has exactly one deploy operation')\n }\n return plan\n}\n\n/** Every chunk is whole hex bytes; every chunk but the last fills its label. */\nfunction assertPlanChunk(hex: string, index: number, count: number): void {\n if (hex.length % 2 !== 0 || hex.length > CHUNK_HEX_LENGTH)\n throw new Error('BRC-207: invalid plan chunk')\n if (index < count - 1 && hex.length !== CHUNK_HEX_LENGTH)\n throw new Error('BRC-207: short nonfinal plan chunk')\n}\n\n/** Encodes and decodes BRC-207 action plans as `p color plan` labels. */\nexport const ColorPlan = {\n /** Splits a plan into `p color plan <i> <n> <hex>` labels after validating it. */\n toLabels(plan: ColorPlan): string[] {\n const bytes = toArray(JSON.stringify(plan), 'utf8')\n if (bytes.length > MAX_PLAN_BYTES) throw new Error('BRC-207: plan exceeds 16 MiB')\n parsePlan(parseStrictJsonBytes(bytes, 'plan'))\n const hex = toHex(bytes)\n const count = Math.ceil(hex.length / CHUNK_HEX_LENGTH)\n return Array.from(\n { length: count },\n (_, i) =>\n `${COLOR_PLAN_LABEL_PREFIX}${i} ${count} ${hex.slice(i * CHUNK_HEX_LENGTH, (i + 1) * CHUNK_HEX_LENGTH)}`\n )\n },\n\n /** Reassembles the plan from its labels; undefined when no plan labels are present. */\n fromLabels(labels: readonly string[] | undefined): ColorPlan | undefined {\n const parts = (labels ?? []).filter(label => label.startsWith(COLOR_PLAN_LABEL_PREFIX))\n if (parts.length === 0) return undefined\n let count: number | undefined\n const chunks: string[] = []\n for (const label of parts) {\n const match = PLAN_LABEL.exec(label)\n if (match == null) throw new Error('BRC-207: invalid p color plan label')\n const index = Number(match[1])\n const partCount = Number(match[2])\n const hex = match[3]\n if (partCount > MAX_PLAN_PARTS) throw new Error('BRC-207: plan exceeds 16 MiB')\n if (count !== undefined && count !== partCount)\n throw new Error('BRC-207: inconsistent plan part counts')\n count = partCount\n if (index >= partCount) throw new Error('BRC-207: plan part index out of range')\n if (chunks[index] !== undefined) throw new Error('BRC-207: duplicate plan part')\n assertPlanChunk(hex, index, partCount)\n chunks[index] = hex\n }\n if (count === undefined || parts.length !== count) throw new Error('BRC-207: missing plan part')\n const hex = chunks.join('')\n if (hex.length > MAX_PLAN_BYTES * 2) throw new Error('BRC-207: plan exceeds 16 MiB')\n return parsePlan(parseStrictJsonBytes(toArray(hex, 'hex'), 'plan'))\n }\n}\n","/**\n * Runs `step` on each item strictly in order, as a `for … of` loop with `await` would: an item\n * starts only after the previous one has finished, and the first throw ends the run with that\n * same error. Checks rely on this, so the refusal reported is always the first one in order, and\n * steps that reserve outputs never race each other.\n */\nexport async function eachInOrder<T>(\n items: Iterable<T>,\n step: (item: T) => Promise<void> | void\n): Promise<void> {\n await Array.from(items).reduce<Promise<void>>(async (previous, item) => {\n // reduce invokes every callback up front, so nothing may run before this await.\n await previous\n await step(item)\n }, Promise.resolve())\n}\n\n/** {@link eachInOrder}, collecting each step's result in item order. */\nexport async function mapInOrder<T, R>(\n items: Iterable<T>,\n step: (item: T, index: number) => Promise<R> | R\n): Promise<R[]> {\n const results: R[] = []\n let index = 0\n await eachInOrder(items, async item => {\n results.push(await step(item, index++))\n })\n return results\n}\n","import { Transaction, type LockingScript, type LookupAnswer } from '@bsv/sdk'\n\nexport interface ListedOutput {\n outpoint: string\n lockingScript: LockingScript\n satoshis: number\n}\n\n/**\n * Reads a BRC-24 `output-list` answer to a `color-spendability` or `color-admission`\n * query. Every returned output must be one of the queried outpoints, at most once;\n * an unrelated, duplicate or malformed entry invalidates the whole answer.\n */\nexport function readOutputList(\n answer: LookupAnswer,\n queried: readonly string[]\n): Map<string, ListedOutput> {\n if (answer?.type !== 'output-list' || !Array.isArray(answer.outputs)) {\n throw new Error('BRC-207: overlay answer is not an output list')\n }\n const listed = new Map<string, ListedOutput>()\n const wanted = new Set(queried)\n for (const item of answer.outputs) {\n let transaction: Transaction\n try {\n transaction = Transaction.fromBEEF(item.beef, item.txid)\n } catch {\n throw new Error('BRC-207: overlay answer carries invalid BEEF')\n }\n const output = Number.isSafeInteger(item.outputIndex)\n ? transaction.outputs[item.outputIndex]\n : undefined\n if (output?.satoshis === undefined)\n throw new Error('BRC-207: overlay answer names a missing output')\n const outpoint = `${transaction.id('hex')}.${item.outputIndex}`\n if (!wanted.has(outpoint))\n throw new Error(`BRC-207: overlay answered an unrelated output ${outpoint}`)\n if (listed.has(outpoint)) throw new Error(`BRC-207: overlay answered ${outpoint} twice`)\n listed.set(outpoint, {\n outpoint,\n lockingScript: output.lockingScript,\n satoshis: output.satoshis\n })\n }\n return listed\n}\n","import type { LockingScript } from '@bsv/sdk'\nimport {\n Bsv21Token,\n isTokenShaped,\n OneColor,\n StrictCborLink,\n tryDecodeStrictCbor\n} from '@bsv/templates'\nimport type {\n Bsv21Envelope,\n Bsv21TokenDecoded,\n StrictCborMap,\n StrictCborValue\n} from '@bsv/templates'\nimport { parseAssetId, type Outpoint, type TokenRole } from './identifiers.js'\n\nexport interface TokenOutput {\n assetId: string\n role: TokenRole\n amount: bigint\n /** True for the asset's deploy output, whose key uses the `ISSUE` selector. */\n deploy: boolean\n /** BRC-162 binary, or BRC-161 JSON, which this module reads but never holds or creates. */\n encoding: 'brc162' | 'brc161'\n /** Set when the remainder after the prefix is exactly P2PKH. */\n pubKeyHash?: number[]\n /** A JSON output's operation; a `mint` is funded by an authority input, not by value inputs. */\n jsonOperation?: JsonOperation\n}\n\n/** The BRC-161 operations this module reads: value outputs, and the authority outputs. */\nexport type JsonOperation = 'transfer' | 'mint' | 'deploy+mint' | 'auth' | 'deploy+auth'\n\nconst PROFILE_ID = /^[a-z][a-z0-9+.-]*:[\\x21-\\x7e]+$/\n\n/** A decoded DAG-CBOR map, as opposed to an array, bytes, a link or a scalar. */\nfunction isCborMap(value: StrictCborValue | undefined): value is StrictCborMap {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array) &&\n !(value instanceof StrictCborLink)\n )\n}\n\n/** Reads `req` and `ext` from a payload; an absent, opaque or non-map payload has none. */\nfunction readPayloadMaps(payload: number[] | undefined): {\n req?: StrictCborMap\n ext?: StrictCborMap\n} {\n if (payload === undefined || payload.length === 0) return {}\n // Strict DAG-CBOR, as BRC-162 requires (L144); anything else is an opaque payload.\n const decoded = tryDecodeStrictCbor(payload)\n if (decoded === undefined) return {}\n const req = decoded.req\n const ext = decoded.ext\n if (req !== undefined && !isCborMap(req))\n throw new Error('BRC-207: malformed req in a BRC-162 payload')\n if (ext !== undefined && !isCborMap(ext))\n throw new Error('BRC-207: malformed ext in a BRC-162 payload')\n for (const profile of [...Object.keys(req ?? {}), ...Object.keys(ext ?? {})]) {\n if (profile.length > 200 || !PROFILE_ID.test(profile)) {\n throw new Error('BRC-207: invalid processing-profile identifier in a BRC-162 payload')\n }\n }\n return { req, ext }\n}\n\n/**\n * A valid BRC-162 output of an asset that requires processing profiles. BRC-207 has an\n * unsupported profile fail, never fall back, so readers that otherwise treat an unreadable\n * script as plain satoshis let this error through.\n */\nexport class UnsupportedProfileError extends Error {\n constructor() {\n super('BRC-207: the asset requires processing profiles this wallet does not support')\n this.name = 'UnsupportedProfileError'\n }\n}\n\n/**\n * Fails unless a payload declares no required processing profiles. This module supports\n * none, so a deploy `req` with entries, or a later output repeating a nonempty `req`, fails.\n */\nexport function assertNoRequiredProfiles(payload: number[] | undefined): void {\n const { req } = readPayloadMaps(payload)\n if (req !== undefined && Object.keys(req).length > 0) throw new UnsupportedProfileError()\n}\n\n/**\n * Reads a BRC-162 token output. Returns undefined for a script without the token\n * layout; throws for a token-shaped script that is invalid or unsupported here.\n */\nexport function readTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n if (!isTokenShaped(lockingScript)) return undefined\n let decoded: ReturnType<typeof OneColor.decode>\n try {\n decoded = OneColor.decode(lockingScript)\n } catch (error) {\n throw new Error(\n `BRC-207: ${outpoint.txid}.${outpoint.vout} is not a supported BRC-162 output (${(error as Error).message})`\n )\n }\n assertNoRequiredProfiles(decoded.payload)\n const deploy = decoded.role === 'deploy'\n if (deploy && outpoint.vout !== 0) throw new Error('BRC-207: a BRC-162 deploy must be output 0')\n return {\n assetId: deploy ? `${outpoint.txid}_0` : OneColor.tokenIdToString(decoded.tokenId!),\n role: decoded.amount === 0n ? 'authority' : 'value',\n amount: decoded.amount,\n deploy,\n encoding: 'brc162',\n pubKeyHash: decoded.restPubKeyHash\n }\n}\n\nconst BSV20_CONTENT_TYPE = 'application/bsv-20'\nconst MAX_UINT64 = (1n << 64n) - 1n\nconst VALUE_OPERATIONS = new Set<string>(['transfer', 'mint', 'deploy+mint'])\nconst JSON_AUTHORITY_OPERATIONS = new Set<string>(['auth', 'deploy+auth'])\n\n/**\n * Reads a BRC-161 JSON token output: a BRC-160 `ord` inscription of type `application/bsv-20`\n * anywhere in the script, located by `Bsv21Token`. Returns undefined for a script without such an\n * inscription. `transfer`, `mint` and `deploy+mint` outputs carry value (BRC-161 L262); `auth` and\n * `deploy+auth` are authority outputs of no value (L191-207); `burn` fails as unsupported, as does\n * a malformed inscription.\n */\nexport function readJsonTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n const malformed = (reason: string): Error =>\n new Error(\n `BRC-207: ${outpoint.txid}.${outpoint.vout} is a malformed BRC-161 inscription (${reason})`\n )\n let envelope: Bsv21Envelope | undefined\n try {\n envelope = Bsv21Token.envelope(lockingScript)\n } catch (error) {\n throw malformed((error as Error).message)\n }\n if (envelope === undefined || envelope.contentType !== BSV20_CONTENT_TYPE) return undefined\n let decoded: Bsv21TokenDecoded\n try {\n decoded = Bsv21Token.decode(lockingScript)\n } catch (error) {\n throw malformed((error as Error).message)\n }\n const op = decoded.op\n if (op === 'burn')\n throw new Error(`BRC-207: BRC-161 ${op} is an operation this module does not support`)\n const authority = JSON_AUTHORITY_OPERATIONS.has(op)\n if (!authority && !VALUE_OPERATIONS.has(op)) throw malformed('unknown op')\n const jsonOperation = op as JsonOperation\n const amount = BigInt(decoded.amt)\n if (amount > MAX_UINT64) throw malformed('amt is not a uint64')\n if (!authority && amount === 0n) throw malformed('amt must be positive')\n const role: TokenRole = authority ? 'authority' : 'value'\n if (op === 'deploy+mint' || op === 'deploy+auth') {\n return {\n assetId: `${outpoint.txid}_${outpoint.vout}`,\n role,\n amount,\n deploy: true,\n encoding: 'brc161',\n jsonOperation\n }\n }\n try {\n parseAssetId(decoded.id)\n } catch {\n throw malformed('id is not a token ID')\n }\n return { assetId: decoded.id, role, amount, deploy: false, encoding: 'brc161', jsonOperation }\n}\n\n/** Reads a token output in either encoding; binary wins when a script parses as both (BRC-162). */\nexport function readAnyTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n return readTokenOutput(lockingScript, outpoint) ?? readJsonTokenOutput(lockingScript, outpoint)\n}\n\n/**\n * True when the script is an asset's deploy: a BRC-162 binary deploy, whose `req` must be\n * empty here, or a BRC-161 JSON deploy+mint, which carries no processing profiles.\n */\nexport function isDeployOutput(lockingScript: LockingScript, outpoint: Outpoint): boolean {\n return readAnyTokenOutput(lockingScript, outpoint)?.deploy === true\n}\n","import {\n Beef,\n LockingScript,\n Signature,\n Spend,\n Transaction,\n TransactionSignature,\n UnlockingScript,\n type AtomicBEEF,\n type BasketInsertion,\n type CreateActionArgs,\n type CreateActionInput,\n type CreateActionOutput,\n type CreateSignatureArgs,\n type InternalizeActionArgs,\n type ListActionsArgs,\n type ListOutputsArgs,\n type ListOutputsResult,\n type SignActionArgs,\n type SignActionResult,\n type WalletCounterparty,\n type WalletInterface,\n type WalletOutput\n} from '@bsv/sdk'\nimport { hash160, hash256 } from '@bsv/sdk/primitives/Hash'\nimport Random from '@bsv/sdk/primitives/Random'\nimport { toArray, toBase64, toHex } from '@bsv/sdk/primitives/utils'\nimport { OneColor } from '@bsv/templates'\nimport {\n encryptMetadata,\n maybeDecryptMetadata,\n sdk as toolbox,\n type PermissionsModule,\n type PermissionsModuleAction,\n type PermissionsModuleNext,\n type PermissionsModuleRequest\n} from '@bsv/wallet-toolbox-client'\nimport {\n ColorPlan,\n type ColorOperationName,\n parseProfileData,\n parseRemittances,\n type ColorRemittance,\n COLOR_PLAN_LABEL_PREFIX\n} from './ColorPlan.js'\nimport {\n ASSETS_SELECTOR,\n assetBasket,\n COLOR_BASKET_NAMESPACE,\n COLOR_KEY_ID,\n colorProtocolID,\n colorTopic,\n DISCOVERY_TOPIC,\n ISSUE,\n outpointString,\n parseAssetBasket,\n parseAssetId,\n parseAssetSelector,\n parseBalanceSelector,\n parseColorProtocolID,\n parseOutpoint,\n validateIdentityKey,\n validateRemittanceString,\n type TokenRole\n} from './identifiers.js'\nimport { eachInOrder, mapInOrder } from './inOrder.js'\nimport { readOutputList } from './overlay.js'\nimport {\n exactMembers,\n jsonByteArray,\n jsonObject,\n jsonUint32,\n parseStrictJsonBytes\n} from './strictJson.js'\nimport {\n isDeployOutput,\n readAnyTokenOutput,\n readJsonTokenOutput,\n readTokenOutput,\n UnsupportedProfileError,\n type TokenOutput\n} from './tokenOutputs.js'\nimport type {\n ColorOverlayProvider,\n ColorPermissionModuleOptions,\n ColorTokenAccessHandler\n} from './types.js'\n\nconst UNLOCKING_SCRIPT_LENGTH = 108\nconst TOKEN_CARRIER_SATOSHIS = 1\nconst DEFAULT_SIGHASH = TransactionSignature.SIGHASH_ALL | TransactionSignature.SIGHASH_FORKID\nconst MAX_ENVELOPE_BYTES = 16 * 1024 * 1024\nconst MAX_RECEIPT_INSTRUCTION_BYTES = 1000\nconst LIST_PAGE_LIMIT = 10_000\nconst SUBMIT_ATTEMPTS = 3\nconst NOSEND_EXPIRY_LABEL_PREFIX = 'p nosend expiry '\nconst STATE_TAG_PREFIX = 'color_state_'\nconst UTF8_ENCODER = new TextEncoder()\n\n/** The derivation tuple a managed output's key was created with; `assetId` is `ISSUE` for a deploy. */\nexport interface Custody {\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n senderIdentityKey: string\n}\n\nexport interface SourceOutput {\n outpoint: string\n lockingScript: LockingScript\n satoshis: number\n}\n\n/** A basket output that may be selected, read from its locking script before any custody is read. */\ninterface Candidate extends SourceOutput {\n token: TokenOutput\n amount: bigint\n customInstructions: string\n}\n\nexport interface ManagedInput extends SourceOutput {\n assetId: string\n role: TokenRole\n amount: bigint\n custody: Custody\n}\n\ntype InventoryState = 'available' | 'reserved'\n\n/** Runs an SDK parser on untrusted input, prefixing its failure as a BRC-207 error. */\nfunction parsed<T>(label: string, parse: () => T): T {\n try {\n return parse()\n } catch (error) {\n throw new Error(`BRC-207: ${label} is invalid (${(error as Error).message})`)\n }\n}\n\nfunction sumAmounts(inputs: ReadonlyArray<{ amount: bigint }>): bigint {\n return inputs.reduce((total, input) => total + input.amount, 0n)\n}\n\nfunction inputOutpoint(input: Transaction['inputs'][number]): string {\n const txid = input.sourceTXID ?? input.sourceTransaction?.id('hex')\n if (txid === undefined) throw new Error('BRC-207: transaction input has no source transaction ID')\n return outpointString(txid, input.sourceOutputIndex)\n}\n\nfunction custodyOf(remittance: ColorRemittance): Custody {\n const { assetId, derivationPrefix, derivationSuffix, senderIdentityKey } = remittance\n return { assetId, derivationPrefix, derivationSuffix, senderIdentityKey }\n}\n\nfunction tokenInputs(inputs: readonly ManagedInput[]): CreateActionInput[] {\n return inputs.map(input => ({\n outpoint: input.outpoint,\n unlockingScriptLength: UNLOCKING_SCRIPT_LENGTH,\n inputDescription: 'BRC-207 token input'\n }))\n}\n\nfunction custodyInstructions(custody: Custody): string {\n return JSON.stringify({ version: 1, ...custody })\n}\n\n/** Parses the receipt-format custody JSON stored in, or supplied as, an output's custom instructions. */\nfunction parseCustody(text: string, maxBytes: number | undefined, label: string): Custody {\n const bytes = UTF8_ENCODER.encode(text)\n if (maxBytes !== undefined && bytes.length > maxBytes)\n throw new Error(`BRC-207: ${label} exceeds ${maxBytes} bytes`)\n const object = jsonObject(parseStrictJsonBytes(bytes, label), label)\n exactMembers(\n object,\n ['version', 'assetId', 'derivationPrefix', 'derivationSuffix', 'senderIdentityKey'],\n ['profileData'],\n label\n )\n if (object.version !== 1) throw new Error(`BRC-207: ${label} version must be 1`)\n const profileData = parseProfileData(object.profileData, `${label}.profileData`)\n if (profileData !== undefined && Object.keys(profileData).length > 0) {\n throw new Error(`BRC-207: ${label}.profileData names a profile the asset does not require`)\n }\n return {\n assetId: parseAssetSelector(object.assetId),\n derivationPrefix: validateRemittanceString(\n object.derivationPrefix,\n `${label}.derivationPrefix`\n ),\n derivationSuffix: validateRemittanceString(\n object.derivationSuffix,\n `${label}.derivationSuffix`\n ),\n senderIdentityKey: validateIdentityKey(object.senderIdentityKey, `${label}.senderIdentityKey`)\n }\n}\n\n/** True when a custody selector names the output's asset: `ISSUE` exactly for its deploy. */\nfunction selectsAsset(selector: string, token: TokenOutput): boolean {\n return selector === ISSUE ? token.deploy : !token.deploy && selector === token.assetId\n}\n\n/** One asset's token units and authority outputs on one side of a transaction. */\nexport interface Holding {\n value: bigint\n authority: number\n /** The part of `value` in BRC-161 transfer outputs, which only value inputs can fund. */\n jsonValue?: bigint\n}\n\n/** What the caller's explicit inputs contribute to one asset, and how much of it is foreign. */\ninterface ExplicitHolding extends Holding {\n foreignValue: bigint\n foreignAuthority: number\n}\n\n/** The caller's explicit inputs and what they contribute per asset. */\ninterface ExplicitInputs {\n inputs: CreateActionInput[]\n managed: ManagedInput[]\n holdings: Map<string, ExplicitHolding>\n}\n\n/** The requested outputs' token totals per existing asset, the deploy, and the outputs that leave the wallet. */\ninterface PlannedOutputs {\n holdings: Map<string, Holding>\n deploy?: { operation: ColorOperationName }\n destinations: Array<{\n outputIndex: number\n assetId: string\n role: TokenRole\n amount: string\n lockingScript: string\n }>\n}\n\n/** One existing asset's funding: its selected inputs, token change and resulting outputs. */\ninterface AssetFunding {\n assetId: string\n selected: ManagedInput[]\n change: bigint\n outputs: Holding\n}\n\nconst AUTHORITY_OPERATIONS: readonly ColorOperationName[] = [\n 'authority-split',\n 'authority-combine',\n 'authority-transfer',\n 'authority-end'\n]\n\nfunction holding<T extends Holding>(totals: Map<string, T>, assetId: string, empty: () => T): T {\n let entry = totals.get(assetId)\n if (entry === undefined) {\n entry = empty()\n totals.set(assetId, entry)\n }\n return entry\n}\n\nfunction emptyHolding(): Holding {\n return { value: 0n, authority: 0 }\n}\n\nfunction emptyExplicitHolding(): ExplicitHolding {\n return { value: 0n, authority: 0, foreignValue: 0n, foreignAuthority: 0 }\n}\n\n/** The BRC-207 authority operation for a transaction's authority input and output counts. */\nexport function authorityOperation(inputs: number, outputs: number): ColorOperationName {\n if (outputs === 0) return 'authority-end'\n if (outputs < inputs) return 'authority-combine'\n return outputs === inputs ? 'authority-transfer' : 'authority-split'\n}\n\n/** Authority inputs to select for a declared authority operation when the caller supplies none. */\nfunction authorityInputsFor(operation: ColorOperationName, outputs: number): number {\n if (operation === 'authority-transfer') return outputs\n if (operation === 'authority-combine') return outputs + 1\n return 1\n}\n\n/**\n * The operations BRC-207 requires for one existing asset: value inputs fund value outputs\n * first, the rest of the inputs is burned and the rest of the outputs is minted.\n */\nexport function requiredOperations(inputs: Holding, outputs: Holding): ColorOperationName[] {\n if (inputs.authority === 0 && outputs.authority > 0)\n throw new Error('BRC-207: an authority output needs an authority input of the same asset')\n if ((outputs.jsonValue ?? 0n) > inputs.value)\n throw new Error(\n 'BRC-207: BRC-161 transfer outputs exceed the value inputs; an authority cannot fund them'\n )\n const { transferred, burned, minted } = supplyChange(inputs, outputs)\n if (minted > 0n && inputs.authority === 0)\n throw new Error('BRC-207: token outputs exceed the authenticated input balance')\n const operations: ColorOperationName[] = []\n if (transferred > 0n) operations.push('transfer')\n if (burned > 0n) operations.push('burn')\n if (minted > 0n) operations.push('mint')\n if (inputs.authority > 0) operations.push(authorityOperation(inputs.authority, outputs.authority))\n return operations\n}\n\nfunction declaredOperations(plan: ColorPlan, assetId: string): Set<ColorOperationName> {\n return new Set(\n plan.operations.filter(operation => operation.assetId === assetId).map(op => op.operation)\n )\n}\n\n/** Fails unless the plan declares exactly the operations the asset's transaction requires. */\nfunction assertOperations(plan: ColorPlan, assetId: string, required: ColorOperationName[]): void {\n const declared = declaredOperations(plan, assetId)\n if (declared.size !== required.length || required.some(operation => !declared.has(operation))) {\n throw new Error(\n `BRC-207: ${assetId} requires the operations [${required.join(', ')}] but the plan declares [${[...declared].join(', ')}]`\n )\n }\n}\n\n/** Supply accounting: value inputs fund value outputs first; the rest is burned or minted. */\nexport function supplyChange(\n inputs: Holding,\n outputs: Holding\n): { transferred: bigint; burned: bigint; minted: bigint } {\n const transferred = outputs.value < inputs.value ? outputs.value : inputs.value\n return {\n transferred,\n burned: inputs.value - transferred,\n minted: outputs.value - transferred\n }\n}\n\n/**\n * What the user approves for a funded action: every asset leg, with this wallet's and foreign\n * inputs, kept and outgoing outputs and the supply change; satoshi totals and fee; the\n * signatures the module releases; and the lock time.\n */\nexport function actionConsent(\n plan: ColorPlan,\n createArgs: CreateActionArgs,\n tx: Transaction,\n tokens: TransactionTokens,\n managed: readonly ManagedInput[],\n scopes: ReadonlyMap<string, number>\n): Record<string, unknown> {\n const requested = createArgs.outputs ?? []\n const kept = (index: number): boolean =>\n requested[index]?.basket?.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true ||\n plan.ownedOutputs.some(remittance => remittance.outputIndex === index)\n return {\n type: 'color_send',\n handoff: (createArgs.labels ?? []).some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX)),\n ...transactionConsent(\n tx,\n tokens,\n managed,\n kept,\n vout => vout < requested.length && !kept(vout),\n managed.map(input => ({\n outpoint: input.outpoint,\n inputIndex: tx.inputs.findIndex(candidate => inputOutpoint(candidate) === input.outpoint),\n sighashType: scopes.get(input.outpoint) ?? DEFAULT_SIGHASH\n })),\n plan.ownedOutputs.some(remittance => remittance.outputIndex === 0)\n )\n }\n}\n\nexport interface ReleasedSignature {\n outpoint: string\n inputIndex: number\n sighashType: number\n}\n\n/**\n * The facts the user approves for any transaction this wallet signs token inputs of, whether the\n * wallet funded it or an app built it: every asset leg with this wallet's (`own`) and foreign\n * inputs, kept and outgoing outputs and the supply change; the destinations; satoshi totals and\n * fee; the signatures released; and the lock time.\n */\nexport function transactionConsent(\n tx: Transaction,\n tokens: TransactionTokens,\n own: ReadonlyArray<{ assetId: string; role: TokenRole; amount: bigint }>,\n kept: (vout: number) => boolean,\n destination: (vout: number) => boolean,\n signatures: ReleasedSignature[],\n deployOwned: boolean\n): Record<string, unknown> {\n const txid = tx.id('hex')\n const outputs = tx.outputs.map((output, vout) => ({\n vout,\n token: readSentToken(output.lockingScript, { txid, vout }),\n satoshis: output.satoshis ?? 0\n }))\n const assets = [...new Set([...tokens.inputs.keys(), ...tokens.outputs.keys()])].map(assetId => {\n const ownInputs = own.filter(input => input.assetId === assetId)\n const inputs = tokens.inputs.get(assetId) ?? emptyHolding()\n const all = tokens.outputs.get(assetId) ?? emptyHolding()\n const keptOutputs = outputs.filter(\n output => output.token?.assetId === assetId && !output.token.deploy && kept(output.vout)\n )\n const { transferred, burned, minted } = supplyChange(inputs, all)\n return {\n assetId,\n operations: requiredOperations(inputs, all),\n inputAmount: sumAmounts(ownInputs).toString(),\n foreignAmount: (inputs.value - sumAmounts(ownInputs)).toString(),\n authorityInputs: ownInputs.filter(input => input.role === 'authority').length,\n foreignAuthorityInputs:\n inputs.authority - ownInputs.filter(input => input.role === 'authority').length,\n keptAmount: sumAmounts(keptOutputs.map(output => output.token!)).toString(),\n keptAuthorities: keptOutputs.filter(output => output.token!.role === 'authority').length,\n outgoingAmount: (all.value - sumAmounts(keptOutputs.map(output => output.token!))).toString(),\n outgoingAuthorities:\n all.authority - keptOutputs.filter(output => output.token!.role === 'authority').length,\n transferred: transferred.toString(),\n burned: burned.toString(),\n minted: minted.toString()\n }\n })\n const inputSatoshis = tx.inputs.reduce(\n (total, input) =>\n total + (input.sourceTransaction!.outputs[input.sourceOutputIndex].satoshis ?? 0),\n 0\n )\n const outputSatoshis = outputs.reduce((total, output) => total + output.satoshis, 0)\n return {\n ...(tokens.deploy === undefined\n ? {}\n : {\n deploy: {\n operation: deployOperation(tokens.deploy),\n amount: tokens.deploy.amount.toString(),\n owned: deployOwned\n }\n }),\n assets,\n destinations: outputs\n .filter(output => destination(output.vout))\n .map(output => ({\n outputIndex: output.vout,\n satoshis: output.satoshis,\n lockingScript: tx.outputs[output.vout].lockingScript.toHex(),\n ...(output.token === undefined\n ? {}\n : {\n assetId: output.token.deploy ? ISSUE : output.token.assetId,\n role: output.token.role,\n amount: output.token.amount.toString()\n })\n })),\n satoshis: {\n inputs: inputSatoshis,\n outputs: outputSatoshis,\n fee: inputSatoshis - outputSatoshis\n },\n signatures,\n lockTime: tx.lockTime\n }\n}\n\n/** Plan and action features this module version does not implement. */\nfunction assertPlanSupported(plan: ColorPlan, args: CreateActionArgs): void {\n // A plan's ownedOutputs, inputPositions and changePositions, and the facts the user approves,\n // all name requested output indices; storage shuffles them when randomizeOutputs is true.\n if (args.options?.randomizeOutputs !== false) {\n throw new Error('BRC-207: a p color plan requires options.randomizeOutputs false')\n }\n if (Object.keys(plan.profileData ?? {}).length > 0) {\n throw new Error('BRC-207: plan.profileData is not supported')\n }\n const handoff = (args.labels ?? []).some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX))\n // A signed deploy is filed in its asset basket through internalizeAction, which would end a\n // noSend transaction's lifecycle; the deploy is a broadcast action.\n if (plan.assets.includes(ISSUE) && (args.options?.noSend === true || handoff)) {\n throw new Error('BRC-207: a deploy cannot be a noSend action')\n }\n // As in BTMS, a token action completes with its overlay submission. The one deferred flow is\n // the BRC-177 handoff, whose receiver submits; a plain noSend action later sent with sendWith\n // would never reach the token overlay, as the manager gives modules no sendWith hook.\n if (args.options?.noSend === true && !handoff) {\n throw new Error('BRC-207: noSend token actions require a BRC-177 p nosend expiry label')\n }\n // Storage adds satoshi change while funding, after this module returns: it appends the requested\n // outputs, then any storage commission output, then change, and reports neither position.\n if (plan.changePositions.some(position => position.assetId === null)) {\n throw new Error(\n 'BRC-207: satoshi change positions are not supported: the wallet does not position satoshi change'\n )\n }\n}\n\n/** Explicit inputs in their final places, with the module's token inputs in the remaining slots. */\nfunction orderInputs(\n explicit: readonly CreateActionInput[],\n added: readonly CreateActionInput[],\n positions: ColorPlan['inputPositions']\n): CreateActionInput[] {\n const all = [...explicit, ...added]\n if (positions.length === 0) return all\n const slots = new Map<number, CreateActionInput>()\n for (const { outpoint, index } of positions) {\n const input = explicit.find(candidate => candidate.outpoint === outpoint)\n if (input === undefined)\n throw new Error(\n 'BRC-207: plan.inputPositions names an outpoint that is not an explicit input'\n )\n if (index >= all.length || slots.has(index))\n throw new Error('BRC-207: plan.inputPositions cannot be satisfied')\n slots.set(index, input)\n }\n const placed = new Set(slots.values())\n const rest = all.filter(input => !placed.has(input))\n return Array.from({ length: all.length }, (_, index) => slots.get(index) ?? rest.shift()!)\n}\n\n/**\n * Requested outputs at their own indices, then token change, each asset's change at its pinned\n * index if it has one. A change position cannot displace a requested output.\n */\nfunction placeChange(\n outputs: readonly CreateActionOutput[],\n changes: ReadonlyArray<{ assetId: string; output: CreateActionOutput }>,\n positions: ColorPlan['changePositions']\n): CreateActionOutput[] {\n const slots = new Map<number, CreateActionOutput>()\n for (const { assetId, index } of positions) {\n if (index < outputs.length)\n throw new Error('BRC-207: plan.changePositions conflict with the requested outputs')\n const change = changes.find(candidate => candidate.assetId === assetId)\n if (change === undefined || index >= outputs.length + changes.length)\n throw new Error('BRC-207: plan.changePositions cannot be satisfied')\n slots.set(index, change.output)\n }\n const placed = new Set(slots.values())\n const rest = changes.map(change => change.output).filter(output => !placed.has(output))\n return [\n ...outputs,\n ...Array.from(\n { length: changes.length },\n (_, offset) => slots.get(outputs.length + offset) ?? rest.shift()!\n )\n ]\n}\n\n/**\n * Reads a token in a transaction the wallet sends: BRC-162 first, then BRC-161 JSON, which the\n * module accounts for but never holds or creates.\n */\nexport function readSentToken(\n lockingScript: LockingScript,\n outpoint: ReturnType<typeof parseOutpoint>\n): TokenOutput | undefined {\n return tryReadTokenOutput(lockingScript, outpoint) ?? readJsonTokenOutput(lockingScript, outpoint)\n}\n\n/**\n * Token inputs of `tx` other than those in `except`, read from their source transactions. With\n * `json`, BRC-161 JSON inputs are read too.\n */\nexport function tokenSources(\n tx: Transaction,\n managed: ReadonlySet<string>,\n json = false\n): Array<SourceOutput & { assetId: string; token: TokenOutput }> {\n const read = json ? readSentToken : tryReadTokenOutput\n return tx.inputs.flatMap(input => {\n const outpoint = inputOutpoint(input)\n const source = input.sourceTransaction?.outputs[input.sourceOutputIndex]\n if (managed.has(outpoint) || source?.satoshis === undefined) return []\n const token = read(source.lockingScript, parseOutpoint(outpoint))\n if (token === undefined) return []\n return [\n {\n outpoint,\n lockingScript: source.lockingScript,\n satoshis: source.satoshis,\n assetId: token.assetId,\n token\n }\n ]\n })\n}\n\n/**\n * The existing assets among a transaction's token inputs (read from `inputs`, which carries their\n * sources) and outputs, and whether output 0 is a deploy: the topics it is submitted to.\n */\nexport function submissionAssets(\n tx: Transaction,\n inputs: Transaction = tx\n): { assetIds: string[]; deploy: boolean } {\n const txid = tx.id('hex')\n const outputs = tx.outputs.map((output, vout) =>\n readSentToken(output.lockingScript, { txid, vout })\n )\n const assetIds = new Set([\n ...tokenSources(inputs, new Set(), true).map(input => input.assetId),\n ...outputs.flatMap(token => (token === undefined || token.deploy ? [] : [token.assetId]))\n ])\n return { assetIds: [...assetIds], deploy: outputs[0]?.deploy === true }\n}\n\n/** Runs one input's unlocking script against its source output; throws when it does not unlock. */\nexport function assertUnlocks(tx: Transaction, inputIndex: number): void {\n const input = tx.inputs[inputIndex]\n const source = input.sourceTransaction?.outputs[input.sourceOutputIndex]\n if (source?.satoshis === undefined || input.unlockingScript === undefined)\n throw new Error(`BRC-207: transaction input ${inputIndex} lacks its source or unlocking script`)\n new Spend({\n sourceTXID: input.sourceTransaction!.id('hex'),\n sourceOutputIndex: input.sourceOutputIndex,\n sourceSatoshis: source.satoshis,\n lockingScript: source.lockingScript,\n transactionVersion: tx.version,\n otherInputs: tx.inputs.filter((_, index) => index !== inputIndex),\n outputs: tx.outputs,\n inputIndex,\n unlockingScript: input.unlockingScript,\n inputSequence: input.sequence ?? 0xffffffff,\n lockTime: tx.lockTime\n }).validate()\n}\n\nfunction addToken(totals: Map<string, Holding>, token: TokenOutput): void {\n const entry = holding(totals, token.assetId, emptyHolding)\n if (token.role === 'value') entry.value += token.amount\n else entry.authority += 1\n if (token.encoding === 'brc161' && token.jsonOperation !== 'mint')\n entry.jsonValue = (entry.jsonValue ?? 0n) + token.amount\n}\n\n/** A foreign input's source output from the caller's inputBEEF, if it is there. */\nfunction foreignSource(beef: Beef | undefined, outpoint: string): SourceOutput | undefined {\n const { txid, vout } = parseOutpoint(outpoint)\n const output = beef?.findTxid(txid)?.tx?.outputs[vout]\n if (output?.satoshis === undefined) return undefined\n return { outpoint, lockingScript: output.lockingScript, satoshis: output.satoshis }\n}\n\n/** A transaction's token inputs and outputs per existing asset, and its deploy output. */\nexport interface TransactionTokens {\n consumed: Array<SourceOutput & { assetId: string; token: TokenOutput }>\n inputs: Map<string, Holding>\n outputs: Map<string, Holding>\n deploy?: TokenOutput\n}\n\n/**\n * Reads every input's source and every output; an input without its source fails. With `json`,\n * for a transaction the wallet sends, BRC-161 JSON inputs and outputs are read too.\n */\nexport function transactionTokens(tx: Transaction, json = false): TransactionTokens {\n tx.inputs.forEach((input, index) => {\n if (input.sourceTransaction === undefined)\n throw new Error(`BRC-207: input ${index} has no source transaction to authenticate`)\n })\n const txid = tx.id('hex')\n const consumed = tokenSources(tx, new Set(), json)\n const inputs = new Map<string, Holding>()\n for (const source of consumed) addToken(inputs, source.token)\n const outputs = new Map<string, Holding>()\n let deploy: TokenOutput | undefined\n tx.outputs.forEach((output, vout) => {\n const token = json\n ? readAnyTokenOutput(output.lockingScript, { txid, vout })\n : readTokenOutput(output.lockingScript, { txid, vout })\n if (token?.deploy === true && token.encoding === 'brc161')\n throw new Error('BRC-207: a new issuance must use BRC-162')\n if (token?.deploy === true) deploy = token\n else if (token !== undefined) addToken(outputs, token)\n })\n return { consumed, inputs, outputs, deploy }\n}\n\nexport function deployOperation(token: TokenOutput): ColorOperationName {\n return token.amount > 0n ? 'deploy-fixed' : 'deploy-authority'\n}\n\n/** Fails unless the plan's operations and assets are exactly what the transaction performs. */\nexport function assertTransactionOperations(plan: ColorPlan, tokens: TransactionTokens): void {\n const assetIds = new Set([...tokens.inputs.keys(), ...tokens.outputs.keys()])\n assertPlanAssets(plan, new Set([...assetIds, ...(tokens.deploy === undefined ? [] : [ISSUE])]))\n if (tokens.deploy !== undefined) assertOperations(plan, ISSUE, [deployOperation(tokens.deploy)])\n for (const assetId of assetIds)\n assertOperations(\n plan,\n assetId,\n requiredOperations(\n tokens.inputs.get(assetId) ?? emptyHolding(),\n tokens.outputs.get(assetId) ?? emptyHolding()\n )\n )\n}\n\n/** The sighash type for each managed input; an override must name one the module signs. */\nexport function sighashScopes(plan: ColorPlan, managed: ReadonlySet<string>): Map<string, number> {\n const scopes = new Map<string, number>()\n for (const { outpoint, sighashType } of plan.sighashTypes) {\n if (!managed.has(outpoint))\n throw new Error('BRC-207: plan.sighashTypes names an input this wallet does not sign')\n scopes.set(outpoint, sighashType)\n }\n return scopes\n}\n\n/** The plan names exactly the assets among the action's token inputs and outputs. */\nexport function assertPlanAssets(plan: ColorPlan, involved: ReadonlySet<string>): void {\n if (plan.assets.length !== involved.size || plan.assets.some(assetId => !involved.has(assetId)))\n throw new Error('BRC-207: plan.assets must name exactly the assets the action moves')\n}\n\n/** Largest amount first. */\n/**\n * Chooses unrejected candidates, in their order, until they cover `target`: units for value, a count\n * for authority. Undefined when they cannot.\n */\nfunction chooseCandidates(\n candidates: readonly Candidate[],\n rejected: ReadonlySet<string>,\n role: TokenRole,\n target: bigint\n): Candidate[] | undefined {\n const chosen: Candidate[] = []\n let total = 0n\n for (const candidate of candidates) {\n if (total >= target) break\n if (rejected.has(candidate.outpoint)) continue\n chosen.push(candidate)\n total += role === 'value' ? candidate.amount : 1n\n }\n return total < target ? undefined : chosen\n}\n\nfunction byAmountDescending(a: { amount: bigint }, b: { amount: bigint }): number {\n if (a.amount === b.amount) return 0\n return a.amount > b.amount ? -1 : 1\n}\n\ninterface InventoryRecord {\n output: WalletOutput\n assetId: string\n source: SourceOutput\n}\n\ninterface InventoryView {\n record: InventoryRecord\n state: InventoryState\n tags: string[]\n}\n\n/** The token outputs of a namespace listing. */\nfunction inventoryRecords(outputs: WalletOutput[], beef: Beef | undefined): InventoryRecord[] {\n const records: InventoryRecord[] = []\n for (const output of outputs) {\n const outpoint = parseOutpoint(output.outpoint)\n const lockingScript =\n beef === undefined\n ? LockingScript.fromHex(output.lockingScript ?? '')\n : beef.findTxid(outpoint.txid)?.tx?.outputs[outpoint.vout]?.lockingScript\n if (lockingScript === undefined) continue\n let token: TokenOutput | undefined\n try {\n token = tryReadTokenOutput(lockingScript, outpoint)\n } catch {\n continue // an unsupported asset's outputs are left out of the inventory\n }\n if (token === undefined) continue\n records.push({\n output,\n assetId: token.assetId,\n source: { outpoint: output.outpoint, lockingScript, satoshis: output.satoshis }\n })\n }\n return records\n}\n\n/** Reserved by a pending action, else available. Wallet state only; the overlay is not consulted. */\nfunction inventoryState(record: InventoryRecord): InventoryState {\n return record.output.spendable ? 'available' : 'reserved'\n}\n\n/**\n * A BRC-162 token output, or undefined for a script that is not one. A token-shaped script that\n * does not decode is an ordinary satoshi output; a valid output of an asset that requires\n * processing profiles is a token this wallet cannot evaluate, and fails (BRC-207 L92-95).\n */\nexport function tryReadTokenOutput(\n lockingScript: LockingScript,\n outpoint: ReturnType<typeof parseOutpoint>\n): TokenOutput | undefined {\n try {\n return readTokenOutput(lockingScript, outpoint)\n } catch (error) {\n if (error instanceof UnsupportedProfileError) throw error\n return undefined\n }\n}\n\n/** A record with its stored tags and the computed state tag in place of any stored one. */\nfunction inventoryView(record: InventoryRecord): InventoryView {\n const state = inventoryState(record)\n const tags = [\n ...(record.output.tags ?? []).filter(tag => !tag.startsWith(STATE_TAG_PREFIX)),\n `${STATE_TAG_PREFIX}${state}`\n ]\n return { record, state, tags }\n}\n\n/** A BEEF holding only the transactions of the returned page. */\nfunction pageBeef(beef: Beef, page: readonly InventoryView[]): number[] {\n const result = new Beef()\n for (const txid of new Set(page.map(view => parseOutpoint(view.record.output.outpoint).txid))) {\n const tx = beef.findAtomicTransaction(txid)\n if (tx !== undefined) result.mergeTransaction(tx)\n }\n return result.toBinary()\n}\n\nfunction matchesTags(\n tags: readonly string[],\n filter: readonly string[],\n mode: ListOutputsArgs['tagQueryMode']\n): boolean {\n if (filter.length === 0) return true\n return mode === 'all'\n ? filter.every(tag => tags.includes(tag))\n : filter.some(tag => tags.includes(tag))\n}\n\n/**\n * BRC-207 `color` wallet module for BRC-162 fungible tokens.\n *\n * Register it as `permissionModules: { color }` on a WalletPermissionsManager. It\n * verifies and accepts receipts, funds token sends from its per-asset baskets and\n * signs their inputs during `signAction`, signs app-built transactions through\n * `createSignature`, and answers the `p color assets` and `p color balance` views.\n */\nexport class ColorPermissionModule implements PermissionsModule {\n protected readonly wallet: WalletInterface\n protected readonly provider: ColorOverlayProvider\n protected readonly requestTokenAccess: ColorTokenAccessHandler\n /** BRC-205 attribute for BRC-207's Discovery section: this module implements revision 5. */\n readonly capabilities: Readonly<Record<string, string>> = { 'brc207-color': '5' }\n /** Outputs a send in progress has selected, so a concurrent send does not select them too. */\n protected readonly selected = new Set<string>()\n protected readonly supportedAssets = new Map<string, Promise<void>>()\n protected identityKey?: Promise<string>\n\n constructor(options: ColorPermissionModuleOptions) {\n if (options?.wallet == null) throw new TypeError('BRC-207: wallet is required')\n if (options.provider == null) throw new TypeError('BRC-207: provider is required')\n if (typeof options.requestTokenAccess !== 'function') {\n throw new TypeError('BRC-207: requestTokenAccess is required')\n }\n this.wallet = options.wallet\n this.provider = options.provider\n this.requestTokenAccess = options.requestTokenAccess\n }\n\n /** Clears in-memory selections and asset checks. */\n dispose(): void {\n this.selected.clear()\n this.supportedAssets.clear()\n this.identityKey = undefined\n }\n\n /** Protocol- and basket-routed calls: key and signature operations and the read views. */\n async handleRequest(\n req: PermissionsModuleRequest,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n switch (req.method) {\n case 'getPublicKey':\n case 'verifySignature':\n this.parseKeyArgs(req.args as { protocolID?: unknown; keyID?: unknown })\n return await next(req.args)\n case 'createSignature':\n return await this.createSignature(req.args as CreateSignatureArgs, req.originator, next)\n case 'listOutputs':\n return await this.listOutputs(req.args as ListOutputsArgs, req.originator, next)\n case 'relinquishOutput': {\n const { basket, output } = req.args as { basket: string; output: string }\n const target = parseAssetBasket(basket)\n if (target === undefined) {\n throw new Error('BRC-207: only per-asset baskets hold outputs that can be relinquished')\n }\n await this.approve(req.originator, {\n type: 'color_relinquish',\n assetId: target.assetId,\n role: target.role,\n outpoint: output\n })\n return await next(req.args)\n }\n default:\n throw new Error(`BRC-207: ${req.method} is not available in the p color namespace`)\n }\n }\n\n /** Label- and basket-routed actions. */\n async onRequest(req: PermissionsModuleRequest): Promise<{ args: object }> {\n switch (req.method) {\n case 'createAction':\n return { args: await this.createAction(req.args as CreateActionArgs, req.originator) }\n case 'signAction':\n return {\n args: await this.signAction(req.args as SignActionArgs, req.action, req.originator)\n }\n case 'internalizeAction': {\n const args = req.args as InternalizeActionArgs\n await this.internalizeAction(args, req.originator)\n return { args }\n }\n case 'listActions': {\n const args = req.args as ListActionsArgs\n await this.authorizeRead(req.originator, {\n labels: (args.labels ?? []).filter(label => label.startsWith(COLOR_BASKET_NAMESPACE)),\n seekPermission: args.seekPermission !== false\n })\n return { args }\n }\n default:\n throw new Error(`BRC-207: ${req.method} is not available in the p color namespace`)\n }\n }\n\n async onResponse(\n res: unknown,\n context: { method: string; originator: string; action?: PermissionsModuleAction }\n ): Promise<unknown> {\n if (context.method === 'signAction' && context.action !== undefined) {\n await this.fileDeploy(res as SignActionResult, context.action, context.originator)\n // A noSend action is always a BRC-177 handoff (createAction refuses any other): its\n // receiver submits it.\n if (!context.action.noSend)\n await this.submitSigned(res as SignActionResult, context.action.transaction)\n }\n return res\n }\n\n /**\n * Files a signed deploy this wallet keeps in its asset's value or authority basket, now that\n * the asset ID is final. The deploy keeps its `ISSUE` key; its asset overlay must admit it\n * before it can be spent.\n */\n protected async fileDeploy(\n result: SignActionResult,\n action: PermissionsModuleAction,\n originator: string\n ): Promise<void> {\n if (result?.tx === undefined) return\n const tx = Transaction.fromAtomicBEEF(result.tx)\n const txid = tx.id('hex')\n const deploy = tryReadTokenOutput(tx.outputs[0]?.lockingScript ?? new LockingScript(), {\n txid,\n vout: 0\n })\n const owned = ColorPlan.fromLabels(action.createArgs?.labels)?.ownedOutputs.some(\n remittance => remittance.outputIndex === 0 && remittance.assetId === ISSUE\n )\n if (deploy?.deploy !== true || owned !== true) return\n // The underlying wallet merges the insertion into its own signed transaction: the basket and\n // the custody (encrypted at createAction) are assigned and the transaction's status is kept.\n const customInstructions = action.createArgs?.outputs?.[0]?.customInstructions\n await this.wallet.internalizeAction(\n {\n tx: result.tx,\n description: 'File the deployed asset',\n outputs: [\n {\n outputIndex: 0,\n protocol: 'basket insertion',\n insertionRemittance: {\n basket: assetBasket(deploy.assetId, deploy.role),\n ...(customInstructions === undefined ? {} : { customInstructions })\n }\n }\n ]\n },\n originator\n )\n }\n\n /* ----------------------------------------------------------------------\n * Receive\n * ---------------------------------------------------------------------- */\n\n /** Verifies every `p color` receipt; the caller must already have submitted the transaction. */\n protected async internalizeAction(\n args: InternalizeActionArgs,\n originator: string\n ): Promise<void> {\n if ((args.labels ?? []).some(label => label.startsWith(`${COLOR_BASKET_NAMESPACE} `))) {\n throw new Error('BRC-207: p color labels have no meaning in internalizeAction')\n }\n const tx = parsed('the received transaction', () => Transaction.fromAtomicBEEF(args.tx))\n const receipts = args.outputs.flatMap(output => {\n const remittance = output.insertionRemittance\n return output.protocol === 'basket insertion' &&\n remittance?.basket.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true\n ? [{ outputIndex: output.outputIndex, remittance }]\n : []\n })\n if (receipts.length === 0) return\n await this.assertCompletedTransaction(tx)\n await eachInOrder(receipts, async ({ outputIndex, remittance }) => {\n await this.verifyReceipt(tx, outputIndex, remittance, originator)\n })\n }\n\n /**\n * Checks a received transaction: every input unlocks its source and every asset it involves is\n * supported. Token amounts are not re-evaluated: the received output must be admitted and\n * unspent, and its overlay admits it only after applying the amount and authority rules.\n */\n protected async assertCompletedTransaction(tx: Transaction): Promise<void> {\n for (let index = 0; index < tx.inputs.length; index++) assertUnlocks(tx, index)\n const { inputs, outputs } = transactionTokens(tx)\n await this.assertSupportedAssets([...inputs.keys(), ...outputs.keys()])\n }\n\n /** Checks each distinct asset in order, so the first unsupported one is the one reported. */\n protected async assertSupportedAssets(assetIds: Iterable<string>): Promise<void> {\n await eachInOrder(new Set(assetIds), async assetId => {\n await this.assertSupportedAsset(assetId)\n })\n }\n\n /** One receipt: its custody, its output's asset, owner and basket, and overlay admission. */\n protected async verifyReceipt(\n tx: Transaction,\n outputIndex: number,\n remittance: BasketInsertion,\n originator: string\n ): Promise<void> {\n const target = parseAssetBasket(remittance.basket)\n if (target === undefined)\n throw new Error('BRC-207: a receipt must name a per-asset value or authority basket')\n const custody = parseCustody(\n remittance.customInstructions ?? '',\n MAX_RECEIPT_INSTRUCTION_BYTES,\n 'receipt customInstructions'\n )\n const source = tx.outputs[outputIndex]\n if (source?.satoshis === undefined)\n throw new Error('BRC-207: the receipt names a missing output')\n const txid = tx.id('hex')\n const token = readTokenOutput(source.lockingScript, { txid, vout: outputIndex })\n if (token === undefined)\n throw new Error('BRC-207: the received output is not a BRC-162 token output')\n if (!selectsAsset(custody.assetId, token)) {\n throw new Error('BRC-207: the receipt instructions name a different asset than the output')\n }\n if (target.assetId !== token.assetId || target.role !== token.role) {\n throw new Error('BRC-207: the receipt basket does not match the received output')\n }\n await this.assertOwned(token, custody, custody.senderIdentityKey, originator)\n await this.assertSupportedAsset(token.assetId)\n const outpoint = outpointString(txid, outputIndex)\n const admitted = await this.spendable(token.assetId, [\n { outpoint, lockingScript: source.lockingScript, satoshis: source.satoshis }\n ])\n if (!admitted.has(outpoint)) {\n throw new Error(\n 'BRC-207: the received output is not admitted and unspent in its asset overlay'\n )\n }\n }\n\n /* ----------------------------------------------------------------------\n * Send\n * ---------------------------------------------------------------------- */\n\n /** Checks a planned token action and adds its selected token inputs and per-asset change. */\n protected async createAction(\n args: CreateActionArgs,\n originator: string\n ): Promise<CreateActionArgs> {\n const labels = args.labels ?? []\n const plan = ColorPlan.fromLabels(labels)\n if (plan === undefined)\n throw new Error('BRC-207: a p color createAction requires a p color plan')\n // Plan labels are the only p color labels; BRC-176 proof transport is not part of BRC-207.\n if (\n labels.some(\n label =>\n label.startsWith(`${COLOR_BASKET_NAMESPACE} `) &&\n !label.startsWith(COLOR_PLAN_LABEL_PREFIX)\n )\n )\n throw new Error('BRC-207: unknown p color label')\n const handoff = labels.some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX))\n assertPlanSupported(plan, args)\n const { planned, outputs } = await this.planOutputs(plan, args, originator)\n // The hold keeps concurrent sends in this module from choosing the same outputs while it plans.\n // It ends when this handler returns; storage then rejects a second action that tries to spend\n // an input already marked spent.\n const reserved = new Set<string>()\n try {\n const explicit = await this.explicitInputs(args, originator)\n this.reserve(reserved, explicit.managed)\n const { inputs, changes } = await this.fund(\n reserved,\n plan,\n planned,\n explicit,\n handoff,\n originator\n )\n sighashScopes(plan, new Set([...explicit.managed, ...inputs].map(input => input.outpoint)))\n return {\n ...args,\n inputs: orderInputs(explicit.inputs, tokenInputs(inputs), plan.inputPositions),\n outputs: placeChange(outputs, changes, plan.changePositions)\n }\n } finally {\n for (const outpoint of reserved) this.selected.delete(outpoint)\n }\n }\n\n protected reserve(reserved: Set<string>, inputs: ReadonlyArray<{ outpoint: string }>): void {\n for (const input of inputs) {\n this.selected.add(input.outpoint)\n reserved.add(input.outpoint)\n }\n }\n\n protected release(reserved: Set<string>, inputs: ReadonlyArray<{ outpoint: string }>): void {\n for (const input of inputs) {\n this.selected.delete(input.outpoint)\n reserved.delete(input.outpoint)\n }\n }\n\n /**\n * Classifies the caller's inputs: this wallet's `p color` outputs are managed and signed by the\n * module; foreign token inputs count only once their asset's overlay admits them; other inputs\n * pass through unchanged.\n */\n protected async explicitInputs(\n args: CreateActionArgs,\n originator: string\n ): Promise<ExplicitInputs> {\n const inputs = args.inputs ?? []\n const explicit: ExplicitInputs = { inputs: [...inputs], managed: [], holdings: new Map() }\n if (inputs.length === 0) return explicit\n const outpoints = new Set(inputs.map(input => input.outpoint))\n if (outpoints.size !== inputs.length) throw new Error('BRC-207: duplicate explicit input')\n const listed = await this.wallet.listOutputs(\n {\n basket: toolbox.specOpBasketPrefixOutputs,\n tags: [COLOR_BASKET_NAMESPACE],\n include: 'locking scripts',\n includeCustomInstructions: true\n },\n originator\n )\n const own = new Map(\n listed.outputs\n .filter(output => outpoints.has(output.outpoint))\n .map(output => [output.outpoint, output])\n )\n const beef =\n args.inputBEEF === undefined\n ? undefined\n : parsed('inputBEEF', () => Beef.fromBinary(args.inputBEEF as number[]))\n await eachInOrder(inputs, async input => {\n const output = own.get(input.outpoint)\n if (output === undefined) await this.foreignInput(explicit, beef, input.outpoint)\n else await this.ownInput(explicit, output, originator)\n })\n return explicit\n }\n\n /** Counts one of this wallet's `p color` outputs once it is managed, admitted and unspent. */\n protected async ownInput(\n explicit: ExplicitInputs,\n output: WalletOutput,\n originator: string\n ): Promise<void> {\n if (!output.spendable)\n throw new Error('BRC-207: an explicit p color input is reserved by another action')\n const managed = await this.managedInput(output, originator)\n if (managed === undefined)\n throw new Error('BRC-207: an explicit p color input is not a managed token output')\n await this.assertSupportedAsset(managed.assetId)\n if (\n !(await this.spendable(managed.assetId, [managed])).has(managed.outpoint) &&\n !(await this.resubmitHeld(managed.assetId, managed.role, [managed], originator)).has(\n managed.outpoint\n )\n )\n throw new Error('BRC-207: an explicit p color input is not admitted and unspent')\n explicit.managed.push(managed)\n const totals = holding(explicit.holdings, managed.assetId, emptyExplicitHolding)\n if (managed.role === 'value') totals.value += managed.amount\n else totals.authority += 1\n }\n\n /** Counts a foreign token input once its overlay admits it; other foreign inputs add nothing. */\n protected async foreignInput(\n explicit: ExplicitInputs,\n beef: Beef | undefined,\n outpoint: string\n ): Promise<void> {\n // A source missing from inputBEEF is resolved from the wallet and checked at signAction.\n const source = foreignSource(beef, outpoint)\n const token =\n source === undefined\n ? undefined\n : readAnyTokenOutput(source.lockingScript, parseOutpoint(outpoint))\n if (token === undefined) return\n await this.assertSupportedAsset(token.assetId)\n if (!(await this.spendable(token.assetId, [source!])).has(outpoint))\n throw new Error('BRC-207: a foreign token input is not admitted and unspent in its overlay')\n const totals = holding(explicit.holdings, token.assetId, emptyExplicitHolding)\n if (token.role === 'value') {\n totals.value += token.amount\n totals.foreignValue += token.amount\n } else {\n totals.authority += 1\n totals.foreignAuthority += 1\n }\n }\n\n /** Classifies the requested outputs, totalling each asset's value and authority outputs. */\n protected async planOutputs(\n plan: ColorPlan,\n args: CreateActionArgs,\n originator: string\n ): Promise<{ planned: PlannedOutputs; outputs: CreateActionOutput[] }> {\n const requested = args.outputs ?? []\n for (const remittance of plan.ownedOutputs) {\n if (remittance.outputIndex >= requested.length) {\n throw new Error('BRC-207: plan.ownedOutputs names a missing output')\n }\n }\n const owned = new Map(plan.ownedOutputs.map(remittance => [remittance.outputIndex, remittance]))\n const planned: PlannedOutputs = { holdings: new Map(), destinations: [] }\n const outputs = await mapInOrder(\n requested,\n async (output, index) =>\n await this.planOutput(plan, args, index, output, owned.get(index), planned, originator)\n )\n return { planned, outputs }\n }\n\n /** One requested output: passed through, a token destination, or a token output this wallet keeps. */\n protected async planOutput(\n plan: ColorPlan,\n args: CreateActionArgs,\n index: number,\n output: CreateActionOutput,\n remittance: ColorRemittance | undefined,\n planned: PlannedOutputs,\n originator: string\n ): Promise<CreateActionOutput> {\n const lockingScript = parsed(`output ${index} locking script`, () =>\n LockingScript.fromHex(output.lockingScript)\n )\n const placeholder = { txid: '00'.repeat(32), vout: index }\n const token = readTokenOutput(lockingScript, placeholder)\n if (token === undefined) {\n if (remittance !== undefined)\n throw new Error('BRC-207: plan.ownedOutputs names a non-token output')\n if (output.basket?.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true) {\n throw new Error('BRC-207: a p color basket can only receive BRC-162 token outputs')\n }\n const json = readJsonTokenOutput(lockingScript, placeholder)\n if (json !== undefined) this.jsonDestination(plan, index, output, json, planned)\n return output\n }\n if (token.deploy)\n return await this.deployOutput(args, output, token, remittance, planned, originator)\n if (!plan.assets.includes(token.assetId))\n throw new Error('BRC-207: an output asset is missing from plan.assets')\n const totals = holding(planned.holdings, token.assetId, emptyHolding)\n if (token.role === 'value') totals.value += token.amount\n else totals.authority += 1\n if (remittance !== undefined)\n return await this.ownedOutput(token, output, remittance, originator)\n if (output.basket !== undefined) {\n throw new Error('BRC-207: only outputs in plan.ownedOutputs may enter a p color basket')\n }\n planned.destinations.push({\n outputIndex: index,\n assetId: token.assetId,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n return output\n }\n\n /** A BRC-161 JSON output to another party: counted for its asset, never held or created here. */\n protected jsonDestination(\n plan: ColorPlan,\n index: number,\n output: CreateActionOutput,\n token: TokenOutput,\n planned: PlannedOutputs\n ): void {\n if (token.deploy) throw new Error('BRC-207: a new issuance must use BRC-162')\n if (!plan.assets.includes(token.assetId))\n throw new Error('BRC-207: an output asset is missing from plan.assets')\n const totals = holding(planned.holdings, token.assetId, emptyHolding)\n if (token.role === 'authority') totals.authority += 1\n else {\n totals.value += token.amount\n if (token.jsonOperation !== 'mint') totals.jsonValue = (totals.jsonValue ?? 0n) + token.amount\n }\n planned.destinations.push({\n outputIndex: index,\n assetId: token.assetId,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n }\n\n /**\n * The action's deploy, which BRC-162 requires at output 0. An owned deploy keeps its `ISSUE`\n * key; its asset basket is assigned once the transaction ID is final.\n */\n protected async deployOutput(\n args: CreateActionArgs,\n output: CreateActionOutput,\n token: TokenOutput,\n remittance: ColorRemittance | undefined,\n planned: PlannedOutputs,\n originator: string\n ): Promise<CreateActionOutput> {\n if (output.basket !== undefined)\n throw new Error(\n \"BRC-207: a deploy output's basket is assigned once its transaction is signed\"\n )\n planned.deploy = { operation: deployOperation(token) }\n if (remittance === undefined) {\n planned.destinations.push({\n outputIndex: 0,\n assetId: ISSUE,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n return output\n }\n if (remittance.assetId !== ISSUE)\n throw new Error('BRC-207: a deploy output remittance must use ISSUE')\n await this.assertOwned(token, remittance, remittance.senderIdentityKey, originator)\n // Without a p color basket the manager does not encrypt its custody, so it is encrypted here.\n return {\n ...output,\n customInstructions: await encryptMetadata(\n this.wallet,\n custodyInstructions(custodyOf(remittance)),\n originator\n )\n }\n }\n\n /** A token output of the action that this wallet keeps, placed in its asset's basket. */\n protected async ownedOutput(\n token: TokenOutput,\n output: CreateActionOutput,\n remittance: ColorRemittance,\n originator: string\n ): Promise<CreateActionOutput> {\n if (remittance.assetId !== token.assetId)\n throw new Error('BRC-207: an owned output remittance names another asset')\n await this.assertOwned(token, remittance, remittance.senderIdentityKey, originator)\n const basket = assetBasket(token.assetId, token.role)\n if (output.basket !== undefined && output.basket !== basket) {\n throw new Error('BRC-207: an owned output names the wrong p color basket')\n }\n return {\n ...output,\n basket,\n customInstructions: custodyInstructions(custodyOf(remittance))\n }\n }\n\n /**\n * Funds each asset the plan involves, checks its operations, splits for a handoff, and returns\n * the selected inputs and token change. The user approves the funded action at signAction.\n */\n protected async fund(\n reserved: Set<string>,\n plan: ColorPlan,\n planned: PlannedOutputs,\n explicit: ExplicitInputs,\n handoff: boolean,\n originator: string\n ): Promise<{\n inputs: ManagedInput[]\n changes: Array<{ assetId: string; output: CreateActionOutput }>\n }> {\n const assetIds = new Set([\n ...planned.holdings.keys(),\n ...explicit.holdings.keys(),\n ...plan.operations.flatMap(operation =>\n operation.assetId === ISSUE ? [] : [operation.assetId]\n )\n ])\n assertPlanAssets(plan, new Set([...assetIds, ...(planned.deploy === undefined ? [] : [ISSUE])]))\n if (planned.deploy !== undefined) assertOperations(plan, ISSUE, [planned.deploy.operation])\n const funding = await mapInOrder(assetIds, async assetId => {\n await this.assertSupportedAsset(assetId)\n return await this.fundAsset(\n reserved,\n plan,\n assetId,\n planned.holdings.get(assetId) ?? emptyHolding(),\n explicit.holdings.get(assetId) ?? emptyExplicitHolding(),\n originator\n )\n })\n const settled = await mapInOrder(\n funding,\n async asset =>\n await this.settleFunding(\n reserved,\n asset,\n explicit.holdings.get(asset.assetId)?.value ?? 0n,\n handoff,\n originator\n )\n )\n return {\n inputs: settled.flatMap(asset => asset.inputs),\n changes: settled.flatMap(asset => asset.change)\n }\n }\n\n /**\n * One funded asset's inputs and change: a handoff with change splits off an exact output instead,\n * so the recipient receives no change; otherwise any change becomes a new managed output.\n */\n protected async settleFunding(\n reserved: Set<string>,\n asset: AssetFunding,\n explicitValue: bigint,\n handoff: boolean,\n originator: string\n ): Promise<{\n inputs: ManagedInput[]\n change: Array<{ assetId: string; output: CreateActionOutput }>\n }> {\n if (asset.change <= 0n) return { inputs: asset.selected, change: [] }\n if (handoff) {\n const value = asset.selected.filter(input => input.role === 'value')\n const needed = asset.outputs.value - asset.change - explicitValue\n return {\n inputs: await this.splitExact(reserved, asset.assetId, value, needed, originator),\n change: []\n }\n }\n const { output } = await this.newManagedOutput(asset.assetId, asset.change, originator)\n return { inputs: asset.selected, change: [{ assetId: asset.assetId, output }] }\n }\n\n /**\n * Selects one asset's value inputs for a transfer and authority inputs for a declared authority\n * operation, then checks the resulting operations against the plan. Value is selected, with\n * change, only when the asset's operations are a transfer without a mint or burn.\n */\n protected async fundAsset(\n reserved: Set<string>,\n plan: ColorPlan,\n assetId: string,\n requested: Holding,\n explicit: ExplicitHolding,\n originator: string\n ): Promise<AssetFunding> {\n const declared = declaredOperations(plan, assetId)\n const selected: ManagedInput[] = []\n const automatic = declared.has('transfer') && !declared.has('mint') && !declared.has('burn')\n if (automatic && requested.value > explicit.value) {\n selected.push(\n ...(await this.selectInputs(\n reserved,\n assetId,\n 'value',\n requested.value - explicit.value,\n originator\n ))\n )\n }\n const authorityOperation = AUTHORITY_OPERATIONS.find(operation => declared.has(operation))\n const authorityCount =\n authorityOperation === undefined || explicit.authority > 0\n ? 0\n : authorityInputsFor(authorityOperation, requested.authority)\n if (authorityCount > 0) {\n selected.push(\n ...(await this.selectInputs(\n reserved,\n assetId,\n 'authority',\n BigInt(authorityCount),\n originator\n ))\n )\n }\n const selectedValue = sumAmounts(selected)\n const value = explicit.value + selectedValue\n // Change returns what selection adds beyond the need; excess explicit value is a burn.\n const change = selectedValue > 0n ? value - requested.value : 0n\n const inputs = { value, authority: explicit.authority + authorityCount }\n const outputs = {\n value: requested.value + change,\n authority: requested.authority,\n jsonValue: requested.jsonValue\n }\n assertOperations(plan, assetId, requiredOperations(inputs, outputs))\n return { assetId, selected, change, outputs }\n }\n\n /** Replaces a handoff's value inputs with one split output of exactly `amount`, which it reserves. */\n protected async splitExact(\n reserved: Set<string>,\n assetId: string,\n selected: ManagedInput[],\n amount: bigint,\n originator: string\n ): Promise<ManagedInput[]> {\n const exact = await this.split(assetId, selected, amount, originator)\n this.release(reserved, selected)\n this.reserve(reserved, [exact])\n return [exact]\n }\n\n /**\n * Selects admitted, unspent outputs of one asset's value or authority basket: value outputs\n * covering `target` units, largest first, or `target` authority outputs.\n */\n protected async selectInputs(\n reserved: Set<string>,\n assetId: string,\n role: TokenRole,\n target: bigint,\n originator: string\n ): Promise<ManagedInput[]> {\n const candidates = (await this.candidates(assetId, role, originator)).sort(byAmountDescending)\n const rejected = new Set<string>()\n for (;;) {\n const chosen = chooseCandidates(candidates, rejected, role, target)\n if (chosen === undefined)\n throw new Error(\n `BRC-207: insufficient spendable ${role === 'value' ? 'balance' : 'authority'} of ${assetId}`\n )\n const selected = await this.checkChosen(reserved, assetId, role, chosen, rejected, originator)\n if (selected !== undefined) return selected\n }\n }\n\n /**\n * Holds the chosen outputs and checks them: each must have readable custody and be admitted and\n * unspent, after resubmission if needed. Returns them as inputs, still held, when all pass;\n * otherwise rejects and releases the ones that failed and returns undefined.\n */\n protected async checkChosen(\n reserved: Set<string>,\n assetId: string,\n role: TokenRole,\n chosen: Candidate[],\n rejected: Set<string>,\n originator: string\n ): Promise<ManagedInput[] | undefined> {\n // Chosen outputs are held while they are checked, so a concurrent action cannot choose them.\n this.reserve(reserved, chosen)\n // Custody is read only for chosen outputs; an unreadable record is skipped, not fatal.\n const inputs = await Promise.all(\n chosen.map(async candidate => await this.readableInput(candidate, originator))\n )\n const unreadable = chosen.filter((_, index) => inputs[index] === undefined)\n if (unreadable.length > 0) {\n for (const candidate of unreadable) rejected.add(candidate.outpoint)\n this.release(reserved, unreadable)\n return undefined\n }\n const selected = inputs as ManagedInput[]\n const admitted = await this.spendable(assetId, selected)\n const unlisted = selected.filter(input => !admitted.has(input.outpoint))\n const recovered = await this.resubmitHeld(assetId, role, unlisted, originator)\n const missing = unlisted.filter(input => !recovered.has(input.outpoint))\n if (missing.length === 0) return selected\n for (const input of missing) rejected.add(input.outpoint)\n this.release(reserved, missing)\n return undefined\n }\n\n /**\n * Resubmits the wallet's own copies of the transactions behind held outputs that the overlay\n * does not report, as BTMS does when it selects, and returns the outputs it then admits.\n */\n protected async resubmitHeld(\n assetId: string,\n role: TokenRole,\n outputs: readonly SourceOutput[],\n originator: string\n ): Promise<Set<string>> {\n if (outputs.length === 0) return new Set()\n const txids = new Set(outputs.map(output => parseOutpoint(output.outpoint).txid))\n const beef = new Beef()\n for (let offset = 0; [...txids].some(txid => beef.findTxid(txid) === undefined);) {\n const page = await this.wallet.listOutputs(\n {\n basket: assetBasket(assetId, role),\n include: 'entire transactions',\n limit: LIST_PAGE_LIMIT,\n offset\n },\n originator\n )\n if (page.BEEF !== undefined) beef.mergeBeef(page.BEEF)\n offset += page.outputs.length\n if (page.outputs.length < LIST_PAGE_LIMIT) break\n }\n await eachInOrder(txids, async txid => {\n if (beef.findTxid(txid) === undefined) return\n const atomic = beef.toBinaryAtomic(txid)\n const { assetIds, deploy } = submissionAssets(Transaction.fromAtomicBEEF(atomic))\n // A refused resubmission leaves the output unlisted; the spendability check decides.\n await this.provider\n .submit([...(deploy ? [DISCOVERY_TOPIC] : []), ...assetIds.map(colorTopic)], atomic)\n .catch(() => undefined)\n })\n return await this.spendable(assetId, outputs)\n }\n\n /** One basket's token outputs of the asset, read from their locking scripts, excluding selected ones. */\n protected async candidates(\n assetId: string,\n role: TokenRole,\n originator: string\n ): Promise<Candidate[]> {\n const outputs = await this.listBasket(assetBasket(assetId, role), originator, {})\n return outputs.flatMap(output => {\n if (this.selected.has(output.outpoint) || output.customInstructions === undefined) return []\n const source = this.sourceOutput(output)\n const token = tryReadTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n if (token?.assetId !== assetId || token.role !== role) return []\n return [\n { ...source, token, amount: token.amount, customInstructions: output.customInstructions }\n ]\n })\n }\n\n /** A chosen candidate with its custody, or undefined when its custody record is unreadable. */\n protected async readableInput(\n candidate: Candidate,\n originator: string\n ): Promise<ManagedInput | undefined> {\n try {\n const { outpoint, lockingScript, satoshis, token, customInstructions } = candidate\n return await this.custodyInput(\n { outpoint, lockingScript, satoshis, token },\n customInstructions,\n originator\n )\n } catch {\n return undefined\n }\n }\n\n /** A `p color` basket output as a managed token input, or undefined when it is not one. */\n protected async managedInput(\n output: WalletOutput,\n originator: string\n ): Promise<ManagedInput | undefined> {\n const source = this.sourceOutput(output)\n const token = readTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n if (token === undefined || output.customInstructions === undefined) return undefined\n return await this.custodyInput({ ...source, token }, output.customInstructions, originator)\n }\n\n /** Decrypts and parses an output's custody tuple; undefined when it names another asset. */\n protected async custodyInput(\n output: SourceOutput & { token: TokenOutput },\n customInstructions: string,\n originator: string\n ): Promise<ManagedInput | undefined> {\n const custody = parseCustody(\n await maybeDecryptMetadata(this.wallet, customInstructions, originator),\n undefined,\n 'managed output customInstructions'\n )\n if (!selectsAsset(custody.assetId, output.token)) return undefined\n const { token, ...source } = output\n return { ...source, assetId: token.assetId, role: token.role, amount: token.amount, custody }\n }\n\n /**\n * Before a handoff, splits the selected inputs into an output of exactly `amount` and token\n * change, broadcast and submitted. The split pays this wallet and, like BRC-177's revocation\n * anchor, needs no separate consent; the user approves the handoff itself in signAction.\n */\n protected async split(\n assetId: string,\n selected: ManagedInput[],\n amount: bigint,\n originator: string\n ): Promise<ManagedInput> {\n const change = sumAmounts(selected) - amount\n const exact = await this.newManagedOutput(assetId, amount, originator)\n const rest = await this.newManagedOutput(assetId, change, originator)\n // The split goes to the underlying wallet directly, so its custody is encrypted here.\n const outputs = await Promise.all(\n [exact.output, rest.output].map(async output => ({\n ...output,\n customInstructions: await encryptMetadata(\n this.wallet,\n output.customInstructions as string,\n originator\n )\n }))\n )\n const created = await this.wallet.createAction(\n {\n description: 'Split tokens for a handoff',\n labels: ColorPlan.toLabels({\n version: 1,\n assets: [assetId],\n ownedOutputs: [\n { outputIndex: 0, ...exact.custody },\n { outputIndex: 1, ...rest.custody }\n ],\n operations: [{ assetId, operation: 'transfer' }],\n inputPositions: [],\n changePositions: [],\n sighashTypes: []\n }),\n inputs: tokenInputs(selected),\n outputs,\n options: { randomizeOutputs: false, signAndProcess: false }\n },\n originator\n )\n const signable = created.signableTransaction\n if (signable == null) throw new Error('BRC-207: the split action was not returned for signing')\n const template = Transaction.fromAtomicBEEF(signable.tx)\n let signed: SignActionResult\n try {\n const spends = await this.signInputs(\n template,\n selected,\n new Map(),\n originator,\n 'BRC-207: the split transaction omits a token input'\n )\n signed = await this.wallet.signAction({ reference: signable.reference, spends }, originator)\n } catch (error) {\n await this.wallet\n .abortAction({ reference: signable.reference }, originator)\n .catch(() => undefined)\n throw error\n }\n if (signed.txid === undefined || signed.tx === undefined) {\n throw new Error('BRC-207: the split transaction was not returned')\n }\n await this.submit([assetId], signed.tx)\n return {\n outpoint: outpointString(signed.txid, 0),\n lockingScript: LockingScript.fromHex(exact.output.lockingScript),\n satoshis: TOKEN_CARRIER_SATOSHIS,\n assetId,\n role: 'value',\n amount,\n custody: exact.custody\n }\n }\n\n /** A fresh wallet-owned value output in the asset's basket, keyed to this wallet. */\n protected async newManagedOutput(\n assetId: string,\n amount: bigint,\n originator: string\n ): Promise<{ output: CreateActionOutput; custody: Custody }> {\n const custody: Custody = {\n assetId,\n derivationPrefix: toBase64(Random(16)),\n derivationSuffix: toBase64(Random(16)),\n senderIdentityKey: await this.identity()\n }\n const publicKey = await this.publicKey(custody, custody.senderIdentityKey, originator)\n return {\n custody,\n output: {\n lockingScript: new OneColor()\n .lock(assetId, amount, hash160(toArray(publicKey, 'hex')))\n .toHex(),\n satoshis: TOKEN_CARRIER_SATOSHIS,\n basket: assetBasket(assetId, 'value'),\n customInstructions: custodyInstructions(custody),\n outputDescription: 'BRC-207 token change'\n }\n }\n }\n\n /**\n * Checks the funded action against its plan, rechecks every token input's spendability, asks\n * the user to approve the final layout, and signs the inputs that spend this wallet's\n * `p color` outputs.\n */\n protected async signAction(\n args: SignActionArgs,\n action: PermissionsModuleAction | undefined,\n originator: string\n ): Promise<SignActionArgs> {\n if (action === undefined) return args\n const createArgs = action.createArgs\n const plan = ColorPlan.fromLabels(createArgs?.labels)\n if (createArgs === undefined || plan === undefined)\n throw new Error(\"BRC-207: signAction needs the action's p color createAction arguments\")\n const tx = action.transaction\n const tokens = transactionTokens(tx, true)\n assertTransactionOperations(plan, tokens)\n const managed = await this.actionInputs(tx, originator)\n const scopes = sighashScopes(plan, new Set(managed.map(input => input.outpoint)))\n await eachInOrder(new Set(tokens.consumed.map(input => input.assetId)), async assetId => {\n const assetInputs = tokens.consumed.filter(input => input.assetId === assetId)\n const admitted = await this.spendable(assetId, assetInputs)\n if (assetInputs.some(input => !admitted.has(input.outpoint)))\n throw new Error(`BRC-207: a ${assetId} input is no longer spendable`)\n })\n await this.approve(originator, actionConsent(plan, createArgs, tx, tokens, managed, scopes))\n return {\n ...args,\n spends: {\n ...args.spends,\n ...(await this.signInputs(\n tx,\n managed,\n scopes,\n originator,\n 'BRC-207: the signable transaction omits a token input'\n ))\n }\n }\n }\n\n /** The transaction's inputs that spend this wallet's `p color` outputs, with their stored custody. */\n protected async actionInputs(tx: Transaction, originator: string): Promise<ManagedInput[]> {\n const outpoints = new Set(tx.inputs.map(input => inputOutpoint(input)))\n // The action's own inputs are reserved by it, which this listing includes.\n const listed = await this.wallet.listOutputs(\n {\n basket: toolbox.specOpBasketPrefixOutputs,\n tags: [COLOR_BASKET_NAMESPACE],\n include: 'locking scripts',\n includeCustomInstructions: true\n },\n originator\n )\n const managed = await Promise.all(\n listed.outputs\n .filter(output => outpoints.has(output.outpoint))\n .map(async output => await this.managedInput(output, originator))\n )\n return managed.filter(input => input !== undefined)\n }\n\n /**\n * Submits a signed token transaction to the topic of every asset among its inputs and outputs,\n * and a deploy to the discovery topic.\n */\n protected async submitSigned(result: SignActionResult, template: Transaction): Promise<void> {\n if (result?.tx === undefined) return\n const { assetIds, deploy } = submissionAssets(Transaction.fromAtomicBEEF(result.tx), template)\n if (assetIds.length > 0 || deploy) await this.submit(assetIds, result.tx, deploy)\n }\n\n /**\n * Submits a transaction to each asset topic, and a deploy to the discovery topic, trying again\n * up to `SUBMIT_ATTEMPTS` times before reporting the provider's failure. As in BTMS, an accepted\n * submission completes the action: every token input was overlay-checked and the plan verified\n * before signing, so an output the overlay then does not admit stays in its basket and is\n * resubmitted when it is next selected.\n */\n protected async submit(assetIds: string[], beef: AtomicBEEF, deploy = false): Promise<void> {\n const topics = [...(deploy ? [DISCOVERY_TOPIC] : []), ...assetIds.map(colorTopic)]\n let failure: unknown\n for (let attempt = 0; attempt < SUBMIT_ATTEMPTS; attempt++) {\n try {\n await this.provider.submit(topics, Array.from(beef))\n return\n } catch (error) {\n failure = error\n }\n }\n throw failure\n }\n\n /* ----------------------------------------------------------------------\n * App-built transactions (createSignature)\n * ---------------------------------------------------------------------- */\n\n /** Signs one managed input of an app-built transaction described by a 207 signature envelope. */\n protected async createSignature(\n args: CreateSignatureArgs,\n originator: string,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n if (args.hashToDirectlySign !== undefined) {\n throw new Error(\n 'BRC-207: p color signatures take a signature envelope, not hashToDirectlySign'\n )\n }\n const selector = this.parseKeyArgs(args)\n if (args.data === undefined || args.data.length > MAX_ENVELOPE_BYTES) {\n throw new Error('BRC-207: the signature envelope is missing or exceeds 16 MiB')\n }\n const envelope = jsonObject(\n parseStrictJsonBytes(args.data, 'signature envelope'),\n 'signature envelope'\n )\n exactMembers(\n envelope,\n ['version', 'tx', 'inputIndex', 'sighashType', 'ownedOutputs'],\n ['profileData'],\n 'signature envelope'\n )\n if (envelope.version !== 1) throw new Error('BRC-207: signature envelope version must be 1')\n if (\n Object.keys(parseProfileData(envelope.profileData, 'signature envelope profileData') ?? {})\n .length > 0\n ) {\n throw new Error(\n 'BRC-207: signature envelope profileData names a profile the asset does not require'\n )\n }\n const tx = parsed('the signature envelope tx', () =>\n Transaction.fromAtomicBEEF(\n jsonByteArray(envelope.tx, 'signature envelope tx', MAX_ENVELOPE_BYTES)\n )\n )\n const inputIndex = jsonUint32(envelope.inputIndex, 'signature envelope inputIndex')\n const sighashType = jsonUint32(envelope.sighashType, 'signature envelope sighashType')\n if (sighashType > 255) throw new Error('BRC-207: sighashType must be in 0..255')\n const ownedOutputs = parseRemittances(envelope.ownedOutputs, 'signature envelope ownedOutputs')\n const input = tx.inputs[inputIndex]\n const sourceTransaction = input?.sourceTransaction\n const source = sourceTransaction?.outputs[input.sourceOutputIndex]\n if (sourceTransaction === undefined || source?.satoshis === undefined) {\n throw new Error('BRC-207: the envelope must carry the signed input source transaction')\n }\n const sourceTXID = sourceTransaction.id('hex')\n const token = readTokenOutput(source.lockingScript, {\n txid: sourceTXID,\n vout: input.sourceOutputIndex\n })\n if (token === undefined || !selectsAsset(selector.assetId, token)) {\n throw new Error(\n 'BRC-207: the protocol asset selector does not match the signed source output'\n )\n }\n await this.assertOwned(token, selector, args.counterparty ?? 'anyone', originator)\n // The signature commits to the whole transaction, so it is evaluated as a send is: every\n // input authenticated from its source, every asset's legs and supply change derived, and\n // every token input admitted and unspent in its overlay.\n const tokens = transactionTokens(tx, true)\n await this.assertSupportedAssets([\n token.assetId,\n ...tokens.inputs.keys(),\n ...tokens.outputs.keys()\n ])\n await Promise.all(\n ownedOutputs.map(async remittance => {\n const output = tx.outputs[remittance.outputIndex]\n const owned =\n output === undefined\n ? undefined\n : readTokenOutput(output.lockingScript, {\n txid: '00'.repeat(32),\n vout: remittance.outputIndex\n })\n if (owned === undefined || owned.deploy || remittance.assetId !== owned.assetId) {\n throw new Error('BRC-207: an envelope remittance does not match its output')\n }\n await this.assertOwned(owned, remittance, remittance.senderIdentityKey, originator)\n })\n )\n const outpoint = outpointString(sourceTXID, input.sourceOutputIndex)\n const signed = { outpoint, lockingScript: source.lockingScript, satoshis: source.satoshis }\n await eachInOrder(new Set(tokens.consumed.map(consumed => consumed.assetId)), async assetId => {\n const assetInputs = tokens.consumed.filter(consumed => consumed.assetId === assetId)\n const admitted = await this.spendable(assetId, assetInputs)\n if (!admitted.has(outpoint) && assetId === token.assetId)\n throw new Error('BRC-207: the signed input is not admitted and unspent in its overlay')\n if (assetInputs.some(consumed => !admitted.has(consumed.outpoint)))\n throw new Error(`BRC-207: a ${assetId} input is not admitted and unspent in its overlay`)\n })\n const preimage = this.preimage(tx, inputIndex, signed, sighashType)\n const kept = (vout: number): boolean =>\n ownedOutputs.some(remittance => remittance.outputIndex === vout)\n await this.approve(originator, {\n type: 'color_signature',\n inputIndex,\n ...transactionConsent(\n tx,\n tokens,\n [token],\n kept,\n vout => !kept(vout),\n [{ outpoint, inputIndex, sighashType }],\n kept(0)\n )\n })\n return await next({\n protocolID: args.protocolID,\n keyID: args.keyID,\n counterparty: args.counterparty,\n privileged: args.privileged,\n privilegedReason: args.privilegedReason,\n seekPermission: args.seekPermission,\n hashToDirectlySign: hash256(preimage)\n })\n }\n\n /* ----------------------------------------------------------------------\n * Read views\n * ---------------------------------------------------------------------- */\n\n protected async listOutputs(\n args: ListOutputsArgs,\n originator: string,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n const seekPermission = args.seekPermission !== false\n if (args.basket === ASSETS_SELECTOR) {\n await this.authorizeRead(originator, { basket: args.basket, seekPermission })\n return await this.inventory(args, originator)\n }\n const balance = parseBalanceSelector(args.basket)\n if (balance !== undefined) {\n await this.authorizeRead(originator, { basket: args.basket, ...balance, seekPermission })\n return await this.balance(balance.assetId, balance.role, args, originator)\n }\n const held = parseAssetBasket(args.basket)\n if (held !== undefined) {\n await this.authorizeRead(originator, { basket: args.basket, ...held, seekPermission })\n return await next(args)\n }\n throw new Error('BRC-207: unknown p color basket selector')\n }\n\n /** `p color balance`: exact sum of available token units, or count of available authorities. */\n protected async balance(\n assetId: string,\n role: TokenRole,\n args: ListOutputsArgs,\n originator: string\n ): Promise<ListOutputsResult> {\n // As in BTMS, a read reports wallet state alone: the basket's unreserved, unspent outputs.\n // The overlay is consulted only when spending.\n const held = (await this.listBasket(assetBasket(assetId, role), originator, args))\n .map(output => {\n const source = this.sourceOutput(output)\n return readTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n })\n .filter(token => token?.assetId === assetId && token.role === role)\n const total = held.reduce((sum, token) => sum + (role === 'value' ? token!.amount : 1n), 0n)\n return { totalOutputs: total.toString(), outputs: [] }\n }\n\n /** `p color assets`: every held token output across all per-asset baskets, with its state. */\n protected async inventory(args: ListOutputsArgs, originator: string): Promise<ListOutputsResult> {\n const entireTransactions = args.include === 'entire transactions'\n const listed = await this.wallet.listOutputs(\n {\n basket: toolbox.specOpBasketPrefixOutputs,\n tags: [COLOR_BASKET_NAMESPACE],\n include: entireTransactions ? 'entire transactions' : 'locking scripts',\n includeCustomInstructions: args.includeCustomInstructions,\n includeTags: true,\n includeLabels: args.includeLabels\n },\n originator\n )\n const beef =\n entireTransactions && listed.BEEF !== undefined ? Beef.fromBinary(listed.BEEF) : undefined\n const views = inventoryRecords(listed.outputs, beef)\n .map(inventoryView)\n .filter(view => matchesTags(view.tags, args.tags ?? [], args.tagQueryMode))\n const limit = args.limit ?? 10\n const offset = args.offset ?? 0\n const ordered = offset < 0 ? [...views].reverse() : views\n const start = offset < 0 ? -offset - 1 : offset\n const page = ordered.slice(start, start + limit)\n // Only the returned page is decrypted and carried in the BEEF.\n const result: ListOutputsResult = {\n totalOutputs: views.length,\n outputs: await Promise.all(\n page.map(async view => await this.inventoryOutput(view, args, originator))\n )\n }\n if (beef !== undefined) result.BEEF = pageBeef(beef, page)\n return result\n }\n\n /** One inventory record as a BRC-100 output with the fields the caller asked for. */\n protected async inventoryOutput(\n view: InventoryView,\n args: ListOutputsArgs,\n originator: string\n ): Promise<WalletOutput> {\n const { record, state, tags } = view\n const output: WalletOutput = {\n satoshis: record.output.satoshis,\n spendable: state === 'available',\n outpoint: record.output.outpoint\n }\n if (args.include === 'locking scripts')\n output.lockingScript = record.source.lockingScript.toHex()\n if (args.includeCustomInstructions === true && record.output.customInstructions !== undefined) {\n output.customInstructions = await maybeDecryptMetadata(\n this.wallet,\n record.output.customInstructions,\n originator\n )\n }\n if (args.includeTags === true) output.tags = tags\n if (args.includeLabels === true) output.labels = record.output.labels\n return output\n }\n\n /* ----------------------------------------------------------------------\n * Shared helpers\n * ---------------------------------------------------------------------- */\n\n /** Validates a `p color` key reference and returns its asset selector and remittance strings. */\n protected parseKeyArgs(args: {\n protocolID?: unknown\n keyID?: unknown\n }): ReturnType<typeof parseColorProtocolID> {\n if (args.keyID !== COLOR_KEY_ID) throw new Error('BRC-207: p color keys use keyID \"color\"')\n return parseColorProtocolID(args.protocolID)\n }\n\n protected async identity(): Promise<string> {\n if (this.identityKey === undefined) {\n const pending = this.wallet\n .getPublicKey({ identityKey: true })\n .then(({ publicKey }) => publicKey)\n this.identityKey = pending\n // A rejected lookup is not cached; the next call asks the wallet again.\n pending.catch(() => {\n if (this.identityKey === pending) this.identityKey = undefined\n })\n }\n return await this.identityKey\n }\n\n protected async publicKey(\n custody: Pick<Custody, 'assetId' | 'derivationPrefix' | 'derivationSuffix'>,\n counterparty: WalletCounterparty,\n originator: string\n ): Promise<string> {\n const { publicKey } = await this.wallet.getPublicKey(\n {\n protocolID: colorProtocolID(\n custody.assetId,\n custody.derivationPrefix,\n custody.derivationSuffix\n ),\n keyID: COLOR_KEY_ID,\n counterparty,\n forSelf: true\n },\n originator\n )\n return publicKey\n }\n\n /** Fails unless the output is a P2PKH remainder locked to this wallet's derived `p color` key. */\n protected async assertOwned(\n token: TokenOutput,\n custody: Pick<Custody, 'assetId' | 'derivationPrefix' | 'derivationSuffix'>,\n counterparty: WalletCounterparty,\n originator: string\n ): Promise<void> {\n if (token.pubKeyHash === undefined)\n throw new Error('BRC-207: a managed token output must have a P2PKH remainder')\n const publicKey = await this.publicKey(custody, counterparty, originator)\n if (toHex(hash160(toArray(publicKey, 'hex'))) !== toHex(token.pubKeyHash)) {\n throw new Error(\"BRC-207: the token output is not locked to this wallet's p color key\")\n }\n }\n\n /**\n * Authenticates the asset's deploy through the overlay and fails when it declares\n * required processing profiles. The deploy bytes hash to the asset ID, so no SPV is needed.\n */\n protected async assertSupportedAsset(assetId: string): Promise<void> {\n let check = this.supportedAssets.get(assetId)\n if (check === undefined) {\n check = (async () => {\n const { txid, vout } = parseAssetId(assetId)\n const outpoint = outpointString(txid, vout)\n const deploy = readOutputList(await this.provider.admission(assetId, [outpoint]), [\n outpoint\n ]).get(outpoint)\n if (deploy === undefined)\n throw new Error(`BRC-207: the overlay has no admitted deploy for ${assetId}`)\n if (!isDeployOutput(deploy.lockingScript, { txid, vout })) {\n throw new Error(`BRC-207: ${assetId} is not a token deploy`)\n }\n })()\n this.supportedAssets.set(assetId, check)\n check.catch(() => this.supportedAssets.delete(assetId))\n }\n await check\n }\n\n /** The queried outputs the overlay reports admitted and unspent, matched to their source bytes. */\n protected async spendable(\n assetId: string,\n outputs: readonly SourceOutput[]\n ): Promise<Set<string>> {\n const outpoints = outputs.map(output => output.outpoint)\n const listed = readOutputList(await this.provider.spendability(assetId, outpoints), outpoints)\n for (const output of outputs) {\n const answer = listed.get(output.outpoint)\n if (\n answer !== undefined &&\n (answer.satoshis !== output.satoshis ||\n answer.lockingScript.toHex() !== output.lockingScript.toHex())\n ) {\n throw new Error(\n `BRC-207: the overlay answer for ${output.outpoint} does not match its source output`\n )\n }\n }\n return new Set(listed.keys())\n }\n\n /** All spendable outputs of one basket, with locking scripts and custom instructions. */\n protected async listBasket(\n basket: string,\n originator: string,\n filter: Pick<ListOutputsArgs, 'tags' | 'tagQueryMode'>\n ): Promise<WalletOutput[]> {\n const outputs: WalletOutput[] = []\n for (;;) {\n const page = await this.wallet.listOutputs(\n {\n basket,\n tags: filter.tags,\n tagQueryMode: filter.tagQueryMode,\n include: 'locking scripts',\n includeCustomInstructions: true,\n limit: LIST_PAGE_LIMIT,\n offset: outputs.length\n },\n originator\n )\n outputs.push(...page.outputs)\n if (page.outputs.length < LIST_PAGE_LIMIT) return outputs\n }\n }\n\n protected sourceOutput(output: WalletOutput): SourceOutput {\n if (output.lockingScript === undefined)\n throw new Error('BRC-207: the wallet omitted a locking script')\n return {\n outpoint: output.outpoint,\n lockingScript: LockingScript.fromHex(output.lockingScript),\n satoshis: output.satoshis\n }\n }\n\n protected preimage(\n tx: Transaction,\n inputIndex: number,\n source: SourceOutput,\n scope: number\n ): number[] {\n if ((scope & 0x1f) === TransactionSignature.SIGHASH_SINGLE && inputIndex >= tx.outputs.length) {\n throw new Error('BRC-207: SIGHASH_SINGLE requires an output at the signed input index')\n }\n const { txid, vout } = parseOutpoint(source.outpoint)\n return TransactionSignature.format({\n sourceTXID: txid,\n sourceOutputIndex: vout,\n sourceSatoshis: source.satoshis,\n transactionVersion: tx.version,\n otherInputs: tx.inputs.filter((_, index) => index !== inputIndex),\n allInputs: tx.inputs,\n outputs: tx.outputs,\n inputIndex,\n subscript: source.lockingScript,\n inputSequence: tx.inputs[inputIndex].sequence ?? 0xffffffff,\n lockTime: tx.lockTime,\n scope\n })\n }\n\n /** Unlocking scripts for this module's inputs of `template`, keyed by input index. */\n protected async signInputs(\n template: Transaction,\n inputs: readonly ManagedInput[],\n scopes: ReadonlyMap<string, number>,\n originator: string,\n missing: string\n ): Promise<Record<number, { unlockingScript: string }>> {\n const indexed = inputs.map(input => {\n const index = template.inputs.findIndex(\n candidate => inputOutpoint(candidate) === input.outpoint\n )\n if (index < 0) throw new Error(missing)\n return { index, input }\n })\n const scripts = await Promise.all(\n indexed.map(\n async ({ index, input }) =>\n await this.unlock(\n template,\n index,\n input,\n scopes.get(input.outpoint) ?? DEFAULT_SIGHASH,\n originator\n )\n )\n )\n return Object.fromEntries(\n indexed.map(({ index }, position) => [index, { unlockingScript: scripts[position] }])\n )\n }\n\n /** P2PKH unlocking script for a managed input, signed with its `p color` key. */\n protected async unlock(\n tx: Transaction,\n inputIndex: number,\n input: ManagedInput,\n scope: number,\n originator: string\n ): Promise<string> {\n const protocolID = colorProtocolID(\n input.custody.assetId,\n input.custody.derivationPrefix,\n input.custody.derivationSuffix\n )\n const counterparty = input.custody.senderIdentityKey\n const { signature } = await this.wallet.createSignature(\n {\n protocolID,\n keyID: COLOR_KEY_ID,\n counterparty,\n hashToDirectlySign: hash256(this.preimage(tx, inputIndex, input, scope))\n },\n originator\n )\n const der = Signature.fromDER(signature)\n const checksig = new TransactionSignature(der.r, der.s, scope).toChecksigFormat()\n const publicKey = toArray(await this.publicKey(input.custody, counterparty, originator), 'hex')\n return new UnlockingScript([\n { op: checksig.length, data: checksig },\n { op: publicKey.length, data: publicKey }\n ]).toHex()\n }\n\n protected async approve(originator: string, request: Record<string, unknown>): Promise<void> {\n const approved = await this.requestTokenAccess(originator, JSON.stringify(request))\n if (approved !== true)\n throw new Error(`BRC-207: the user declined the ${String(request.type)} request`)\n }\n\n /** Every `p color` read asks the host; the host decides whether an existing grant covers it. */\n /**\n * Asks the host to approve a read, naming what is read: the `basket` requested (with the\n * `assetId` and `role` of a balance or holdings read) or the `p color` `labels` of a\n * listActions, and the caller's `seekPermission`.\n */\n protected async authorizeRead(originator: string, read: Record<string, unknown>): Promise<void> {\n await this.approve(originator, { type: 'color_access', ...read })\n }\n}\n","import { ColorPermissionModule } from './ColorPermissionModule.js'\nimport type { ColorPermissionModuleOptions } from './types.js'\n\nexport {\n ColorPermissionModule,\n actionConsent,\n assertPlanAssets,\n assertTransactionOperations,\n assertUnlocks,\n authorityOperation,\n deployOperation,\n readSentToken,\n requiredOperations,\n sighashScopes,\n submissionAssets,\n supplyChange,\n tokenSources,\n transactionConsent,\n transactionTokens,\n tryReadTokenOutput\n} from './ColorPermissionModule.js'\nexport type {\n Custody,\n Holding,\n ManagedInput,\n ReleasedSignature,\n SourceOutput,\n TransactionTokens\n} from './ColorPermissionModule.js'\nexport {\n UnsupportedProfileError,\n assertNoRequiredProfiles,\n readAnyTokenOutput,\n readJsonTokenOutput,\n readTokenOutput\n} from './tokenOutputs.js'\nexport type { JsonOperation, TokenOutput } from './tokenOutputs.js'\nexport { ColorPlan, COLOR_PLAN_LABEL_PREFIX, COLOR_OPERATIONS } from './ColorPlan.js'\nexport type { ColorOperation, ColorOperationName, ColorRemittance } from './ColorPlan.js'\nexport {\n ASSETS_SELECTOR,\n COLOR_KEY_ID,\n ISSUE,\n assetBasket,\n assetTag,\n colorProtocolID,\n colorTopic,\n parseAssetBasket,\n parseBalanceSelector,\n parseColorProtocolID\n} from './identifiers.js'\nexport type { TokenRole } from './identifiers.js'\nexport type {\n ColorOverlayProvider,\n ColorPermissionModuleOptions,\n ColorTokenAccessHandler\n} from './types.js'\n\nexport const createColorModule = (options: ColorPermissionModuleOptions): ColorPermissionModule =>\n new ColorPermissionModule(options)\n"],"mappings":";;;;;;;;AAIA,MAAa,QAAQ;;AAGrB,MAAa,eAAe;;AAG5B,MAAa,kBAAkB;;AAG/B,MAAa,yBAAyB;AAItC,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAMA,eAAa;AACnB,MAAM,2BAA2B;AACjC,MAAMC,iBAAe,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;AAO9E,SAAS,OAAO,MAAkC;CAChD,MAAM,QAAQ,OAAO,IAAI;CACzB,OAAO,SAASD,eAAa,QAAQ,KAAA;AACvC;;AAGA,SAAgB,aAAa,SAA4B;CACvD,MAAM,QAAQ,OAAO,YAAY,WAAW,SAAS,KAAK,OAAO,IAAI;CACrE,MAAM,OAAO,SAAS,OAAO,KAAA,IAAY,OAAO,MAAM,EAAE;CACxD,IAAI,SAAS,QAAQ,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,2BAA2B;CACpF,OAAO;EAAE,MAAM,MAAM;EAAI;CAAK;AAChC;;AAGA,SAAgB,mBAAmB,SAA0B;CAC3D,IAAI,YAAA,SAAmB,OAAO;CAC9B,aAAa,OAAO;CACpB,OAAO;AACT;;AAGA,SAAgB,cAAc,UAA6B;CACzD,MAAM,QAAQ,OAAO,aAAa,WAAW,SAAS,KAAK,QAAQ,IAAI;CACvE,MAAM,OAAO,SAAS,OAAO,KAAA,IAAY,OAAO,MAAM,EAAE;CACxD,IAAI,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,QAAQ,SACd,MAAM,QAAQ,kBACd,MAAM,QAAQ,gBAChB;EACA,MAAM,eAAe,MAAM,QAAQ;EACnC,MAAM,EAAE,cAAc,MAAM,KAAK,OAAO,gBACtC;GACE;GACA,OAAO;GACP;GACA,oBAAoB,QAAQ,KAAK,SAAS,IAAI,YAAY,OAAO,KAAK,CAAC;EACzE,GACA,UACF;EACA,MAAM,MAAM,UAAU,QAAQ,SAAS;EACvC,MAAM,WAAW,IAAI,qBAAqB,IAAI,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,iBAAiB;EAChF,MAAM,YAAY,QAAQ,MAAM,KAAK,UAAU,MAAM,SAAS,cAAc,UAAU,GAAG,KAAK;EAC9F,OAAO,IAAI,gBAAgB,CACzB;GAAE,IAAI,SAAS;GAAQ,MAAM;EAAS,GACtC;GAAE,IAAI,UAAU;GAAQ,MAAM;EAAU,CAC1C,CAAC,CAAC,CAAC,MAAM;CACX;CAEA,MAAgB,QAAQ,YAAoB,SAAiD;EAE3F,IAAI,MADmB,KAAK,mBAAmB,YAAY,KAAK,UAAU,OAAO,CAAC,MACjE,MACf,MAAM,IAAI,MAAM,kCAAkC,OAAO,QAAQ,IAAI,EAAE,SAAS;CACpF;;;;;;;CAQA,MAAgB,cAAc,YAAoB,MAA8C;EAC9F,MAAM,KAAK,QAAQ,YAAY;GAAE,MAAM;GAAgB,GAAG;EAAK,CAAC;CAClE;AACF;;;ACjxEA,MAAa,qBAAqB,YAChC,IAAI,sBAAsB,OAAO"}
1
+ {"version":3,"file":"index.mjs","names":["UINT32_MAX","UTF8_DECODER","toolbox"],"sources":["../src/identifiers.ts","../src/strictJson.ts","../src/ColorPlan.ts","../src/inOrder.ts","../src/overlay.ts","../src/tokenOutputs.ts","../src/ColorPermissionModule.ts","../src/index.ts"],"sourcesContent":["import { PublicKey, type WalletProtocol } from '@bsv/sdk'\nimport { sha256 } from '@bsv/sdk/primitives/Hash'\nimport { toArray, toHex } from '@bsv/sdk/primitives/utils'\n\n/** Asset selector for a deploy output's key derivation before its asset ID exists. */\nexport const ISSUE = 'ISSUE'\n\n/** Fixed BRC-43 key ID for every `p color` key. */\nexport const COLOR_KEY_ID = 'color'\n\n/** `listOutputs` selector for the inventory across every per-asset basket. */\nexport const ASSETS_SELECTOR = 'p color assets'\n\n/** Basket namespace of the per-asset value and authority baskets. */\nexport const COLOR_BASKET_NAMESPACE = 'p color'\n\nexport type TokenRole = 'value' | 'authority'\n\nconst ASSET_ID = /^([0-9a-f]{64})_(0|[1-9]\\d{0,9})$/\nconst ASSET_TAG = /^([0-9a-f]{64})v(0|[1-9]\\d{0,9})$/\nconst OUTPOINT = /^([0-9a-f]{64})\\.(0|[1-9]\\d{0,9})$/\nconst HEX_TAG = /^(?:[0-9a-f]{2})+$/\nconst IDENTITY_KEY = /^0[23][0-9a-f]{64}$/\nconst WHITESPACE = /\\s/u\nconst UINT32_MAX = 0xffffffff\nconst MAX_PROTOCOL_NAME_LENGTH = 280\n// Stryker disable next-line StringLiteral: TextDecoder('') throws ERR_ENCODING_NOT_SUPPORTED at module load, so the mutant can only be a RuntimeError, never a behavior change a test could observe\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\n\nexport interface Outpoint {\n txid: string\n vout: number\n}\n\nfunction uint32(text: string): number | undefined {\n const value = Number(text)\n return value <= UINT32_MAX ? value : undefined\n}\n\n/** Parses a canonical BRC-162 API asset ID, `<64 hex>_<vout>`. */\nexport function parseAssetId(assetId: unknown): Outpoint {\n const match = typeof assetId === 'string' ? ASSET_ID.exec(assetId) : null\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid asset ID')\n return { txid: match[1], vout }\n}\n\n/** Parses an asset ID, or `ISSUE` where a deploy output's key is meant. */\nexport function parseAssetSelector(assetId: unknown): string {\n if (assetId === ISSUE) return ISSUE\n parseAssetId(assetId)\n return assetId as string\n}\n\n/** Parses a canonical BRC-36 dot-form outpoint. */\nexport function parseOutpoint(outpoint: unknown): Outpoint {\n const match = typeof outpoint === 'string' ? OUTPOINT.exec(outpoint) : null\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid outpoint')\n return { txid: match[1], vout }\n}\n\nexport function outpointString(txid: string, vout: number): string {\n return `${txid}.${vout}`\n}\n\n/** The wire tag for an asset ID or `ISSUE` in protocol IDs and basket names. */\nexport function assetTag(assetId: string): string {\n if (assetId === ISSUE) return 'issue'\n const { txid, vout } = parseAssetId(assetId)\n return `${txid}v${vout}`\n}\n\nfunction assetIdFromTag(tag: string): string {\n if (tag === 'issue') return ISSUE\n const match = ASSET_TAG.exec(tag)\n const vout = match == null ? undefined : uint32(match[2])\n if (match == null || vout === undefined) throw new Error('BRC-207: invalid asset tag')\n return `${match[1]}_${vout}`\n}\n\n/** Validates a remittance string: nonempty strict UTF-8 without whitespace. */\nexport function validateRemittanceString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0 || WHITESPACE.test(value)) {\n throw new Error(`BRC-207: ${name} must be a nonempty string without whitespace`)\n }\n // Lone surrogates are not strict UTF-8; encoding replaces them, so the round trip differs.\n if (UTF8_DECODER.decode(new TextEncoder().encode(value)) !== value) {\n throw new Error(`BRC-207: ${name} must be strict UTF-8`)\n }\n return value\n}\n\n/** Validates a compressed secp256k1 public key in lowercase hex. */\nexport function validateIdentityKey(value: unknown, name: string): string {\n if (typeof value !== 'string' || !IDENTITY_KEY.test(value)) {\n throw new Error(`BRC-207: ${name} must be a compressed public key in lowercase hex`)\n }\n try {\n PublicKey.fromString(value)\n } catch (error) {\n throw new Error(`BRC-207: ${name} is not a valid public key (${(error as Error).message})`)\n }\n return value\n}\n\n/** The BRC-43 protocol ID `[2, \"p color <assetTag> <prefixTag> <suffixTag>\"]`. */\nexport function colorProtocolID(\n assetId: string,\n derivationPrefix: string,\n derivationSuffix: string\n): WalletProtocol {\n const prefixTag = toHex(\n toArray(validateRemittanceString(derivationPrefix, 'derivationPrefix'), 'utf8')\n )\n const suffixTag = toHex(\n toArray(validateRemittanceString(derivationSuffix, 'derivationSuffix'), 'utf8')\n )\n const name = `p color ${assetTag(assetId)} ${prefixTag} ${suffixTag}`\n if (name.length > MAX_PROTOCOL_NAME_LENGTH)\n throw new Error('BRC-207: protocol name exceeds 280 characters')\n return [2, name]\n}\n\n/** Parses a `p color` protocol ID back into its asset selector and remittance strings. */\nexport function parseColorProtocolID(protocolID: unknown): {\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n} {\n if (!Array.isArray(protocolID) || protocolID.length !== 2 || protocolID[0] !== 2) {\n throw new Error('BRC-207: p color protocols use security level 2')\n }\n const name = protocolID[1]\n const parts = typeof name === 'string' ? name.split(' ') : []\n if (\n parts.length !== 5 ||\n parts[0] !== 'p' ||\n parts[1] !== 'color' ||\n name.length > MAX_PROTOCOL_NAME_LENGTH\n ) {\n throw new Error('BRC-207: invalid p color protocol name')\n }\n const [, , tag, prefixTag, suffixTag] = parts\n if (!HEX_TAG.test(prefixTag) || !HEX_TAG.test(suffixTag)) {\n throw new Error('BRC-207: invalid p color remittance tags')\n }\n const derivationPrefix = validateRemittanceString(\n UTF8_DECODER.decode(new Uint8Array(toArray(prefixTag, 'hex'))),\n 'derivationPrefix'\n )\n const derivationSuffix = validateRemittanceString(\n UTF8_DECODER.decode(new Uint8Array(toArray(suffixTag, 'hex'))),\n 'derivationSuffix'\n )\n return { assetId: assetIdFromTag(tag), derivationPrefix, derivationSuffix }\n}\n\n/** The per-asset value or authority basket; there is no `issue` basket. */\nexport function assetBasket(assetId: string, role: TokenRole): string {\n parseAssetId(assetId)\n const basket = `${COLOR_BASKET_NAMESPACE} ${assetTag(assetId)}`\n return role === 'authority' ? `${basket} authority` : basket\n}\n\nfunction parseTaggedBasket(rest: string[]): { assetId: string; role: TokenRole } | undefined {\n if (rest.length === 0 || rest.length > 2 || (rest.length === 2 && rest[1] !== 'authority'))\n return undefined\n const assetId = assetIdFromTag(rest[0])\n if (assetId === ISSUE) throw new Error('BRC-207: issue is not a stored basket')\n return { assetId, role: rest.length === 2 ? 'authority' : 'value' }\n}\n\n/** Parses a per-asset value (`p color <assetTag>`) or authority (`... authority`) basket. */\nexport function parseAssetBasket(basket: string): { assetId: string; role: TokenRole } | undefined {\n const parts = basket.split(' ')\n if (parts[0] !== 'p' || parts[1] !== 'color' || parts[2] === 'balance' || parts[2] === 'assets')\n return undefined\n return parseTaggedBasket(parts.slice(2))\n}\n\n/** Parses a balance selector, `p color balance <assetTag>` or `... authority`. */\nexport function parseBalanceSelector(\n basket: string\n): { assetId: string; role: TokenRole } | undefined {\n const parts = basket.split(' ')\n if (parts[0] !== 'p' || parts[1] !== 'color' || parts[2] !== 'balance') return undefined\n return parseTaggedBasket(parts.slice(3))\n}\n\n/** The shared deployment discovery topic. */\nexport const DISCOVERY_TOPIC = 'tm_color'\n\nconst SUFFIX_TAG = /^p color [0-9a-f]{64}$/\n\n/**\n * The tag filed on a managed output: `p color ` and the lowercase hex of the SHA-256 of the UTF-8\n * bytes of its custody's derivation suffix. It has a fixed length whatever the suffix, and storage\n * keeps nothing of the suffix itself.\n */\nexport function derivationSuffixTag(derivationSuffix: string): string {\n return `${COLOR_BASKET_NAMESPACE} ${toHex(sha256(toArray(derivationSuffix, 'utf8')))}`\n}\n\n/** Whether a tag is a derivation suffix tag. */\nexport function isDerivationSuffixTag(tag: string): boolean {\n return SUFFIX_TAG.test(tag)\n}\n\nexport function colorTopic(assetId: string): string {\n return `tm_color_${assetId}`\n}\n","// Strict JSON for BRC-207 metadata: RFC 8259 grammar, duplicate members rejected\n// at every level, unpaired surrogate escapes rejected, bounded nesting.\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject\nexport interface JsonObject {\n [member: string]: JsonValue\n}\n\nconst MAX_DEPTH = 64\nconst UINT32_MAX = 0xffffffff\n// Stryker disable next-line StringLiteral: TextDecoder('') throws ERR_ENCODING_NOT_SUPPORTED at module load, so the mutant can only be a RuntimeError, never a behavior change a test could observe\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })\nconst NUMBER = /-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/y\nconst ESCAPES: Record<string, string> = {\n '\"': '\"',\n '\\\\': '\\\\',\n '/': '/',\n b: '\\b',\n f: '\\f',\n n: '\\n',\n r: '\\r',\n t: '\\t'\n}\n\nclass Parser {\n private position = 0\n\n constructor(\n private readonly text: string,\n private readonly label: string\n ) {}\n\n fail(reason: string): never {\n throw new Error(`BRC-207: ${this.label} is not strict JSON (${reason})`)\n }\n\n parse(): JsonValue {\n const value = this.value(0)\n this.whitespace()\n if (this.position !== this.text.length) this.fail('trailing data')\n return value\n }\n\n private whitespace(): void {\n while (this.position < this.text.length && ' \\t\\n\\r'.includes(this.text[this.position]))\n this.position++\n }\n\n private literal(word: string, value: JsonValue): JsonValue {\n if (!this.text.startsWith(word, this.position)) this.fail('invalid literal')\n this.position += word.length\n return value\n }\n\n private value(depth: number): JsonValue {\n if (depth > MAX_DEPTH) this.fail('nesting too deep')\n this.whitespace()\n const next = this.text[this.position]\n if (next === '{') return this.object(depth)\n if (next === '[') return this.array(depth)\n if (next === '\"') return this.string()\n if (next === 't') return this.literal('true', true)\n if (next === 'f') return this.literal('false', false)\n if (next === 'n') return this.literal('null', null)\n return this.number()\n }\n\n private number(): number {\n NUMBER.lastIndex = this.position\n const match = NUMBER.exec(this.text)\n if (match == null) this.fail('invalid value')\n this.position += match[0].length\n const value = Number(match[0])\n // BRC-207 integer fields are integers, not fractions: 1.0 and 1e0 are not the integer 1.\n // JSON.stringify writes every integer below 1e21 as plain digits, so only a literal in that\n // range can be a non-integer spelling of an integer.\n if (Number.isInteger(value) && Math.abs(value) < 1e21 && /[.eE]/.test(match[0]))\n this.fail('an integer written as a fraction or exponent')\n return value\n }\n\n private hex4(): number {\n const digits = this.text.slice(this.position, this.position + 4)\n if (!/^[0-9a-fA-F]{4}$/.test(digits)) this.fail('invalid unicode escape')\n this.position += 4\n return Number.parseInt(digits, 16)\n }\n\n private string(): string {\n this.position++\n let result = ''\n for (;;) {\n const char = this.text[this.position++]\n if (char === undefined) this.fail('unterminated string')\n if (char === '\"') return result\n if (char < ' ') this.fail('control character in string')\n result += char === '\\\\' ? this.escape() : char\n }\n }\n\n /** Decodes the escape after a backslash; a surrogate pair decodes to its one code point. */\n private escape(): string {\n const escape = this.text[this.position++]\n if (escape !== 'u') {\n const decoded = ESCAPES[escape]\n if (decoded === undefined) this.fail('invalid escape')\n return decoded\n }\n const unit = this.hex4()\n if (unit >= 0xdc00 && unit <= 0xdfff) this.fail('unpaired surrogate')\n if (unit < 0xd800 || unit > 0xdbff) return String.fromCodePoint(unit)\n if (this.text.slice(this.position, this.position + 2) !== String.raw`\\u`)\n this.fail('unpaired surrogate')\n this.position += 2\n const low = this.hex4()\n if (low < 0xdc00 || low > 0xdfff) this.fail('unpaired surrogate')\n return String.fromCodePoint(0x10000 + ((unit - 0xd800) << 10) + (low - 0xdc00))\n }\n\n private array(depth: number): JsonValue[] {\n this.position++\n const result: JsonValue[] = []\n this.whitespace()\n if (this.text[this.position] === ']') {\n this.position++\n return result\n }\n for (;;) {\n result.push(this.value(depth + 1))\n this.whitespace()\n const next = this.text[this.position++]\n if (next === ']') return result\n if (next !== ',') this.fail('expected , or ]')\n }\n }\n\n private object(depth: number): JsonObject {\n this.position++\n const result: JsonObject = Object.create(null)\n this.whitespace()\n if (this.text[this.position] === '}') {\n this.position++\n return result\n }\n for (;;) {\n this.whitespace()\n if (this.text[this.position] !== '\"') this.fail('expected member name')\n const name = this.string()\n if (Object.hasOwn(result, name)) this.fail(`duplicate member ${name}`)\n this.whitespace()\n if (this.text[this.position++] !== ':') this.fail('expected :')\n result[name] = this.value(depth + 1)\n this.whitespace()\n const next = this.text[this.position++]\n if (next === '}') return result\n if (next !== ',') this.fail('expected , or }')\n }\n }\n}\n\n/** Parses strict JSON text; member objects have no prototype. */\nexport function parseStrictJson(text: string, label: string): JsonValue {\n return new Parser(text, label).parse()\n}\n\n/** Decodes strict UTF-8 bytes and parses them as strict JSON. */\nexport function parseStrictJsonBytes(\n bytes: readonly number[] | Uint8Array,\n label: string\n): JsonValue {\n let text: string\n try {\n text = UTF8_DECODER.decode(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes))\n } catch {\n throw new Error(`BRC-207: ${label} is not strict UTF-8`)\n }\n return parseStrictJson(text, label)\n}\n\nexport function jsonObject(value: JsonValue | undefined, label: string): JsonObject {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`BRC-207: ${label} must be a JSON object`)\n }\n return value\n}\n\n/** Requires exactly the named members: every required one, any optional ones, nothing else. */\nexport function exactMembers(\n object: JsonObject,\n required: readonly string[],\n optional: readonly string[],\n label: string\n): void {\n for (const member of required) {\n if (!Object.hasOwn(object, member)) throw new Error(`BRC-207: ${label} is missing ${member}`)\n }\n for (const member of Object.keys(object)) {\n if (!required.includes(member) && !optional.includes(member)) {\n throw new Error(`BRC-207: ${label} has unknown member ${member}`)\n }\n }\n}\n\nexport function jsonArray(value: JsonValue | undefined, label: string): JsonValue[] {\n if (!Array.isArray(value)) throw new Error(`BRC-207: ${label} must be an array`)\n return value\n}\n\nexport function jsonUint32(value: JsonValue | undefined, label: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0 || value > UINT32_MAX) {\n throw new Error(`BRC-207: ${label} must be an integer in 0..2^32-1`)\n }\n return value\n}\n\n/** A nonempty array of integer bytes, bounded before it is copied. */\nexport function jsonByteArray(\n value: JsonValue | undefined,\n label: string,\n maxBytes: number\n): number[] {\n const array = jsonArray(value, label)\n if (array.length === 0 || array.length > maxBytes) {\n throw new Error(`BRC-207: ${label} must hold 1..${maxBytes} bytes`)\n }\n for (const byte of array) {\n if (typeof byte !== 'number' || !Number.isInteger(byte) || byte < 0 || byte > 255) {\n throw new Error(`BRC-207: ${label} must contain integer bytes`)\n }\n }\n return array as number[]\n}\n","// BRC-207 action plan codec. Carried in action labels as\n// `p color plan <partIndex> <partCount> <hexChunk>`; no wallet-toolbox dependency\n// so applications can build plans with it.\nimport { toArray, toHex } from '@bsv/sdk/primitives/utils'\nimport {\n colorProtocolID,\n ISSUE,\n parseAssetId,\n parseAssetSelector,\n parseOutpoint,\n validateIdentityKey,\n validateRemittanceString\n} from './identifiers.js'\nimport {\n exactMembers,\n jsonArray,\n jsonObject,\n jsonUint32,\n parseStrictJsonBytes,\n type JsonObject,\n type JsonValue\n} from './strictJson.js'\n\nexport const COLOR_PLAN_LABEL_PREFIX = 'p color plan '\n\nconst CHUNK_HEX_LENGTH = 200\nconst MAX_PLAN_BYTES = 16 * 1024 * 1024\n// Bounds the label count before reassembly; the joined hex is then bounded exactly.\nconst MAX_PLAN_PARTS = Math.ceil((MAX_PLAN_BYTES * 2) / CHUNK_HEX_LENGTH)\nconst PLAN_LABEL = /^p color plan (0|[1-9]\\d{0,9}) ([1-9]\\d{0,9}) ([0-9a-f]+)$/\n\nexport const COLOR_OPERATIONS = [\n 'transfer',\n 'burn',\n 'deploy-fixed',\n 'deploy-authority',\n 'mint',\n 'authority-split',\n 'authority-combine',\n 'authority-transfer',\n 'authority-end',\n 'resource'\n] as const\n\nexport type ColorOperationName = (typeof COLOR_OPERATIONS)[number]\n\n/** Key derivation facts for a managed output; `assetId` is `ISSUE` for a deploy output. */\nexport interface ColorRemittance {\n outputIndex: number\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n senderIdentityKey: string\n}\n\nexport interface ColorOperation {\n assetId: string\n operation: ColorOperationName\n}\n\n/** A BRC-207 version 1 action plan. */\nexport interface ColorPlan {\n version: 1\n assets: string[]\n ownedOutputs: ColorRemittance[]\n operations: ColorOperation[]\n inputPositions: Array<{ outpoint: string; index: number }>\n changePositions: Array<{ assetId: string | null; index: number }>\n sighashTypes: Array<{ outpoint: string; sighashType: number }>\n profileData?: Record<string, Record<string, JsonValue>>\n}\n\nfunction unique<T>(values: T[], label: string): void {\n if (new Set(values).size !== values.length) throw new Error(`BRC-207: duplicate ${label}`)\n}\n\n/** Validates a remittance object, as used by plans and signature envelopes. */\nexport function parseRemittance(value: JsonValue, label: string): ColorRemittance {\n const object = jsonObject(value, label)\n exactMembers(\n object,\n ['outputIndex', 'assetId', 'derivationPrefix', 'derivationSuffix', 'senderIdentityKey'],\n [],\n label\n )\n const remittance: ColorRemittance = {\n outputIndex: jsonUint32(object.outputIndex, `${label}.outputIndex`),\n assetId: parseAssetSelector(object.assetId),\n derivationPrefix: validateRemittanceString(\n object.derivationPrefix,\n `${label}.derivationPrefix`\n ),\n derivationSuffix: validateRemittanceString(\n object.derivationSuffix,\n `${label}.derivationSuffix`\n ),\n senderIdentityKey: validateIdentityKey(object.senderIdentityKey, `${label}.senderIdentityKey`)\n }\n colorProtocolID(remittance.assetId, remittance.derivationPrefix, remittance.derivationSuffix)\n return remittance\n}\n\n/** Validates a remittance list: at most one remittance per output index. */\nexport function parseRemittances(value: JsonValue | undefined, label: string): ColorRemittance[] {\n const remittances = jsonArray(value, label).map((item, i) =>\n parseRemittance(item, `${label}[${i}]`)\n )\n unique(\n remittances.map(remittance => remittance.outputIndex),\n `${label} output index`\n )\n return remittances\n}\n\n/** Validates optional `profileData`: profile identifier, then asset ID or `ISSUE`, then profile data. */\nexport function parseProfileData(\n value: JsonValue | undefined,\n label: string\n): Record<string, Record<string, JsonValue>> | undefined {\n if (value === undefined) return undefined\n const profiles = jsonObject(value, label)\n const result: Record<string, Record<string, JsonValue>> = Object.create(null)\n for (const [profile, assets] of Object.entries(profiles)) {\n const byAsset = jsonObject(assets, `${label}.${profile}`)\n for (const assetId of Object.keys(byAsset)) parseAssetSelector(assetId)\n result[profile] = { ...byAsset }\n }\n return result\n}\n\nfunction parsePlan(value: JsonValue): ColorPlan {\n const object: JsonObject = jsonObject(value, 'plan')\n exactMembers(\n object,\n [\n 'version',\n 'assets',\n 'ownedOutputs',\n 'operations',\n 'inputPositions',\n 'changePositions',\n 'sighashTypes'\n ],\n ['profileData'],\n 'plan'\n )\n if (object.version !== 1) throw new Error('BRC-207: plan version must be 1')\n const assets = jsonArray(object.assets, 'plan.assets').map(asset => parseAssetSelector(asset))\n unique(assets, 'plan asset')\n const operations = jsonArray(object.operations, 'plan.operations').map((item, i) => {\n const operation = jsonObject(item, `plan.operations[${i}]`)\n exactMembers(operation, ['assetId', 'operation'], [], `plan.operations[${i}]`)\n if (!COLOR_OPERATIONS.includes(operation.operation as ColorOperationName)) {\n throw new Error(`BRC-207: plan.operations[${i}] has an unknown operation`)\n }\n return {\n assetId: parseAssetSelector(operation.assetId),\n operation: operation.operation as ColorOperationName\n }\n })\n unique(\n operations.map(operation => `${operation.assetId} ${operation.operation}`),\n 'plan operation'\n )\n const inputPositions = jsonArray(object.inputPositions, 'plan.inputPositions').map((item, i) => {\n const position = jsonObject(item, `plan.inputPositions[${i}]`)\n exactMembers(position, ['outpoint', 'index'], [], `plan.inputPositions[${i}]`)\n parseOutpoint(position.outpoint)\n return {\n outpoint: position.outpoint as string,\n index: jsonUint32(position.index, `plan.inputPositions[${i}].index`)\n }\n })\n unique(\n inputPositions.map(position => position.outpoint),\n 'plan input position outpoint'\n )\n unique(\n inputPositions.map(position => position.index),\n 'plan input position index'\n )\n const changePositions = jsonArray(object.changePositions, 'plan.changePositions').map(\n (item, i) => {\n const position = jsonObject(item, `plan.changePositions[${i}]`)\n exactMembers(position, ['assetId', 'index'], [], `plan.changePositions[${i}]`)\n if (position.assetId !== null) parseAssetId(position.assetId)\n return {\n assetId: position.assetId as string | null,\n index: jsonUint32(position.index, `plan.changePositions[${i}].index`)\n }\n }\n )\n unique(\n changePositions.map(position => position.assetId),\n 'plan change position asset'\n )\n unique(\n changePositions.map(position => position.index),\n 'plan change position index'\n )\n const sighashTypes = jsonArray(object.sighashTypes, 'plan.sighashTypes').map((item, i) => {\n const override = jsonObject(item, `plan.sighashTypes[${i}]`)\n exactMembers(override, ['outpoint', 'sighashType'], [], `plan.sighashTypes[${i}]`)\n parseOutpoint(override.outpoint)\n const sighashType = jsonUint32(override.sighashType, `plan.sighashTypes[${i}].sighashType`)\n if (sighashType > 255)\n throw new Error(`BRC-207: plan.sighashTypes[${i}].sighashType must be in 0..255`)\n return { outpoint: override.outpoint as string, sighashType }\n })\n unique(\n sighashTypes.map(override => override.outpoint),\n 'plan sighash override outpoint'\n )\n const plan: ColorPlan = {\n version: 1,\n assets,\n ownedOutputs: parseRemittances(object.ownedOutputs, 'plan.ownedOutputs'),\n operations,\n inputPositions,\n changePositions,\n sighashTypes\n }\n const profileData = parseProfileData(object.profileData, 'plan.profileData')\n if (profileData !== undefined) plan.profileData = profileData\n const referenced = [\n ...plan.ownedOutputs.map(remittance => remittance.assetId),\n ...plan.operations.map(operation => operation.assetId),\n ...plan.changePositions.flatMap(position =>\n position.assetId === null ? [] : [position.assetId]\n )\n ]\n for (const assetId of referenced) {\n if (!assets.includes(assetId))\n throw new Error(`BRC-207: plan references ${assetId} outside plan.assets`)\n }\n if (\n assets.includes(ISSUE) &&\n plan.operations.filter(op => op.operation.startsWith('deploy-')).length !== 1\n ) {\n throw new Error('BRC-207: a deploy plan has exactly one deploy operation')\n }\n return plan\n}\n\n/** Every chunk is whole hex bytes; every chunk but the last fills its label. */\nfunction assertPlanChunk(hex: string, index: number, count: number): void {\n if (hex.length % 2 !== 0 || hex.length > CHUNK_HEX_LENGTH)\n throw new Error('BRC-207: invalid plan chunk')\n if (index < count - 1 && hex.length !== CHUNK_HEX_LENGTH)\n throw new Error('BRC-207: short nonfinal plan chunk')\n}\n\n/** Encodes and decodes BRC-207 action plans as `p color plan` labels. */\nexport const ColorPlan = {\n /** Splits a plan into `p color plan <i> <n> <hex>` labels after validating it. */\n toLabels(plan: ColorPlan): string[] {\n const bytes = toArray(JSON.stringify(plan), 'utf8')\n if (bytes.length > MAX_PLAN_BYTES) throw new Error('BRC-207: plan exceeds 16 MiB')\n parsePlan(parseStrictJsonBytes(bytes, 'plan'))\n const hex = toHex(bytes)\n const count = Math.ceil(hex.length / CHUNK_HEX_LENGTH)\n return Array.from(\n { length: count },\n (_, i) =>\n `${COLOR_PLAN_LABEL_PREFIX}${i} ${count} ${hex.slice(i * CHUNK_HEX_LENGTH, (i + 1) * CHUNK_HEX_LENGTH)}`\n )\n },\n\n /** Reassembles the plan from its labels; undefined when no plan labels are present. */\n fromLabels(labels: readonly string[] | undefined): ColorPlan | undefined {\n const parts = (labels ?? []).filter(label => label.startsWith(COLOR_PLAN_LABEL_PREFIX))\n if (parts.length === 0) return undefined\n let count: number | undefined\n const chunks: string[] = []\n for (const label of parts) {\n const match = PLAN_LABEL.exec(label)\n if (match == null) throw new Error('BRC-207: invalid p color plan label')\n const index = Number(match[1])\n const partCount = Number(match[2])\n const hex = match[3]\n if (partCount > MAX_PLAN_PARTS) throw new Error('BRC-207: plan exceeds 16 MiB')\n if (count !== undefined && count !== partCount)\n throw new Error('BRC-207: inconsistent plan part counts')\n count = partCount\n if (index >= partCount) throw new Error('BRC-207: plan part index out of range')\n if (chunks[index] !== undefined) throw new Error('BRC-207: duplicate plan part')\n assertPlanChunk(hex, index, partCount)\n chunks[index] = hex\n }\n if (count === undefined || parts.length !== count) throw new Error('BRC-207: missing plan part')\n const hex = chunks.join('')\n if (hex.length > MAX_PLAN_BYTES * 2) throw new Error('BRC-207: plan exceeds 16 MiB')\n return parsePlan(parseStrictJsonBytes(toArray(hex, 'hex'), 'plan'))\n }\n}\n","/**\n * Runs `step` on each item strictly in order, as a `for … of` loop with `await` would: an item\n * starts only after the previous one has finished, and the first throw ends the run with that\n * same error. Checks rely on this, so the refusal reported is always the first one in order, and\n * steps that reserve outputs never race each other.\n */\nexport async function eachInOrder<T>(\n items: Iterable<T>,\n step: (item: T) => Promise<void> | void\n): Promise<void> {\n await Array.from(items).reduce<Promise<void>>(async (previous, item) => {\n // reduce invokes every callback up front, so nothing may run before this await.\n await previous\n await step(item)\n }, Promise.resolve())\n}\n\n/** {@link eachInOrder}, collecting each step's result in item order. */\nexport async function mapInOrder<T, R>(\n items: Iterable<T>,\n step: (item: T, index: number) => Promise<R> | R\n): Promise<R[]> {\n const results: R[] = []\n let index = 0\n await eachInOrder(items, async item => {\n results.push(await step(item, index++))\n })\n return results\n}\n","import { Transaction, type LockingScript, type LookupAnswer } from '@bsv/sdk'\n\nexport interface ListedOutput {\n outpoint: string\n lockingScript: LockingScript\n satoshis: number\n}\n\n/**\n * Reads a BRC-24 `output-list` answer to a `color-spendability` or `color-admission`\n * query. Every returned output must be one of the queried outpoints, at most once;\n * an unrelated, duplicate or malformed entry invalidates the whole answer.\n */\nexport function readOutputList(\n answer: LookupAnswer,\n queried: readonly string[]\n): Map<string, ListedOutput> {\n if (answer?.type !== 'output-list' || !Array.isArray(answer.outputs)) {\n throw new Error('BRC-207: overlay answer is not an output list')\n }\n const listed = new Map<string, ListedOutput>()\n const wanted = new Set(queried)\n for (const item of answer.outputs) {\n let transaction: Transaction\n try {\n transaction = Transaction.fromBEEF(item.beef, item.txid)\n } catch {\n throw new Error('BRC-207: overlay answer carries invalid BEEF')\n }\n const output = Number.isSafeInteger(item.outputIndex)\n ? transaction.outputs[item.outputIndex]\n : undefined\n if (output?.satoshis === undefined)\n throw new Error('BRC-207: overlay answer names a missing output')\n const outpoint = `${transaction.id('hex')}.${item.outputIndex}`\n if (!wanted.has(outpoint))\n throw new Error(`BRC-207: overlay answered an unrelated output ${outpoint}`)\n if (listed.has(outpoint)) throw new Error(`BRC-207: overlay answered ${outpoint} twice`)\n listed.set(outpoint, {\n outpoint,\n lockingScript: output.lockingScript,\n satoshis: output.satoshis\n })\n }\n return listed\n}\n","import type { LockingScript } from '@bsv/sdk'\nimport {\n Bsv21Token,\n isTokenShaped,\n OneColor,\n StrictCborLink,\n tryDecodeStrictCbor\n} from '@bsv/templates'\nimport type {\n Bsv21Envelope,\n Bsv21TokenDecoded,\n StrictCborMap,\n StrictCborValue\n} from '@bsv/templates'\nimport { parseAssetId, type Outpoint, type TokenRole } from './identifiers.js'\n\nexport interface TokenOutput {\n assetId: string\n role: TokenRole\n amount: bigint\n /** True for the asset's deploy output, whose key uses the `ISSUE` selector. */\n deploy: boolean\n /** BRC-162 binary, or BRC-161 JSON, which this module reads but never holds or creates. */\n encoding: 'brc162' | 'brc161'\n /** Set when the remainder after the prefix is exactly P2PKH. */\n pubKeyHash?: number[]\n /** A JSON output's operation; a `mint` is funded by an authority input, not by value inputs. */\n jsonOperation?: JsonOperation\n}\n\n/** The BRC-161 operations this module reads: value outputs, and the authority outputs. */\nexport type JsonOperation = 'transfer' | 'mint' | 'deploy+mint' | 'auth' | 'deploy+auth'\n\nconst PROFILE_ID = /^[a-z][a-z0-9+.-]*:[\\x21-\\x7e]+$/\n\n/** A decoded DAG-CBOR map, as opposed to an array, bytes, a link or a scalar. */\nfunction isCborMap(value: StrictCborValue | undefined): value is StrictCborMap {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array) &&\n !(value instanceof StrictCborLink)\n )\n}\n\n/** Reads `req` and `ext` from a payload; an absent, opaque or non-map payload has none. */\nfunction readPayloadMaps(payload: number[] | undefined): {\n req?: StrictCborMap\n ext?: StrictCborMap\n} {\n if (payload === undefined || payload.length === 0) return {}\n // Strict DAG-CBOR, as BRC-162 requires (L144); anything else is an opaque payload.\n const decoded = tryDecodeStrictCbor(payload)\n if (decoded === undefined) return {}\n const req = decoded.req\n const ext = decoded.ext\n if (req !== undefined && !isCborMap(req))\n throw new Error('BRC-207: malformed req in a BRC-162 payload')\n if (ext !== undefined && !isCborMap(ext))\n throw new Error('BRC-207: malformed ext in a BRC-162 payload')\n for (const profile of [...Object.keys(req ?? {}), ...Object.keys(ext ?? {})]) {\n if (profile.length > 200 || !PROFILE_ID.test(profile)) {\n throw new Error('BRC-207: invalid processing-profile identifier in a BRC-162 payload')\n }\n }\n return { req, ext }\n}\n\n/**\n * A valid BRC-162 output of an asset that requires processing profiles. BRC-207 has an\n * unsupported profile fail, never fall back, so readers that otherwise treat an unreadable\n * script as plain satoshis let this error through.\n */\nexport class UnsupportedProfileError extends Error {\n constructor() {\n super('BRC-207: the asset requires processing profiles this wallet does not support')\n this.name = 'UnsupportedProfileError'\n }\n}\n\n/**\n * Fails unless a payload declares no required processing profiles. This module supports\n * none, so a deploy `req` with entries, or a later output repeating a nonempty `req`, fails.\n */\nexport function assertNoRequiredProfiles(payload: number[] | undefined): void {\n const { req } = readPayloadMaps(payload)\n if (req !== undefined && Object.keys(req).length > 0) throw new UnsupportedProfileError()\n}\n\n/**\n * Reads a BRC-162 token output. Returns undefined for a script without the token\n * layout; throws for a token-shaped script that is invalid or unsupported here.\n */\nexport function readTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n if (!isTokenShaped(lockingScript)) return undefined\n let decoded: ReturnType<typeof OneColor.decode>\n try {\n decoded = OneColor.decode(lockingScript)\n } catch (error) {\n throw new Error(\n `BRC-207: ${outpoint.txid}.${outpoint.vout} is not a supported BRC-162 output (${(error as Error).message})`\n )\n }\n assertNoRequiredProfiles(decoded.payload)\n const deploy = decoded.role === 'deploy'\n if (deploy && outpoint.vout !== 0) throw new Error('BRC-207: a BRC-162 deploy must be output 0')\n return {\n assetId: deploy ? `${outpoint.txid}_0` : OneColor.tokenIdToString(decoded.tokenId!),\n role: decoded.amount === 0n ? 'authority' : 'value',\n amount: decoded.amount,\n deploy,\n encoding: 'brc162',\n pubKeyHash: decoded.restPubKeyHash\n }\n}\n\nconst BSV20_CONTENT_TYPE = 'application/bsv-20'\nconst MAX_UINT64 = (1n << 64n) - 1n\nconst VALUE_OPERATIONS = new Set<string>(['transfer', 'mint', 'deploy+mint'])\nconst JSON_AUTHORITY_OPERATIONS = new Set<string>(['auth', 'deploy+auth'])\n\n/**\n * Reads a BRC-161 JSON token output: a BRC-160 `ord` inscription of type `application/bsv-20`\n * anywhere in the script, located by `Bsv21Token`. Returns undefined for a script without such an\n * inscription. `transfer`, `mint` and `deploy+mint` outputs carry value (BRC-161 L262); `auth` and\n * `deploy+auth` are authority outputs of no value (L191-207); `burn` fails as unsupported, as does\n * a malformed inscription.\n */\nexport function readJsonTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n const malformed = (reason: string): Error =>\n new Error(\n `BRC-207: ${outpoint.txid}.${outpoint.vout} is a malformed BRC-161 inscription (${reason})`\n )\n let envelope: Bsv21Envelope | undefined\n try {\n envelope = Bsv21Token.envelope(lockingScript)\n } catch (error) {\n throw malformed((error as Error).message)\n }\n if (envelope === undefined || envelope.contentType !== BSV20_CONTENT_TYPE) return undefined\n let decoded: Bsv21TokenDecoded\n try {\n decoded = Bsv21Token.decode(lockingScript)\n } catch (error) {\n throw malformed((error as Error).message)\n }\n const op = decoded.op\n if (op === 'burn')\n throw new Error(`BRC-207: BRC-161 ${op} is an operation this module does not support`)\n const authority = JSON_AUTHORITY_OPERATIONS.has(op)\n if (!authority && !VALUE_OPERATIONS.has(op)) throw malformed('unknown op')\n const jsonOperation = op as JsonOperation\n const amount = BigInt(decoded.amt)\n if (amount > MAX_UINT64) throw malformed('amt is not a uint64')\n if (!authority && amount === 0n) throw malformed('amt must be positive')\n const role: TokenRole = authority ? 'authority' : 'value'\n if (op === 'deploy+mint' || op === 'deploy+auth') {\n return {\n assetId: `${outpoint.txid}_${outpoint.vout}`,\n role,\n amount,\n deploy: true,\n encoding: 'brc161',\n jsonOperation\n }\n }\n try {\n parseAssetId(decoded.id)\n } catch {\n throw malformed('id is not a token ID')\n }\n return { assetId: decoded.id, role, amount, deploy: false, encoding: 'brc161', jsonOperation }\n}\n\n/** Reads a token output in either encoding; binary wins when a script parses as both (BRC-162). */\nexport function readAnyTokenOutput(\n lockingScript: LockingScript,\n outpoint: Outpoint\n): TokenOutput | undefined {\n return readTokenOutput(lockingScript, outpoint) ?? readJsonTokenOutput(lockingScript, outpoint)\n}\n\n/**\n * True when the script is an asset's deploy: a BRC-162 binary deploy, whose `req` must be\n * empty here, or a BRC-161 JSON deploy+mint, which carries no processing profiles.\n */\nexport function isDeployOutput(lockingScript: LockingScript, outpoint: Outpoint): boolean {\n return readAnyTokenOutput(lockingScript, outpoint)?.deploy === true\n}\n","import {\n Beef,\n LockingScript,\n Signature,\n Spend,\n Transaction,\n TransactionSignature,\n UnlockingScript,\n type AtomicBEEF,\n type BEEF,\n type BasketInsertion,\n type CreateActionArgs,\n type CreateActionInput,\n type CreateActionOutput,\n type CreateActionResult,\n type CreateSignatureArgs,\n type InternalizeActionArgs,\n type ListActionsArgs,\n type ListOutputsArgs,\n type ListOutputsResult,\n type SignActionArgs,\n type SignActionResult,\n type WalletCounterparty,\n type WalletInterface,\n type WalletOutput\n} from '@bsv/sdk'\nimport { hash160, hash256 } from '@bsv/sdk/primitives/Hash'\nimport Random from '@bsv/sdk/primitives/Random'\nimport { toArray, toBase64, toHex } from '@bsv/sdk/primitives/utils'\nimport { OneColor } from '@bsv/templates'\nimport {\n encryptMetadata,\n maybeDecryptMetadata,\n sdk as toolbox,\n type PermissionsModule,\n type PermissionsModuleAction,\n type PermissionsModuleNext,\n type PermissionsModuleRequest\n} from '@bsv/wallet-toolbox-client'\nimport {\n ColorPlan,\n type ColorOperationName,\n parseProfileData,\n parseRemittances,\n type ColorRemittance,\n COLOR_PLAN_LABEL_PREFIX\n} from './ColorPlan.js'\nimport {\n ASSETS_SELECTOR,\n assetBasket,\n COLOR_BASKET_NAMESPACE,\n COLOR_KEY_ID,\n colorProtocolID,\n colorTopic,\n derivationSuffixTag,\n isDerivationSuffixTag,\n DISCOVERY_TOPIC,\n ISSUE,\n outpointString,\n parseAssetBasket,\n parseAssetId,\n parseAssetSelector,\n parseBalanceSelector,\n parseColorProtocolID,\n parseOutpoint,\n validateIdentityKey,\n validateRemittanceString,\n type TokenRole\n} from './identifiers.js'\nimport { eachInOrder, mapInOrder } from './inOrder.js'\nimport { readOutputList } from './overlay.js'\nimport {\n exactMembers,\n jsonByteArray,\n jsonObject,\n jsonUint32,\n parseStrictJsonBytes\n} from './strictJson.js'\nimport {\n isDeployOutput,\n readAnyTokenOutput,\n readJsonTokenOutput,\n readTokenOutput,\n UnsupportedProfileError,\n type TokenOutput\n} from './tokenOutputs.js'\nimport type {\n ColorOverlayProvider,\n ColorPermissionModuleOptions,\n ColorTokenAccessHandler\n} from './types.js'\n\nconst UNLOCKING_SCRIPT_LENGTH = 108\nconst TOKEN_CARRIER_SATOSHIS = 1\nconst DEFAULT_SIGHASH = TransactionSignature.SIGHASH_ALL | TransactionSignature.SIGHASH_FORKID\nconst MAX_ENVELOPE_BYTES = 16 * 1024 * 1024\nconst MAX_RECEIPT_INSTRUCTION_BYTES = 1000\nconst LIST_PAGE_LIMIT = 10_000\nconst SUBMIT_ATTEMPTS = 3\nconst NOSEND_EXPIRY_LABEL_PREFIX = 'p nosend expiry '\nconst STATE_TAG_PREFIX = 'color_state_'\nconst UTF8_ENCODER = new TextEncoder()\n\n/** The derivation tuple a managed output's key was created with; `assetId` is `ISSUE` for a deploy. */\nexport interface Custody {\n assetId: string\n derivationPrefix: string\n derivationSuffix: string\n senderIdentityKey: string\n}\n\nexport interface SourceOutput {\n outpoint: string\n lockingScript: LockingScript\n satoshis: number\n}\n\n/** A basket output that may be selected, read from its locking script before any custody is read. */\ninterface Candidate extends SourceOutput {\n token: TokenOutput\n amount: bigint\n customInstructions: string\n /** The tags the wallet listed for the output. */\n tags: readonly string[]\n}\n\nexport interface ManagedInput extends SourceOutput {\n assetId: string\n role: TokenRole\n amount: bigint\n custody: Custody\n /** The source transaction as BEEF, when the module made it (a handoff split). */\n sourceBEEF?: BEEF\n}\n\ntype InventoryState = 'available' | 'reserved'\n\n/** Runs an SDK parser on untrusted input, prefixing its failure as a BRC-207 error. */\nfunction parsed<T>(label: string, parse: () => T): T {\n try {\n return parse()\n } catch (error) {\n throw new Error(`BRC-207: ${label} is invalid (${(error as Error).message})`)\n }\n}\n\nfunction sumAmounts(inputs: ReadonlyArray<{ amount: bigint }>): bigint {\n return inputs.reduce((total, input) => total + input.amount, 0n)\n}\n\nfunction inputOutpoint(input: Transaction['inputs'][number]): string {\n const txid = input.sourceTXID ?? input.sourceTransaction?.id('hex')\n if (txid === undefined) throw new Error('BRC-207: transaction input has no source transaction ID')\n return outpointString(txid, input.sourceOutputIndex)\n}\n\nfunction custodyOf(remittance: ColorRemittance): Custody {\n const { assetId, derivationPrefix, derivationSuffix, senderIdentityKey } = remittance\n return { assetId, derivationPrefix, derivationSuffix, senderIdentityKey }\n}\n\n/** Whether `beef` holds the transaction `txid` in full, not by txid alone. */\nfunction holdsTransaction(beef: Beef, txid: string): boolean {\n const found = beef.findTxid(txid)\n return found !== undefined && !found.isTxidOnly\n}\n\n/**\n * Merges the source transaction of `outpoint` from `from` into `into` with only its own proof or\n * unproven ancestors, so other transactions in `from` are left out.\n */\nfunction mergeSource(into: Beef, from: Beef, outpoint: string): void {\n const { txid } = parseOutpoint(outpoint)\n if (!holdsTransaction(from, txid))\n throw new Error(\n `BRC-207: the wallet returned no source transaction for token input ${outpoint}`\n )\n into.mergeBeef(from.toBinaryAtomic(txid))\n}\n\n/** The tag every output the module files carries: the module finds an output's transaction by it. */\nfunction suffixTagOf(custody: { derivationSuffix: string }): string {\n return derivationSuffixTag(custody.derivationSuffix)\n}\n\n/** `tags` with the custody's suffix tag added. */\nfunction withSuffixTag(\n tags: readonly string[] | undefined,\n custody: { derivationSuffix: string }\n): string[] {\n return [...new Set([...(tags ?? []), suffixTagOf(custody)])]\n}\n\n/** Whether a listed output carries the suffix tag of its custody. */\nfunction carriesSuffixTag(tags: readonly string[] | undefined, custody: Custody): boolean {\n return tags?.includes(suffixTagOf(custody)) === true\n}\n\n/** The BEEF a listOutputs result returns, empty when it returns none. */\nfunction listingBeef(listing: ListOutputsResult): Beef {\n return listing.BEEF === undefined ? new Beef() : Beef.fromBinary(listing.BEEF)\n}\n\nfunction tokenInputs(inputs: readonly ManagedInput[]): CreateActionInput[] {\n return inputs.map(input => ({\n outpoint: input.outpoint,\n unlockingScriptLength: UNLOCKING_SCRIPT_LENGTH,\n inputDescription: 'BRC-207 token input'\n }))\n}\n\nfunction custodyInstructions(custody: Custody): string {\n return JSON.stringify({ version: 1, ...custody })\n}\n\n/** Parses the receipt-format custody JSON stored in, or supplied as, an output's custom instructions. */\nfunction parseCustody(text: string, maxBytes: number | undefined, label: string): Custody {\n const bytes = UTF8_ENCODER.encode(text)\n if (maxBytes !== undefined && bytes.length > maxBytes)\n throw new Error(`BRC-207: ${label} exceeds ${maxBytes} bytes`)\n const object = jsonObject(parseStrictJsonBytes(bytes, label), label)\n exactMembers(\n object,\n ['version', 'assetId', 'derivationPrefix', 'derivationSuffix', 'senderIdentityKey'],\n ['profileData'],\n label\n )\n if (object.version !== 1) throw new Error(`BRC-207: ${label} version must be 1`)\n const profileData = parseProfileData(object.profileData, `${label}.profileData`)\n if (profileData !== undefined && Object.keys(profileData).length > 0) {\n throw new Error(`BRC-207: ${label}.profileData names a profile the asset does not require`)\n }\n return {\n assetId: parseAssetSelector(object.assetId),\n derivationPrefix: validateRemittanceString(\n object.derivationPrefix,\n `${label}.derivationPrefix`\n ),\n derivationSuffix: validateRemittanceString(\n object.derivationSuffix,\n `${label}.derivationSuffix`\n ),\n senderIdentityKey: validateIdentityKey(object.senderIdentityKey, `${label}.senderIdentityKey`)\n }\n}\n\n/** True when a custody selector names the output's asset: `ISSUE` exactly for its deploy. */\nfunction selectsAsset(selector: string, token: TokenOutput): boolean {\n return selector === ISSUE ? token.deploy : !token.deploy && selector === token.assetId\n}\n\n/** One asset's token units and authority outputs on one side of a transaction. */\nexport interface Holding {\n value: bigint\n authority: number\n /** The part of `value` in BRC-161 transfer outputs, which only value inputs can fund. */\n jsonValue?: bigint\n}\n\n/** What the caller's explicit inputs contribute to one asset, and how much of it is foreign. */\ninterface ExplicitHolding extends Holding {\n foreignValue: bigint\n foreignAuthority: number\n}\n\n/** The caller's explicit inputs and what they contribute per asset. */\ninterface ExplicitInputs {\n inputs: CreateActionInput[]\n managed: ManagedInput[]\n holdings: Map<string, ExplicitHolding>\n}\n\n/** The requested outputs' token totals per existing asset, the deploy, and the outputs that leave the wallet. */\ninterface PlannedOutputs {\n holdings: Map<string, Holding>\n deploy?: { operation: ColorOperationName }\n destinations: Array<{\n outputIndex: number\n assetId: string\n role: TokenRole\n amount: string\n lockingScript: string\n }>\n}\n\n/** One existing asset's funding: its selected inputs, token change and resulting outputs. */\ninterface AssetFunding {\n assetId: string\n selected: ManagedInput[]\n change: bigint\n outputs: Holding\n}\n\nconst AUTHORITY_OPERATIONS: readonly ColorOperationName[] = [\n 'authority-split',\n 'authority-combine',\n 'authority-transfer',\n 'authority-end'\n]\n\nfunction holding<T extends Holding>(totals: Map<string, T>, assetId: string, empty: () => T): T {\n let entry = totals.get(assetId)\n if (entry === undefined) {\n entry = empty()\n totals.set(assetId, entry)\n }\n return entry\n}\n\nfunction emptyHolding(): Holding {\n return { value: 0n, authority: 0 }\n}\n\nfunction emptyExplicitHolding(): ExplicitHolding {\n return { value: 0n, authority: 0, foreignValue: 0n, foreignAuthority: 0 }\n}\n\n/** The BRC-207 authority operation for a transaction's authority input and output counts. */\nexport function authorityOperation(inputs: number, outputs: number): ColorOperationName {\n if (outputs === 0) return 'authority-end'\n if (outputs < inputs) return 'authority-combine'\n return outputs === inputs ? 'authority-transfer' : 'authority-split'\n}\n\n/** Authority inputs to select for a declared authority operation when the caller supplies none. */\nfunction authorityInputsFor(operation: ColorOperationName, outputs: number): number {\n if (operation === 'authority-transfer') return outputs\n if (operation === 'authority-combine') return outputs + 1\n return 1\n}\n\n/**\n * The operations BRC-207 requires for one existing asset: value inputs fund value outputs\n * first, the rest of the inputs is burned and the rest of the outputs is minted.\n */\nexport function requiredOperations(inputs: Holding, outputs: Holding): ColorOperationName[] {\n if (inputs.authority === 0 && outputs.authority > 0)\n throw new Error('BRC-207: an authority output needs an authority input of the same asset')\n if ((outputs.jsonValue ?? 0n) > inputs.value)\n throw new Error(\n 'BRC-207: BRC-161 transfer outputs exceed the value inputs; an authority cannot fund them'\n )\n const { transferred, burned, minted } = supplyChange(inputs, outputs)\n if (minted > 0n && inputs.authority === 0)\n throw new Error('BRC-207: token outputs exceed the authenticated input balance')\n const operations: ColorOperationName[] = []\n if (transferred > 0n) operations.push('transfer')\n if (burned > 0n) operations.push('burn')\n if (minted > 0n) operations.push('mint')\n if (inputs.authority > 0) operations.push(authorityOperation(inputs.authority, outputs.authority))\n return operations\n}\n\nfunction declaredOperations(plan: ColorPlan, assetId: string): Set<ColorOperationName> {\n return new Set(\n plan.operations.filter(operation => operation.assetId === assetId).map(op => op.operation)\n )\n}\n\n/** Fails unless the plan declares exactly the operations the asset's transaction requires. */\nfunction assertOperations(plan: ColorPlan, assetId: string, required: ColorOperationName[]): void {\n const declared = declaredOperations(plan, assetId)\n if (declared.size !== required.length || required.some(operation => !declared.has(operation))) {\n throw new Error(\n `BRC-207: ${assetId} requires the operations [${required.join(', ')}] but the plan declares [${[...declared].join(', ')}]`\n )\n }\n}\n\n/** Supply accounting: value inputs fund value outputs first; the rest is burned or minted. */\nexport function supplyChange(\n inputs: Holding,\n outputs: Holding\n): { transferred: bigint; burned: bigint; minted: bigint } {\n const transferred = outputs.value < inputs.value ? outputs.value : inputs.value\n return {\n transferred,\n burned: inputs.value - transferred,\n minted: outputs.value - transferred\n }\n}\n\n/**\n * What the user approves for a funded action: every asset leg, with this wallet's and foreign\n * inputs, kept and outgoing outputs and the supply change; satoshi totals and fee; the\n * signatures the module releases; and the lock time.\n */\nexport function actionConsent(\n plan: ColorPlan,\n createArgs: CreateActionArgs,\n tx: Transaction,\n tokens: TransactionTokens,\n managed: readonly ManagedInput[],\n scopes: ReadonlyMap<string, number>\n): Record<string, unknown> {\n const requested = createArgs.outputs ?? []\n const kept = (index: number): boolean =>\n requested[index]?.basket?.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true ||\n plan.ownedOutputs.some(remittance => remittance.outputIndex === index)\n return {\n type: 'color_send',\n handoff: (createArgs.labels ?? []).some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX)),\n ...transactionConsent(\n tx,\n tokens,\n managed,\n kept,\n vout => vout < requested.length && !kept(vout),\n managed.map(input => ({\n outpoint: input.outpoint,\n inputIndex: tx.inputs.findIndex(candidate => inputOutpoint(candidate) === input.outpoint),\n sighashType: scopes.get(input.outpoint) ?? DEFAULT_SIGHASH\n })),\n plan.ownedOutputs.some(remittance => remittance.outputIndex === 0)\n )\n }\n}\n\nexport interface ReleasedSignature {\n outpoint: string\n inputIndex: number\n sighashType: number\n}\n\n/**\n * The facts the user approves for any transaction this wallet signs token inputs of, whether the\n * wallet funded it or an app built it: every asset leg with this wallet's (`own`) and foreign\n * inputs, kept and outgoing outputs and the supply change; the destinations; satoshi totals and\n * fee; the signatures released; and the lock time.\n */\nexport function transactionConsent(\n tx: Transaction,\n tokens: TransactionTokens,\n own: ReadonlyArray<{ assetId: string; role: TokenRole; amount: bigint }>,\n kept: (vout: number) => boolean,\n destination: (vout: number) => boolean,\n signatures: ReleasedSignature[],\n deployOwned: boolean\n): Record<string, unknown> {\n const txid = tx.id('hex')\n const outputs = tx.outputs.map((output, vout) => ({\n vout,\n token: readSentToken(output.lockingScript, { txid, vout }),\n satoshis: output.satoshis ?? 0\n }))\n const assets = [...new Set([...tokens.inputs.keys(), ...tokens.outputs.keys()])].map(assetId => {\n const ownInputs = own.filter(input => input.assetId === assetId)\n const inputs = tokens.inputs.get(assetId) ?? emptyHolding()\n const all = tokens.outputs.get(assetId) ?? emptyHolding()\n const keptOutputs = outputs.filter(\n output => output.token?.assetId === assetId && !output.token.deploy && kept(output.vout)\n )\n const { transferred, burned, minted } = supplyChange(inputs, all)\n return {\n assetId,\n operations: requiredOperations(inputs, all),\n inputAmount: sumAmounts(ownInputs).toString(),\n foreignAmount: (inputs.value - sumAmounts(ownInputs)).toString(),\n authorityInputs: ownInputs.filter(input => input.role === 'authority').length,\n foreignAuthorityInputs:\n inputs.authority - ownInputs.filter(input => input.role === 'authority').length,\n keptAmount: sumAmounts(keptOutputs.map(output => output.token!)).toString(),\n keptAuthorities: keptOutputs.filter(output => output.token!.role === 'authority').length,\n outgoingAmount: (all.value - sumAmounts(keptOutputs.map(output => output.token!))).toString(),\n outgoingAuthorities:\n all.authority - keptOutputs.filter(output => output.token!.role === 'authority').length,\n transferred: transferred.toString(),\n burned: burned.toString(),\n minted: minted.toString()\n }\n })\n const inputSatoshis = tx.inputs.reduce(\n (total, input) =>\n total + (input.sourceTransaction!.outputs[input.sourceOutputIndex].satoshis ?? 0),\n 0\n )\n const outputSatoshis = outputs.reduce((total, output) => total + output.satoshis, 0)\n return {\n ...(tokens.deploy === undefined\n ? {}\n : {\n deploy: {\n operation: deployOperation(tokens.deploy),\n amount: tokens.deploy.amount.toString(),\n owned: deployOwned\n }\n }),\n assets,\n destinations: outputs\n .filter(output => destination(output.vout))\n .map(output => ({\n outputIndex: output.vout,\n satoshis: output.satoshis,\n lockingScript: tx.outputs[output.vout].lockingScript.toHex(),\n ...(output.token === undefined\n ? {}\n : {\n assetId: output.token.deploy ? ISSUE : output.token.assetId,\n role: output.token.role,\n amount: output.token.amount.toString()\n })\n })),\n satoshis: {\n inputs: inputSatoshis,\n outputs: outputSatoshis,\n fee: inputSatoshis - outputSatoshis\n },\n signatures,\n lockTime: tx.lockTime\n }\n}\n\n/** Plan and action features this module version does not implement. */\nfunction assertPlanSupported(plan: ColorPlan, args: CreateActionArgs): void {\n // A plan's ownedOutputs, inputPositions and changePositions, and the facts the user approves,\n // all name requested output indices; storage shuffles them when randomizeOutputs is true.\n if (args.options?.randomizeOutputs !== false) {\n throw new Error('BRC-207: a p color plan requires options.randomizeOutputs false')\n }\n if (Object.keys(plan.profileData ?? {}).length > 0) {\n throw new Error('BRC-207: plan.profileData is not supported')\n }\n const handoff = (args.labels ?? []).some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX))\n // A signed deploy is filed in its asset basket through internalizeAction, which would end a\n // noSend transaction's lifecycle; the deploy is a broadcast action.\n if (plan.assets.includes(ISSUE) && (args.options?.noSend === true || handoff)) {\n throw new Error('BRC-207: a deploy cannot be a noSend action')\n }\n // As in BTMS, a token action completes with its overlay submission. The one deferred flow is\n // the BRC-177 handoff, whose receiver submits; a plain noSend action later sent with sendWith\n // would never reach the token overlay, as the manager gives modules no sendWith hook.\n if (args.options?.noSend === true && !handoff) {\n throw new Error('BRC-207: noSend token actions require a BRC-177 p nosend expiry label')\n }\n // Storage adds satoshi change while funding, after this module returns: it appends the requested\n // outputs, then any storage commission output, then change, and reports neither position.\n if (plan.changePositions.some(position => position.assetId === null)) {\n throw new Error(\n 'BRC-207: satoshi change positions are not supported: the wallet does not position satoshi change'\n )\n }\n}\n\n/** Explicit inputs in their final places, with the module's token inputs in the remaining slots. */\nfunction orderInputs(\n explicit: readonly CreateActionInput[],\n added: readonly CreateActionInput[],\n positions: ColorPlan['inputPositions']\n): CreateActionInput[] {\n const all = [...explicit, ...added]\n if (positions.length === 0) return all\n const slots = new Map<number, CreateActionInput>()\n for (const { outpoint, index } of positions) {\n const input = explicit.find(candidate => candidate.outpoint === outpoint)\n if (input === undefined)\n throw new Error(\n 'BRC-207: plan.inputPositions names an outpoint that is not an explicit input'\n )\n if (index >= all.length || slots.has(index))\n throw new Error('BRC-207: plan.inputPositions cannot be satisfied')\n slots.set(index, input)\n }\n const placed = new Set(slots.values())\n const rest = all.filter(input => !placed.has(input))\n return Array.from({ length: all.length }, (_, index) => slots.get(index) ?? rest.shift()!)\n}\n\n/**\n * Requested outputs at their own indices, then token change, each asset's change at its pinned\n * index if it has one. A change position cannot displace a requested output.\n */\nfunction placeChange(\n outputs: readonly CreateActionOutput[],\n changes: ReadonlyArray<{ assetId: string; output: CreateActionOutput }>,\n positions: ColorPlan['changePositions']\n): CreateActionOutput[] {\n const slots = new Map<number, CreateActionOutput>()\n for (const { assetId, index } of positions) {\n if (index < outputs.length)\n throw new Error('BRC-207: plan.changePositions conflict with the requested outputs')\n const change = changes.find(candidate => candidate.assetId === assetId)\n if (change === undefined || index >= outputs.length + changes.length)\n throw new Error('BRC-207: plan.changePositions cannot be satisfied')\n slots.set(index, change.output)\n }\n const placed = new Set(slots.values())\n const rest = changes.map(change => change.output).filter(output => !placed.has(output))\n return [\n ...outputs,\n ...Array.from(\n { length: changes.length },\n (_, offset) => slots.get(outputs.length + offset) ?? rest.shift()!\n )\n ]\n}\n\n/**\n * Reads a token in a transaction the wallet sends: BRC-162 first, then BRC-161 JSON, which the\n * module accounts for but never holds or creates.\n */\nexport function readSentToken(\n lockingScript: LockingScript,\n outpoint: ReturnType<typeof parseOutpoint>\n): TokenOutput | undefined {\n return tryReadTokenOutput(lockingScript, outpoint) ?? readJsonTokenOutput(lockingScript, outpoint)\n}\n\n/**\n * Token inputs of `tx` other than those in `except`, read from their source transactions. With\n * `json`, BRC-161 JSON inputs are read too.\n */\nexport function tokenSources(\n tx: Transaction,\n managed: ReadonlySet<string>,\n json = false\n): Array<SourceOutput & { assetId: string; token: TokenOutput }> {\n const read = json ? readSentToken : tryReadTokenOutput\n return tx.inputs.flatMap(input => {\n const outpoint = inputOutpoint(input)\n const source = input.sourceTransaction?.outputs[input.sourceOutputIndex]\n if (managed.has(outpoint) || source?.satoshis === undefined) return []\n const token = read(source.lockingScript, parseOutpoint(outpoint))\n if (token === undefined) return []\n return [\n {\n outpoint,\n lockingScript: source.lockingScript,\n satoshis: source.satoshis,\n assetId: token.assetId,\n token\n }\n ]\n })\n}\n\n/**\n * The existing assets among a transaction's token inputs (read from `inputs`, which carries their\n * sources) and outputs, and whether output 0 is a deploy: the topics it is submitted to.\n */\nexport function submissionAssets(\n tx: Transaction,\n inputs: Transaction = tx\n): { assetIds: string[]; deploy: boolean } {\n const txid = tx.id('hex')\n const outputs = tx.outputs.map((output, vout) =>\n readSentToken(output.lockingScript, { txid, vout })\n )\n const assetIds = new Set([\n ...tokenSources(inputs, new Set(), true).map(input => input.assetId),\n ...outputs.flatMap(token => (token === undefined || token.deploy ? [] : [token.assetId]))\n ])\n return { assetIds: [...assetIds], deploy: outputs[0]?.deploy === true }\n}\n\n/** Runs one input's unlocking script against its source output; throws when it does not unlock. */\nexport function assertUnlocks(tx: Transaction, inputIndex: number): void {\n const input = tx.inputs[inputIndex]\n const source = input.sourceTransaction?.outputs[input.sourceOutputIndex]\n if (source?.satoshis === undefined || input.unlockingScript === undefined)\n throw new Error(`BRC-207: transaction input ${inputIndex} lacks its source or unlocking script`)\n new Spend({\n sourceTXID: input.sourceTransaction!.id('hex'),\n sourceOutputIndex: input.sourceOutputIndex,\n sourceSatoshis: source.satoshis,\n lockingScript: source.lockingScript,\n transactionVersion: tx.version,\n otherInputs: tx.inputs.filter((_, index) => index !== inputIndex),\n outputs: tx.outputs,\n inputIndex,\n unlockingScript: input.unlockingScript,\n inputSequence: input.sequence ?? 0xffffffff,\n lockTime: tx.lockTime\n }).validate()\n}\n\nfunction addToken(totals: Map<string, Holding>, token: TokenOutput): void {\n const entry = holding(totals, token.assetId, emptyHolding)\n if (token.role === 'value') entry.value += token.amount\n else entry.authority += 1\n if (token.encoding === 'brc161' && token.jsonOperation !== 'mint')\n entry.jsonValue = (entry.jsonValue ?? 0n) + token.amount\n}\n\n/** A foreign input's source output from the caller's inputBEEF, if it is there. */\nfunction foreignSource(beef: Beef | undefined, outpoint: string): SourceOutput | undefined {\n const { txid, vout } = parseOutpoint(outpoint)\n const output = beef?.findTxid(txid)?.tx?.outputs[vout]\n if (output?.satoshis === undefined) return undefined\n return { outpoint, lockingScript: output.lockingScript, satoshis: output.satoshis }\n}\n\n/** A transaction's token inputs and outputs per existing asset, and its deploy output. */\nexport interface TransactionTokens {\n consumed: Array<SourceOutput & { assetId: string; token: TokenOutput }>\n inputs: Map<string, Holding>\n outputs: Map<string, Holding>\n deploy?: TokenOutput\n}\n\n/**\n * Reads every input's source and every output; an input without its source fails. With `json`,\n * for a transaction the wallet sends, BRC-161 JSON inputs and outputs are read too.\n */\nexport function transactionTokens(tx: Transaction, json = false): TransactionTokens {\n tx.inputs.forEach((input, index) => {\n if (input.sourceTransaction === undefined)\n throw new Error(`BRC-207: input ${index} has no source transaction to authenticate`)\n })\n const txid = tx.id('hex')\n const consumed = tokenSources(tx, new Set(), json)\n const inputs = new Map<string, Holding>()\n for (const source of consumed) addToken(inputs, source.token)\n const outputs = new Map<string, Holding>()\n let deploy: TokenOutput | undefined\n tx.outputs.forEach((output, vout) => {\n const token = json\n ? readAnyTokenOutput(output.lockingScript, { txid, vout })\n : readTokenOutput(output.lockingScript, { txid, vout })\n if (token?.deploy === true && token.encoding === 'brc161')\n throw new Error('BRC-207: a new issuance must use BRC-162')\n if (token?.deploy === true) deploy = token\n else if (token !== undefined) addToken(outputs, token)\n })\n return { consumed, inputs, outputs, deploy }\n}\n\nexport function deployOperation(token: TokenOutput): ColorOperationName {\n return token.amount > 0n ? 'deploy-fixed' : 'deploy-authority'\n}\n\n/** Fails unless the plan's operations and assets are exactly what the transaction performs. */\nexport function assertTransactionOperations(plan: ColorPlan, tokens: TransactionTokens): void {\n const assetIds = new Set([...tokens.inputs.keys(), ...tokens.outputs.keys()])\n assertPlanAssets(plan, new Set([...assetIds, ...(tokens.deploy === undefined ? [] : [ISSUE])]))\n if (tokens.deploy !== undefined) assertOperations(plan, ISSUE, [deployOperation(tokens.deploy)])\n for (const assetId of assetIds)\n assertOperations(\n plan,\n assetId,\n requiredOperations(\n tokens.inputs.get(assetId) ?? emptyHolding(),\n tokens.outputs.get(assetId) ?? emptyHolding()\n )\n )\n}\n\n/** The sighash type for each managed input; an override must name one the module signs. */\nexport function sighashScopes(plan: ColorPlan, managed: ReadonlySet<string>): Map<string, number> {\n const scopes = new Map<string, number>()\n for (const { outpoint, sighashType } of plan.sighashTypes) {\n if (!managed.has(outpoint))\n throw new Error('BRC-207: plan.sighashTypes names an input this wallet does not sign')\n scopes.set(outpoint, sighashType)\n }\n return scopes\n}\n\n/** The plan names exactly the assets among the action's token inputs and outputs. */\nexport function assertPlanAssets(plan: ColorPlan, involved: ReadonlySet<string>): void {\n if (plan.assets.length !== involved.size || plan.assets.some(assetId => !involved.has(assetId)))\n throw new Error('BRC-207: plan.assets must name exactly the assets the action moves')\n}\n\n/** Largest amount first. */\n/**\n * Chooses unrejected candidates, in their order, until they cover `target`: units for value, a count\n * for authority. Undefined when they cannot.\n */\nfunction chooseCandidates(\n candidates: readonly Candidate[],\n rejected: ReadonlySet<string>,\n role: TokenRole,\n target: bigint\n): Candidate[] | undefined {\n const chosen: Candidate[] = []\n let total = 0n\n for (const candidate of candidates) {\n if (total >= target) break\n if (rejected.has(candidate.outpoint)) continue\n chosen.push(candidate)\n total += role === 'value' ? candidate.amount : 1n\n }\n return total < target ? undefined : chosen\n}\n\nfunction byAmountDescending(a: { amount: bigint }, b: { amount: bigint }): number {\n if (a.amount === b.amount) return 0\n return a.amount > b.amount ? -1 : 1\n}\n\ninterface InventoryRecord {\n output: WalletOutput\n assetId: string\n source: SourceOutput\n}\n\ninterface InventoryView {\n record: InventoryRecord\n state: InventoryState\n tags: string[]\n}\n\n/** The token outputs of a namespace listing. */\nfunction inventoryRecords(outputs: WalletOutput[], beef: Beef | undefined): InventoryRecord[] {\n const records: InventoryRecord[] = []\n for (const output of outputs) {\n const outpoint = parseOutpoint(output.outpoint)\n const lockingScript =\n beef === undefined\n ? LockingScript.fromHex(output.lockingScript ?? '')\n : beef.findTxid(outpoint.txid)?.tx?.outputs[outpoint.vout]?.lockingScript\n if (lockingScript === undefined) continue\n let token: TokenOutput | undefined\n try {\n token = tryReadTokenOutput(lockingScript, outpoint)\n } catch {\n continue // an unsupported asset's outputs are left out of the inventory\n }\n if (token === undefined) continue\n records.push({\n output,\n assetId: token.assetId,\n source: { outpoint: output.outpoint, lockingScript, satoshis: output.satoshis }\n })\n }\n return records\n}\n\n/** Reserved by a pending action, else available. Wallet state only; the overlay is not consulted. */\nfunction inventoryState(record: InventoryRecord): InventoryState {\n return record.output.spendable ? 'available' : 'reserved'\n}\n\n/**\n * A BRC-162 token output, or undefined for a script that is not one. A token-shaped script that\n * does not decode is an ordinary satoshi output; a valid output of an asset that requires\n * processing profiles is a token this wallet cannot evaluate, and fails (BRC-207 L92-95).\n */\nexport function tryReadTokenOutput(\n lockingScript: LockingScript,\n outpoint: ReturnType<typeof parseOutpoint>\n): TokenOutput | undefined {\n try {\n return readTokenOutput(lockingScript, outpoint)\n } catch (error) {\n if (error instanceof UnsupportedProfileError) throw error\n return undefined\n }\n}\n\n/** A record with its stored tags, less suffix tags, and the computed state tag in place of any stored one. */\nfunction inventoryView(record: InventoryRecord): InventoryView {\n const state = inventoryState(record)\n const tags = [\n // The suffix tag is the module's own index into the basket; apps see the stored tags without it.\n ...(record.output.tags ?? []).filter(\n tag => !tag.startsWith(STATE_TAG_PREFIX) && !isDerivationSuffixTag(tag)\n ),\n `${STATE_TAG_PREFIX}${state}`\n ]\n return { record, state, tags }\n}\n\n/** A BEEF holding only the transactions of the returned page. */\nfunction pageBeef(beef: Beef, page: readonly InventoryView[]): number[] {\n const result = new Beef()\n for (const txid of new Set(page.map(view => parseOutpoint(view.record.output.outpoint).txid))) {\n const tx = beef.findAtomicTransaction(txid)\n if (tx !== undefined) result.mergeTransaction(tx)\n }\n return result.toBinary()\n}\n\nfunction matchesTags(\n tags: readonly string[],\n filter: readonly string[],\n mode: ListOutputsArgs['tagQueryMode']\n): boolean {\n if (filter.length === 0) return true\n return mode === 'all'\n ? filter.every(tag => tags.includes(tag))\n : filter.some(tag => tags.includes(tag))\n}\n\n/**\n * BRC-207 `color` wallet module for BRC-162 fungible tokens.\n *\n * Register it as `permissionModules: { color }` on a WalletPermissionsManager. It\n * verifies and accepts receipts, funds token sends from its per-asset baskets and\n * signs their inputs during `signAction`, signs app-built transactions through\n * `createSignature`, and answers the `p color assets` and `p color balance` views.\n */\nexport class ColorPermissionModule implements PermissionsModule {\n protected readonly wallet: WalletInterface\n protected readonly provider: ColorOverlayProvider\n protected readonly requestTokenAccess: ColorTokenAccessHandler\n /** BRC-205 attribute for BRC-207's Discovery section: this module implements revision 5. */\n readonly capabilities: Readonly<Record<string, string>> = { 'brc207-color': '5' }\n /** Outputs a send in progress has selected, so a concurrent send does not select them too. */\n protected readonly selected = new Set<string>()\n /** The managed inputs of funded actions whose createAction has not come back, by outpoint. */\n protected readonly staged = new Map<string, ManagedInput>()\n /** The managed inputs the module signs for, by the action reference they were bound to. */\n protected readonly bound = new Map<string, ManagedInput[]>()\n protected readonly supportedAssets = new Map<string, Promise<void>>()\n protected identityKey?: Promise<string>\n\n constructor(options: ColorPermissionModuleOptions) {\n if (options?.wallet == null) throw new TypeError('BRC-207: wallet is required')\n if (options.provider == null) throw new TypeError('BRC-207: provider is required')\n if (typeof options.requestTokenAccess !== 'function') {\n throw new TypeError('BRC-207: requestTokenAccess is required')\n }\n this.wallet = options.wallet\n this.provider = options.provider\n this.requestTokenAccess = options.requestTokenAccess\n }\n\n /** Clears in-memory selections, staged and bound input records and asset checks. */\n dispose(): void {\n this.selected.clear()\n this.staged.clear()\n this.bound.clear()\n this.supportedAssets.clear()\n this.identityKey = undefined\n }\n\n /** Protocol- and basket-routed calls: key and signature operations and the read views. */\n async handleRequest(\n req: PermissionsModuleRequest,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n switch (req.method) {\n case 'getPublicKey':\n case 'verifySignature':\n this.parseKeyArgs(req.args as { protocolID?: unknown; keyID?: unknown })\n return await next(req.args)\n case 'createSignature':\n return await this.createSignature(req.args as CreateSignatureArgs, req.originator, next)\n case 'listOutputs':\n return await this.listOutputs(req.args as ListOutputsArgs, req.originator, next)\n case 'relinquishOutput': {\n const { basket, output } = req.args as { basket: string; output: string }\n const target = parseAssetBasket(basket)\n if (target === undefined) {\n throw new Error('BRC-207: only per-asset baskets hold outputs that can be relinquished')\n }\n await this.approve(req.originator, {\n type: 'color_relinquish',\n assetId: target.assetId,\n role: target.role,\n outpoint: output\n })\n return await next(req.args)\n }\n default:\n throw new Error(`BRC-207: ${req.method} is not available in the p color namespace`)\n }\n }\n\n /** Label- and basket-routed actions. */\n async onRequest(req: PermissionsModuleRequest): Promise<{ args: object }> {\n switch (req.method) {\n case 'createAction':\n return { args: await this.createAction(req.args as CreateActionArgs, req.originator) }\n case 'signAction':\n return {\n args: await this.signAction(req.args as SignActionArgs, req.action, req.originator)\n }\n case 'internalizeAction': {\n return {\n args: await this.internalizeAction(req.args as InternalizeActionArgs, req.originator)\n }\n }\n case 'listActions': {\n const args = req.args as ListActionsArgs\n await this.authorizeRead(req.originator, {\n labels: (args.labels ?? []).filter(label => label.startsWith(COLOR_BASKET_NAMESPACE)),\n seekPermission: args.seekPermission !== false\n })\n return { args }\n }\n default:\n throw new Error(`BRC-207: ${req.method} is not available in the p color namespace`)\n }\n }\n\n async onResponse(\n res: unknown,\n context: { method: string; originator: string; action?: PermissionsModuleAction }\n ): Promise<unknown> {\n if (context.method === 'createAction') this.bindAction(res as CreateActionResult)\n if (context.method === 'signAction' && context.action !== undefined) {\n await this.fileDeploy(res as SignActionResult, context.action, context.originator)\n // A noSend action is always a BRC-177 handoff (createAction refuses any other): its\n // receiver submits it.\n if (!context.action.noSend)\n await this.submitSigned(res as SignActionResult, context.action.transaction)\n }\n return res\n }\n\n /**\n * Files a signed deploy this wallet keeps in its asset's value or authority basket, now that\n * the asset ID is final. The deploy keeps its `ISSUE` key; its asset overlay must admit it\n * before it can be spent.\n */\n protected async fileDeploy(\n result: SignActionResult,\n action: PermissionsModuleAction,\n originator: string\n ): Promise<void> {\n if (result?.tx === undefined) return\n const tx = Transaction.fromAtomicBEEF(result.tx)\n const txid = tx.id('hex')\n const deploy = tryReadTokenOutput(tx.outputs[0]?.lockingScript ?? new LockingScript(), {\n txid,\n vout: 0\n })\n const remittance = ColorPlan.fromLabels(action.createArgs?.labels)?.ownedOutputs.find(\n owned => owned.outputIndex === 0 && owned.assetId === ISSUE\n )\n if (deploy?.deploy !== true || remittance === undefined) return\n // The underlying wallet merges the insertion into its own signed transaction: the basket and\n // the custody (encrypted at createAction) are assigned and the transaction's status is kept.\n const customInstructions = action.createArgs?.outputs?.[0]?.customInstructions\n await this.wallet.internalizeAction(\n {\n tx: result.tx,\n description: 'File the deployed asset',\n outputs: [\n {\n outputIndex: 0,\n protocol: 'basket insertion',\n insertionRemittance: {\n basket: assetBasket(deploy.assetId, deploy.role),\n ...(customInstructions === undefined ? {} : { customInstructions }),\n tags: [suffixTagOf(remittance)]\n }\n }\n ]\n },\n originator\n )\n }\n\n /* ----------------------------------------------------------------------\n * Receive\n * ---------------------------------------------------------------------- */\n\n /**\n * Verifies every `p color` receipt and tags it with its derivation suffix; the caller must\n * already have submitted the transaction.\n */\n protected async internalizeAction(\n args: InternalizeActionArgs,\n originator: string\n ): Promise<InternalizeActionArgs> {\n if ((args.labels ?? []).some(label => label.startsWith(`${COLOR_BASKET_NAMESPACE} `))) {\n throw new Error('BRC-207: p color labels have no meaning in internalizeAction')\n }\n const tx = parsed('the received transaction', () => Transaction.fromAtomicBEEF(args.tx))\n const receipts = args.outputs.flatMap(output => {\n const remittance = output.insertionRemittance\n return output.protocol === 'basket insertion' &&\n remittance?.basket.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true\n ? [{ outputIndex: output.outputIndex, remittance }]\n : []\n })\n if (receipts.length === 0) return args\n await this.assertCompletedTransaction(tx)\n const tags = new Map<number, string[]>()\n await eachInOrder(receipts, async ({ outputIndex, remittance }) => {\n const custody = await this.verifyReceipt(tx, outputIndex, remittance, originator)\n tags.set(outputIndex, withSuffixTag(remittance.tags, custody))\n })\n return {\n ...args,\n outputs: args.outputs.map(output =>\n output.insertionRemittance === undefined || !tags.has(output.outputIndex)\n ? output\n : {\n ...output,\n insertionRemittance: {\n ...output.insertionRemittance,\n tags: tags.get(output.outputIndex)\n }\n }\n )\n }\n }\n\n /**\n * Checks a received transaction: every input unlocks its source and every asset it involves is\n * supported. Token amounts are not re-evaluated: the received output must be admitted and\n * unspent, and its overlay admits it only after applying the amount and authority rules.\n */\n protected async assertCompletedTransaction(tx: Transaction): Promise<void> {\n for (let index = 0; index < tx.inputs.length; index++) assertUnlocks(tx, index)\n const { inputs, outputs } = transactionTokens(tx)\n await this.assertSupportedAssets([...inputs.keys(), ...outputs.keys()])\n }\n\n /** Checks each distinct asset in order, so the first unsupported one is the one reported. */\n protected async assertSupportedAssets(assetIds: Iterable<string>): Promise<void> {\n await eachInOrder(new Set(assetIds), async assetId => {\n await this.assertSupportedAsset(assetId)\n })\n }\n\n /** One receipt: its custody, its output's asset, owner and basket, and overlay admission. */\n protected async verifyReceipt(\n tx: Transaction,\n outputIndex: number,\n remittance: BasketInsertion,\n originator: string\n ): Promise<Custody> {\n const target = parseAssetBasket(remittance.basket)\n if (target === undefined)\n throw new Error('BRC-207: a receipt must name a per-asset value or authority basket')\n const custody = parseCustody(\n remittance.customInstructions ?? '',\n MAX_RECEIPT_INSTRUCTION_BYTES,\n 'receipt customInstructions'\n )\n const source = tx.outputs[outputIndex]\n if (source?.satoshis === undefined)\n throw new Error('BRC-207: the receipt names a missing output')\n const txid = tx.id('hex')\n const token = readTokenOutput(source.lockingScript, { txid, vout: outputIndex })\n if (token === undefined)\n throw new Error('BRC-207: the received output is not a BRC-162 token output')\n if (!selectsAsset(custody.assetId, token)) {\n throw new Error('BRC-207: the receipt instructions name a different asset than the output')\n }\n if (target.assetId !== token.assetId || target.role !== token.role) {\n throw new Error('BRC-207: the receipt basket does not match the received output')\n }\n await this.assertOwned(token, custody, custody.senderIdentityKey, originator)\n await this.assertSupportedAsset(token.assetId)\n const outpoint = outpointString(txid, outputIndex)\n const admitted = await this.spendable(token.assetId, [\n { outpoint, lockingScript: source.lockingScript, satoshis: source.satoshis }\n ])\n if (!admitted.has(outpoint)) {\n throw new Error(\n 'BRC-207: the received output is not admitted and unspent in its asset overlay'\n )\n }\n return custody\n }\n\n /* ----------------------------------------------------------------------\n * Send\n * ---------------------------------------------------------------------- */\n\n /** Checks a planned token action and adds its selected token inputs and per-asset change. */\n protected async createAction(\n args: CreateActionArgs,\n originator: string\n ): Promise<CreateActionArgs> {\n const labels = args.labels ?? []\n const plan = ColorPlan.fromLabels(labels)\n if (plan === undefined)\n throw new Error('BRC-207: a p color createAction requires a p color plan')\n // Plan labels are the only p color labels; BRC-176 proof transport is not part of BRC-207.\n if (\n labels.some(\n label =>\n label.startsWith(`${COLOR_BASKET_NAMESPACE} `) &&\n !label.startsWith(COLOR_PLAN_LABEL_PREFIX)\n )\n )\n throw new Error('BRC-207: unknown p color label')\n const handoff = labels.some(label => label.startsWith(NOSEND_EXPIRY_LABEL_PREFIX))\n assertPlanSupported(plan, args)\n const { planned, outputs } = await this.planOutputs(plan, args, originator)\n // The hold keeps concurrent sends in this module from choosing the same outputs while it plans.\n // Once this handler returns, the inputs are staged until the action's createAction comes back\n // (onResponse) and moves them to its reference; storage has then reserved them.\n const reserved = new Set<string>()\n try {\n const explicit = await this.explicitInputs(args, originator)\n this.reserve(reserved, explicit.managed)\n const { inputs, changes } = await this.fund(\n reserved,\n plan,\n planned,\n explicit,\n handoff,\n originator\n )\n sighashScopes(plan, new Set([...explicit.managed, ...inputs].map(input => input.outpoint)))\n const inputBEEF = await this.inputBeef(args.inputBEEF, inputs, originator)\n const funded = {\n ...args,\n inputs: orderInputs(explicit.inputs, tokenInputs(inputs), plan.inputPositions),\n outputs: placeChange(outputs, changes, plan.changePositions),\n ...(inputBEEF === undefined ? {} : { inputBEEF })\n }\n this.stage([...explicit.managed, ...inputs])\n return funded\n } finally {\n for (const outpoint of reserved) this.selected.delete(outpoint)\n }\n }\n\n /** Stages a funded action's managed inputs until its createAction comes back. */\n protected stage(inputs: readonly ManagedInput[]): void {\n for (const input of inputs) this.staged.set(input.outpoint, input)\n }\n\n /**\n * Moves the staged inputs the returned transaction spends to its action reference. A result\n * without a signable transaction binds nothing; its named inputs are only unstaged.\n */\n protected bindAction(result: CreateActionResult): void {\n const signable = result.signableTransaction\n const atomic = signable?.tx ?? result.tx\n if (atomic === undefined) return\n let tx: Transaction\n try {\n tx = Transaction.fromAtomicBEEF(atomic)\n } catch {\n return // the manager refuses a malformed transaction itself\n }\n for (const input of tx.inputs) {\n const outpoint = inputOutpoint(input)\n const staged = this.staged.get(outpoint)\n if (staged === undefined) continue\n this.staged.delete(outpoint)\n if (signable === undefined) continue\n const records = this.bound.get(signable.reference) ?? []\n records.push(staged)\n this.bound.set(signable.reference, records)\n }\n }\n\n protected reserve(reserved: Set<string>, inputs: ReadonlyArray<{ outpoint: string }>): void {\n for (const input of inputs) {\n this.selected.add(input.outpoint)\n reserved.add(input.outpoint)\n }\n }\n\n protected release(reserved: Set<string>, inputs: ReadonlyArray<{ outpoint: string }>): void {\n for (const input of inputs) {\n this.selected.delete(input.outpoint)\n reserved.delete(input.outpoint)\n }\n }\n\n /**\n * Classifies the caller's inputs: this wallet's `p color` outputs are managed and signed by the\n * module; foreign token inputs count only once their asset's overlay admits them; other inputs\n * pass through unchanged.\n */\n protected async explicitInputs(\n args: CreateActionArgs,\n originator: string\n ): Promise<ExplicitInputs> {\n const inputs = args.inputs ?? []\n const explicit: ExplicitInputs = { inputs: [...inputs], managed: [], holdings: new Map() }\n if (inputs.length === 0) return explicit\n const outpoints = new Set(inputs.map(input => input.outpoint))\n if (outpoints.size !== inputs.length) throw new Error('BRC-207: duplicate explicit input')\n const listed = await this.wallet.listOutputs(\n {\n basket: toolbox.specOpBasketPrefixOutputs,\n tags: [COLOR_BASKET_NAMESPACE],\n include: 'locking scripts',\n includeCustomInstructions: true,\n includeTags: true\n },\n originator\n )\n const own = new Map(\n listed.outputs\n .filter(output => outpoints.has(output.outpoint))\n .map(output => [output.outpoint, output])\n )\n const beef =\n args.inputBEEF === undefined\n ? undefined\n : parsed('inputBEEF', () => Beef.fromBinary(args.inputBEEF as number[]))\n await eachInOrder(inputs, async input => {\n const output = own.get(input.outpoint)\n if (output === undefined) await this.foreignInput(explicit, beef, input.outpoint)\n else await this.ownInput(explicit, output, originator)\n })\n return explicit\n }\n\n /** Counts one of this wallet's `p color` outputs once it is managed, admitted and unspent. */\n protected async ownInput(\n explicit: ExplicitInputs,\n output: WalletOutput,\n originator: string\n ): Promise<void> {\n if (!output.spendable || this.staged.has(output.outpoint) || this.selected.has(output.outpoint))\n throw new Error('BRC-207: an explicit p color input is reserved by another action')\n const managed = await this.managedInput(output, originator)\n if (managed === undefined)\n throw new Error('BRC-207: an explicit p color input is not a managed token output')\n if (!carriesSuffixTag(output.tags, managed.custody))\n throw new Error(\n `BRC-207: token output ${managed.outpoint} was filed without its suffix tag and is not spendable through the module`\n )\n await this.assertSupportedAsset(managed.assetId)\n if (\n !(await this.spendable(managed.assetId, [managed])).has(managed.outpoint) &&\n !(await this.resubmitHeld(managed.assetId, managed.role, [managed], originator)).has(\n managed.outpoint\n )\n )\n throw new Error('BRC-207: an explicit p color input is not admitted and unspent')\n explicit.managed.push(managed)\n const totals = holding(explicit.holdings, managed.assetId, emptyExplicitHolding)\n if (managed.role === 'value') totals.value += managed.amount\n else totals.authority += 1\n }\n\n /** Counts a foreign token input once its overlay admits it; other foreign inputs add nothing. */\n protected async foreignInput(\n explicit: ExplicitInputs,\n beef: Beef | undefined,\n outpoint: string\n ): Promise<void> {\n // A source missing from inputBEEF is resolved from the wallet and checked at signAction.\n const source = foreignSource(beef, outpoint)\n const token =\n source === undefined\n ? undefined\n : readAnyTokenOutput(source.lockingScript, parseOutpoint(outpoint))\n if (token === undefined) return\n await this.assertSupportedAsset(token.assetId)\n if (!(await this.spendable(token.assetId, [source!])).has(outpoint))\n throw new Error('BRC-207: a foreign token input is not admitted and unspent in its overlay')\n const totals = holding(explicit.holdings, token.assetId, emptyExplicitHolding)\n if (token.role === 'value') {\n totals.value += token.amount\n totals.foreignValue += token.amount\n } else {\n totals.authority += 1\n totals.foreignAuthority += 1\n }\n }\n\n /** Classifies the requested outputs, totalling each asset's value and authority outputs. */\n protected async planOutputs(\n plan: ColorPlan,\n args: CreateActionArgs,\n originator: string\n ): Promise<{ planned: PlannedOutputs; outputs: CreateActionOutput[] }> {\n const requested = args.outputs ?? []\n for (const remittance of plan.ownedOutputs) {\n if (remittance.outputIndex >= requested.length) {\n throw new Error('BRC-207: plan.ownedOutputs names a missing output')\n }\n }\n const owned = new Map(plan.ownedOutputs.map(remittance => [remittance.outputIndex, remittance]))\n const planned: PlannedOutputs = { holdings: new Map(), destinations: [] }\n const outputs = await mapInOrder(\n requested,\n async (output, index) =>\n await this.planOutput(plan, args, index, output, owned.get(index), planned, originator)\n )\n return { planned, outputs }\n }\n\n /** One requested output: passed through, a token destination, or a token output this wallet keeps. */\n protected async planOutput(\n plan: ColorPlan,\n args: CreateActionArgs,\n index: number,\n output: CreateActionOutput,\n remittance: ColorRemittance | undefined,\n planned: PlannedOutputs,\n originator: string\n ): Promise<CreateActionOutput> {\n const lockingScript = parsed(`output ${index} locking script`, () =>\n LockingScript.fromHex(output.lockingScript)\n )\n const placeholder = { txid: '00'.repeat(32), vout: index }\n const token = readTokenOutput(lockingScript, placeholder)\n if (token === undefined) {\n if (remittance !== undefined)\n throw new Error('BRC-207: plan.ownedOutputs names a non-token output')\n if (output.basket?.startsWith(`${COLOR_BASKET_NAMESPACE} `) === true) {\n throw new Error('BRC-207: a p color basket can only receive BRC-162 token outputs')\n }\n const json = readJsonTokenOutput(lockingScript, placeholder)\n if (json !== undefined) this.jsonDestination(plan, index, output, json, planned)\n return output\n }\n if (token.deploy)\n return await this.deployOutput(args, output, token, remittance, planned, originator)\n if (!plan.assets.includes(token.assetId))\n throw new Error('BRC-207: an output asset is missing from plan.assets')\n const totals = holding(planned.holdings, token.assetId, emptyHolding)\n if (token.role === 'value') totals.value += token.amount\n else totals.authority += 1\n if (remittance !== undefined)\n return await this.ownedOutput(token, output, remittance, originator)\n if (output.basket !== undefined) {\n throw new Error('BRC-207: only outputs in plan.ownedOutputs may enter a p color basket')\n }\n planned.destinations.push({\n outputIndex: index,\n assetId: token.assetId,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n return output\n }\n\n /** A BRC-161 JSON output to another party: counted for its asset, never held or created here. */\n protected jsonDestination(\n plan: ColorPlan,\n index: number,\n output: CreateActionOutput,\n token: TokenOutput,\n planned: PlannedOutputs\n ): void {\n if (token.deploy) throw new Error('BRC-207: a new issuance must use BRC-162')\n if (!plan.assets.includes(token.assetId))\n throw new Error('BRC-207: an output asset is missing from plan.assets')\n const totals = holding(planned.holdings, token.assetId, emptyHolding)\n if (token.role === 'authority') totals.authority += 1\n else {\n totals.value += token.amount\n if (token.jsonOperation !== 'mint') totals.jsonValue = (totals.jsonValue ?? 0n) + token.amount\n }\n planned.destinations.push({\n outputIndex: index,\n assetId: token.assetId,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n }\n\n /**\n * The action's deploy, which BRC-162 requires at output 0. An owned deploy keeps its `ISSUE`\n * key; its asset basket is assigned once the transaction ID is final.\n */\n protected async deployOutput(\n args: CreateActionArgs,\n output: CreateActionOutput,\n token: TokenOutput,\n remittance: ColorRemittance | undefined,\n planned: PlannedOutputs,\n originator: string\n ): Promise<CreateActionOutput> {\n if (output.basket !== undefined)\n throw new Error(\n \"BRC-207: a deploy output's basket is assigned once its transaction is signed\"\n )\n planned.deploy = { operation: deployOperation(token) }\n if (remittance === undefined) {\n planned.destinations.push({\n outputIndex: 0,\n assetId: ISSUE,\n role: token.role,\n amount: token.amount.toString(),\n lockingScript: output.lockingScript\n })\n return output\n }\n if (remittance.assetId !== ISSUE)\n throw new Error('BRC-207: a deploy output remittance must use ISSUE')\n await this.assertOwned(token, remittance, remittance.senderIdentityKey, originator)\n // Without a p color basket the manager does not encrypt its custody, so it is encrypted here.\n return {\n ...output,\n customInstructions: await encryptMetadata(\n this.wallet,\n custodyInstructions(custodyOf(remittance)),\n originator\n )\n }\n }\n\n /** A token output of the action that this wallet keeps, placed in its asset's basket. */\n protected async ownedOutput(\n token: TokenOutput,\n output: CreateActionOutput,\n remittance: ColorRemittance,\n originator: string\n ): Promise<CreateActionOutput> {\n if (remittance.assetId !== token.assetId)\n throw new Error('BRC-207: an owned output remittance names another asset')\n await this.assertOwned(token, remittance, remittance.senderIdentityKey, originator)\n const basket = assetBasket(token.assetId, token.role)\n if (output.basket !== undefined && output.basket !== basket) {\n throw new Error('BRC-207: an owned output names the wrong p color basket')\n }\n return {\n ...output,\n basket,\n customInstructions: custodyInstructions(custodyOf(remittance)),\n tags: withSuffixTag(output.tags, remittance)\n }\n }\n\n /**\n * Funds each asset the plan involves, checks its operations, splits for a handoff, and returns\n * the selected inputs and token change. The user approves the funded action at signAction.\n */\n protected async fund(\n reserved: Set<string>,\n plan: ColorPlan,\n planned: PlannedOutputs,\n explicit: ExplicitInputs,\n handoff: boolean,\n originator: string\n ): Promise<{\n inputs: ManagedInput[]\n changes: Array<{ assetId: string; output: CreateActionOutput }>\n }> {\n const assetIds = new Set([\n ...planned.holdings.keys(),\n ...explicit.holdings.keys(),\n ...plan.operations.flatMap(operation =>\n operation.assetId === ISSUE ? [] : [operation.assetId]\n )\n ])\n assertPlanAssets(plan, new Set([...assetIds, ...(planned.deploy === undefined ? [] : [ISSUE])]))\n if (planned.deploy !== undefined) assertOperations(plan, ISSUE, [planned.deploy.operation])\n const funding = await mapInOrder(assetIds, async assetId => {\n await this.assertSupportedAsset(assetId)\n return await this.fundAsset(\n reserved,\n plan,\n assetId,\n planned.holdings.get(assetId) ?? emptyHolding(),\n explicit.holdings.get(assetId) ?? emptyExplicitHolding(),\n originator\n )\n })\n const settled = await mapInOrder(\n funding,\n async asset =>\n await this.settleFunding(\n reserved,\n asset,\n explicit.holdings.get(asset.assetId)?.value ?? 0n,\n handoff,\n originator\n )\n )\n return {\n inputs: settled.flatMap(asset => asset.inputs),\n changes: settled.flatMap(asset => asset.change)\n }\n }\n\n /**\n * One funded asset's inputs and change: a handoff with change splits off an exact output instead,\n * so the recipient receives no change; otherwise any change becomes a new managed output.\n */\n protected async settleFunding(\n reserved: Set<string>,\n asset: AssetFunding,\n explicitValue: bigint,\n handoff: boolean,\n originator: string\n ): Promise<{\n inputs: ManagedInput[]\n change: Array<{ assetId: string; output: CreateActionOutput }>\n }> {\n if (asset.change <= 0n) return { inputs: asset.selected, change: [] }\n if (handoff) {\n const value = asset.selected.filter(input => input.role === 'value')\n const needed = asset.outputs.value - asset.change - explicitValue\n return {\n inputs: await this.splitExact(reserved, asset.assetId, value, needed, originator),\n change: []\n }\n }\n const { output } = await this.newManagedOutput(asset.assetId, asset.change, originator)\n return { inputs: asset.selected, change: [{ assetId: asset.assetId, output }] }\n }\n\n /**\n * Selects one asset's value inputs for a transfer and authority inputs for a declared authority\n * operation, then checks the resulting operations against the plan. Value is selected, with\n * change, only when the asset's operations are a transfer without a mint or burn.\n */\n protected async fundAsset(\n reserved: Set<string>,\n plan: ColorPlan,\n assetId: string,\n requested: Holding,\n explicit: ExplicitHolding,\n originator: string\n ): Promise<AssetFunding> {\n const declared = declaredOperations(plan, assetId)\n const selected: ManagedInput[] = []\n const automatic = declared.has('transfer') && !declared.has('mint') && !declared.has('burn')\n if (automatic && requested.value > explicit.value) {\n selected.push(\n ...(await this.selectInputs(\n reserved,\n assetId,\n 'value',\n requested.value - explicit.value,\n originator\n ))\n )\n }\n const authorityOperation = AUTHORITY_OPERATIONS.find(operation => declared.has(operation))\n const authorityCount =\n authorityOperation === undefined || explicit.authority > 0\n ? 0\n : authorityInputsFor(authorityOperation, requested.authority)\n if (authorityCount > 0) {\n selected.push(\n ...(await this.selectInputs(\n reserved,\n assetId,\n 'authority',\n BigInt(authorityCount),\n originator\n ))\n )\n }\n const selectedValue = sumAmounts(selected)\n const value = explicit.value + selectedValue\n // Change returns what selection adds beyond the need; excess explicit value is a burn.\n const change = selectedValue > 0n ? value - requested.value : 0n\n const inputs = { value, authority: explicit.authority + authorityCount }\n const outputs = {\n value: requested.value + change,\n authority: requested.authority,\n jsonValue: requested.jsonValue\n }\n assertOperations(plan, assetId, requiredOperations(inputs, outputs))\n return { assetId, selected, change, outputs }\n }\n\n /** Replaces a handoff's value inputs with one split output of exactly `amount`, which it reserves. */\n protected async splitExact(\n reserved: Set<string>,\n assetId: string,\n selected: ManagedInput[],\n amount: bigint,\n originator: string\n ): Promise<ManagedInput[]> {\n const exact = await this.split(assetId, selected, amount, originator)\n this.release(reserved, selected)\n this.reserve(reserved, [exact])\n return [exact]\n }\n\n /**\n * Selects admitted, unspent outputs of one asset's value or authority basket: value outputs\n * covering `target` units, largest first, or `target` authority outputs.\n */\n protected async selectInputs(\n reserved: Set<string>,\n assetId: string,\n role: TokenRole,\n target: bigint,\n originator: string\n ): Promise<ManagedInput[]> {\n const candidates = (await this.candidates(assetId, role, originator)).sort(byAmountDescending)\n const rejected = new Set<string>()\n for (;;) {\n const chosen = chooseCandidates(candidates, rejected, role, target)\n if (chosen === undefined)\n throw new Error(\n `BRC-207: insufficient spendable ${role === 'value' ? 'balance' : 'authority'} of ${assetId}`\n )\n const selected = await this.checkChosen(reserved, assetId, role, chosen, rejected, originator)\n if (selected !== undefined) return selected\n }\n }\n\n /**\n * Holds the chosen outputs and checks them: each must have readable custody and be admitted and\n * unspent, after resubmission if needed. Returns them as inputs, still held, when all pass;\n * otherwise rejects and releases the ones that failed and returns undefined.\n */\n protected async checkChosen(\n reserved: Set<string>,\n assetId: string,\n role: TokenRole,\n chosen: Candidate[],\n rejected: Set<string>,\n originator: string\n ): Promise<ManagedInput[] | undefined> {\n // Chosen outputs are held while they are checked, so a concurrent action cannot choose them.\n this.reserve(reserved, chosen)\n // Custody is read only for chosen outputs; an unreadable record is skipped, not fatal.\n const inputs = await Promise.all(\n chosen.map(async candidate => await this.readableInput(candidate, originator))\n )\n const unreadable = chosen.filter((_, index) => inputs[index] === undefined)\n if (unreadable.length > 0) {\n for (const candidate of unreadable) rejected.add(candidate.outpoint)\n this.release(reserved, unreadable)\n return undefined\n }\n const selected = inputs as ManagedInput[]\n const admitted = await this.spendable(assetId, selected)\n const unlisted = selected.filter(input => !admitted.has(input.outpoint))\n const recovered = await this.resubmitHeld(assetId, role, unlisted, originator)\n const missing = unlisted.filter(input => !recovered.has(input.outpoint))\n if (missing.length === 0) return selected\n for (const input of missing) rejected.add(input.outpoint)\n this.release(reserved, missing)\n return undefined\n }\n\n /**\n * Resubmits the wallet's own copies of the transactions behind held outputs that the overlay\n * does not report, as BTMS does when it selects, and returns the outputs it then admits.\n */\n protected async resubmitHeld(\n assetId: string,\n role: TokenRole,\n outputs: readonly SourceOutput[],\n originator: string\n ): Promise<Set<string>> {\n if (outputs.length === 0) return new Set()\n const txids = new Set(outputs.map(output => parseOutpoint(output.outpoint).txid))\n const beef = new Beef()\n for (let offset = 0; [...txids].some(txid => beef.findTxid(txid) === undefined);) {\n const page = await this.wallet.listOutputs(\n {\n basket: assetBasket(assetId, role),\n include: 'entire transactions',\n limit: LIST_PAGE_LIMIT,\n offset\n },\n originator\n )\n if (page.BEEF !== undefined) beef.mergeBeef(page.BEEF)\n offset += page.outputs.length\n if (page.outputs.length < LIST_PAGE_LIMIT) break\n }\n await eachInOrder(txids, async txid => {\n if (beef.findTxid(txid) === undefined) return\n const atomic = beef.toBinaryAtomic(txid)\n const { assetIds, deploy } = submissionAssets(Transaction.fromAtomicBEEF(atomic))\n // A refused resubmission leaves the output unlisted; the spendability check decides.\n await this.provider\n .submit([...(deploy ? [DISCOVERY_TOPIC] : []), ...assetIds.map(colorTopic)], atomic)\n .catch(() => undefined)\n })\n return await this.spendable(assetId, outputs)\n }\n\n /**\n * `callerBEEF` with the source transactions of the module's selected inputs merged in, each with\n * its proof or unproven ancestors and nothing else. Inputs the caller named keep the BEEF the\n * caller gave; the module adds none for them.\n */\n protected async inputBeef(\n callerBEEF: BEEF | undefined,\n inputs: readonly ManagedInput[],\n originator: string\n ): Promise<BEEF | undefined> {\n if (inputs.length === 0) return callerBEEF\n const beef =\n callerBEEF === undefined ? new Beef() : parsed('inputBEEF', () => Beef.fromBinary(callerBEEF))\n const baskets = new Map<string, ManagedInput[]>()\n for (const input of inputs) {\n if (input.sourceBEEF !== undefined) {\n mergeSource(beef, Beef.fromBinary(input.sourceBEEF), input.outpoint)\n continue\n }\n const basket = assetBasket(input.assetId, input.role)\n baskets.set(basket, [...(baskets.get(basket) ?? []), input])\n }\n await eachInOrder(baskets, async ([basket, selected]) => {\n const sources = await this.sourceTransactions(basket, selected, originator)\n for (const input of selected) mergeSource(beef, sources, input.outpoint)\n })\n return beef.toBinary()\n }\n\n /**\n * The selected inputs of one basket with their entire transactions, in one listing by their\n * suffix tags. The listing must return exactly the selected outputs.\n */\n protected async sourceTransactions(\n basket: string,\n selected: readonly ManagedInput[],\n originator: string\n ): Promise<Beef> {\n const listing = await this.wallet.listOutputs(\n {\n basket,\n tags: selected.map(input => suffixTagOf(input.custody)),\n tagQueryMode: 'any',\n include: 'entire transactions',\n limit: selected.length\n },\n originator\n )\n const wanted = new Set(selected.map(input => input.outpoint))\n const returned = new Set(listing.outputs.map(output => output.outpoint))\n const missing = [...wanted].filter(outpoint => !returned.has(outpoint))\n const extra = [...returned].filter(outpoint => !wanted.has(outpoint))\n if (missing.length > 0 || extra.length > 0 || listing.outputs.length !== wanted.size)\n throw new Error(\n `BRC-207: the wallet returned other outputs than the selected token inputs: missing ${\n missing.join(', ') || 'none'\n }; extra ${extra.join(', ') || 'none'}`\n )\n return listingBeef(listing)\n }\n\n /** One basket's token outputs of the asset, read from their locking scripts, excluding selected ones. */\n protected async candidates(\n assetId: string,\n role: TokenRole,\n originator: string\n ): Promise<Candidate[]> {\n const outputs = await this.listBasket(assetBasket(assetId, role), originator, {\n includeTags: true\n })\n return outputs.flatMap(output => {\n if (\n output.spendable === false ||\n this.selected.has(output.outpoint) ||\n this.staged.has(output.outpoint) ||\n output.customInstructions === undefined ||\n // An output without a suffix tag cannot be fetched by it, so it is not selected.\n !(output.tags ?? []).some(isDerivationSuffixTag)\n )\n return []\n const source = this.sourceOutput(output)\n const token = tryReadTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n if (token?.assetId !== assetId || token.role !== role) return []\n return [\n {\n ...source,\n token,\n amount: token.amount,\n customInstructions: output.customInstructions,\n tags: output.tags ?? []\n }\n ]\n })\n }\n\n /** A chosen candidate with its custody, or undefined when its custody record is unreadable. */\n protected async readableInput(\n candidate: Candidate,\n originator: string\n ): Promise<ManagedInput | undefined> {\n try {\n const { outpoint, lockingScript, satoshis, token, customInstructions, tags } = candidate\n const input = await this.custodyInput(\n { outpoint, lockingScript, satoshis, token },\n customInstructions,\n originator\n )\n // An output not tagged with its custody's suffix cannot be fetched by it, so it is skipped.\n if (input === undefined || !carriesSuffixTag(tags, input.custody)) return undefined\n return input\n } catch {\n return undefined\n }\n }\n\n /** A `p color` basket output as a managed token input, or undefined when it is not one. */\n protected async managedInput(\n output: WalletOutput,\n originator: string\n ): Promise<ManagedInput | undefined> {\n const source = this.sourceOutput(output)\n const token = readTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n if (token === undefined || output.customInstructions === undefined) return undefined\n return await this.custodyInput({ ...source, token }, output.customInstructions, originator)\n }\n\n /** Decrypts and parses an output's custody tuple; undefined when it names another asset. */\n protected async custodyInput(\n output: SourceOutput & { token: TokenOutput },\n customInstructions: string,\n originator: string\n ): Promise<ManagedInput | undefined> {\n const custody = parseCustody(\n await maybeDecryptMetadata(this.wallet, customInstructions, originator),\n undefined,\n 'managed output customInstructions'\n )\n if (!selectsAsset(custody.assetId, output.token)) return undefined\n const { token, ...source } = output\n return { ...source, assetId: token.assetId, role: token.role, amount: token.amount, custody }\n }\n\n /**\n * Before a handoff, splits the selected inputs into an output of exactly `amount` and token\n * change, broadcast and submitted. The split pays this wallet and, like BRC-177's revocation\n * anchor, needs no separate consent; the user approves the handoff itself in signAction.\n */\n protected async split(\n assetId: string,\n selected: ManagedInput[],\n amount: bigint,\n originator: string\n ): Promise<ManagedInput> {\n const change = sumAmounts(selected) - amount\n const exact = await this.newManagedOutput(assetId, amount, originator)\n const rest = await this.newManagedOutput(assetId, change, originator)\n // The split goes to the underlying wallet directly, so its custody is encrypted here.\n const outputs = await Promise.all(\n [exact.output, rest.output].map(async output => ({\n ...output,\n customInstructions: await encryptMetadata(\n this.wallet,\n output.customInstructions as string,\n originator\n )\n }))\n )\n const created = await this.wallet.createAction(\n {\n description: 'Split tokens for a handoff',\n labels: ColorPlan.toLabels({\n version: 1,\n assets: [assetId],\n ownedOutputs: [\n { outputIndex: 0, ...exact.custody },\n { outputIndex: 1, ...rest.custody }\n ],\n operations: [{ assetId, operation: 'transfer' }],\n inputPositions: [],\n changePositions: [],\n sighashTypes: []\n }),\n inputs: tokenInputs(selected),\n inputBEEF: await this.inputBeef(undefined, selected, originator),\n outputs,\n options: { randomizeOutputs: false, signAndProcess: false }\n },\n originator\n )\n const signable = created.signableTransaction\n if (signable == null) throw new Error('BRC-207: the split action was not returned for signing')\n const template = Transaction.fromAtomicBEEF(signable.tx)\n let signed: SignActionResult\n try {\n const spends = await this.signInputs(\n template,\n selected,\n new Map(),\n originator,\n 'BRC-207: the split transaction omits a token input'\n )\n signed = await this.wallet.signAction({ reference: signable.reference, spends }, originator)\n } catch (error) {\n await this.wallet\n .abortAction({ reference: signable.reference }, originator)\n .catch(() => undefined)\n throw error\n }\n if (signed.txid === undefined || signed.tx === undefined) {\n throw new Error('BRC-207: the split transaction was not returned')\n }\n await this.submit([assetId], signed.tx)\n return {\n outpoint: outpointString(signed.txid, 0),\n lockingScript: LockingScript.fromHex(exact.output.lockingScript),\n satoshis: TOKEN_CARRIER_SATOSHIS,\n assetId,\n role: 'value',\n amount,\n custody: exact.custody,\n sourceBEEF: signed.tx\n }\n }\n\n /** A fresh wallet-owned value output in the asset's basket, keyed to this wallet. */\n protected async newManagedOutput(\n assetId: string,\n amount: bigint,\n originator: string\n ): Promise<{ output: CreateActionOutput; custody: Custody }> {\n const custody: Custody = {\n assetId,\n derivationPrefix: toBase64(Random(16)),\n derivationSuffix: toBase64(Random(16)),\n senderIdentityKey: await this.identity()\n }\n const publicKey = await this.publicKey(custody, custody.senderIdentityKey, originator)\n return {\n custody,\n output: {\n lockingScript: new OneColor()\n .lock(assetId, amount, hash160(toArray(publicKey, 'hex')))\n .toHex(),\n satoshis: TOKEN_CARRIER_SATOSHIS,\n basket: assetBasket(assetId, 'value'),\n customInstructions: custodyInstructions(custody),\n tags: [suffixTagOf(custody)],\n outputDescription: 'BRC-207 token change'\n }\n }\n }\n\n /**\n * Checks the funded action against its plan, rechecks every token input's spendability, asks\n * the user to approve the final layout, and signs the inputs that spend this wallet's\n * `p color` outputs.\n */\n protected async signAction(\n args: SignActionArgs,\n action: PermissionsModuleAction | undefined,\n originator: string\n ): Promise<SignActionArgs> {\n if (action === undefined) return args\n const createArgs = action.createArgs\n const plan = ColorPlan.fromLabels(createArgs?.labels)\n if (createArgs === undefined || plan === undefined)\n throw new Error(\"BRC-207: signAction needs the action's p color createAction arguments\")\n const tx = action.transaction\n const tokens = transactionTokens(tx, true)\n assertTransactionOperations(plan, tokens)\n // Only the records bound to this reference are the module's to sign.\n const managed = this.bound.get(action.reference) ?? []\n try {\n return await this.signBound(args, { plan, createArgs, tx, tokens }, managed, originator)\n } finally {\n // Signed, refused or failed, the action is done with these records; the manager aborts a\n // refused or failed action, which returns its inputs to the wallet.\n this.bound.delete(action.reference)\n }\n }\n\n /** Rechecks, approves and signs the module's inputs of a funded action. */\n protected async signBound(\n args: SignActionArgs,\n funded: {\n plan: ColorPlan\n createArgs: CreateActionArgs\n tx: Transaction\n tokens: TransactionTokens\n },\n managed: ManagedInput[],\n originator: string\n ): Promise<SignActionArgs> {\n const { plan, createArgs, tx, tokens } = funded\n const scopes = sighashScopes(plan, new Set(managed.map(input => input.outpoint)))\n await eachInOrder(new Set(tokens.consumed.map(input => input.assetId)), async assetId => {\n const assetInputs = tokens.consumed.filter(input => input.assetId === assetId)\n const admitted = await this.spendable(assetId, assetInputs)\n if (assetInputs.some(input => !admitted.has(input.outpoint)))\n throw new Error(`BRC-207: a ${assetId} input is no longer spendable`)\n })\n await this.approve(originator, actionConsent(plan, createArgs, tx, tokens, managed, scopes))\n return {\n ...args,\n spends: {\n ...args.spends,\n ...(await this.signInputs(\n tx,\n managed,\n scopes,\n originator,\n 'BRC-207: the signable transaction omits a token input'\n ))\n }\n }\n }\n\n /**\n * Submits a signed token transaction to the topic of every asset among its inputs and outputs,\n * and a deploy to the discovery topic.\n */\n protected async submitSigned(result: SignActionResult, template: Transaction): Promise<void> {\n if (result?.tx === undefined) return\n const { assetIds, deploy } = submissionAssets(Transaction.fromAtomicBEEF(result.tx), template)\n if (assetIds.length > 0 || deploy) await this.submit(assetIds, result.tx, deploy)\n }\n\n /**\n * Submits a transaction to each asset topic, and a deploy to the discovery topic, trying again\n * up to `SUBMIT_ATTEMPTS` times before reporting the provider's failure. As in BTMS, an accepted\n * submission completes the action: every token input was overlay-checked and the plan verified\n * before signing, so an output the overlay then does not admit stays in its basket and is\n * resubmitted when it is next selected.\n */\n protected async submit(assetIds: string[], beef: AtomicBEEF, deploy = false): Promise<void> {\n const topics = [...(deploy ? [DISCOVERY_TOPIC] : []), ...assetIds.map(colorTopic)]\n let failure: unknown\n for (let attempt = 0; attempt < SUBMIT_ATTEMPTS; attempt++) {\n try {\n await this.provider.submit(topics, Array.from(beef))\n return\n } catch (error) {\n failure = error\n }\n }\n throw failure\n }\n\n /* ----------------------------------------------------------------------\n * App-built transactions (createSignature)\n * ---------------------------------------------------------------------- */\n\n /** Signs one managed input of an app-built transaction described by a 207 signature envelope. */\n protected async createSignature(\n args: CreateSignatureArgs,\n originator: string,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n if (args.hashToDirectlySign !== undefined) {\n throw new Error(\n 'BRC-207: p color signatures take a signature envelope, not hashToDirectlySign'\n )\n }\n const selector = this.parseKeyArgs(args)\n if (args.data === undefined || args.data.length > MAX_ENVELOPE_BYTES) {\n throw new Error('BRC-207: the signature envelope is missing or exceeds 16 MiB')\n }\n const envelope = jsonObject(\n parseStrictJsonBytes(args.data, 'signature envelope'),\n 'signature envelope'\n )\n exactMembers(\n envelope,\n ['version', 'tx', 'inputIndex', 'sighashType', 'ownedOutputs'],\n ['profileData'],\n 'signature envelope'\n )\n if (envelope.version !== 1) throw new Error('BRC-207: signature envelope version must be 1')\n if (\n Object.keys(parseProfileData(envelope.profileData, 'signature envelope profileData') ?? {})\n .length > 0\n ) {\n throw new Error(\n 'BRC-207: signature envelope profileData names a profile the asset does not require'\n )\n }\n const tx = parsed('the signature envelope tx', () =>\n Transaction.fromAtomicBEEF(\n jsonByteArray(envelope.tx, 'signature envelope tx', MAX_ENVELOPE_BYTES)\n )\n )\n const inputIndex = jsonUint32(envelope.inputIndex, 'signature envelope inputIndex')\n const sighashType = jsonUint32(envelope.sighashType, 'signature envelope sighashType')\n if (sighashType > 255) throw new Error('BRC-207: sighashType must be in 0..255')\n const ownedOutputs = parseRemittances(envelope.ownedOutputs, 'signature envelope ownedOutputs')\n const input = tx.inputs[inputIndex]\n const sourceTransaction = input?.sourceTransaction\n const source = sourceTransaction?.outputs[input.sourceOutputIndex]\n if (sourceTransaction === undefined || source?.satoshis === undefined) {\n throw new Error('BRC-207: the envelope must carry the signed input source transaction')\n }\n const sourceTXID = sourceTransaction.id('hex')\n const token = readTokenOutput(source.lockingScript, {\n txid: sourceTXID,\n vout: input.sourceOutputIndex\n })\n if (token === undefined || !selectsAsset(selector.assetId, token)) {\n throw new Error(\n 'BRC-207: the protocol asset selector does not match the signed source output'\n )\n }\n await this.assertOwned(token, selector, args.counterparty ?? 'anyone', originator)\n // The signature commits to the whole transaction, so it is evaluated as a send is: every\n // input authenticated from its source, every asset's legs and supply change derived, and\n // every token input admitted and unspent in its overlay.\n const tokens = transactionTokens(tx, true)\n await this.assertSupportedAssets([\n token.assetId,\n ...tokens.inputs.keys(),\n ...tokens.outputs.keys()\n ])\n await Promise.all(\n ownedOutputs.map(async remittance => {\n const output = tx.outputs[remittance.outputIndex]\n const owned =\n output === undefined\n ? undefined\n : readTokenOutput(output.lockingScript, {\n txid: '00'.repeat(32),\n vout: remittance.outputIndex\n })\n if (owned === undefined || owned.deploy || remittance.assetId !== owned.assetId) {\n throw new Error('BRC-207: an envelope remittance does not match its output')\n }\n await this.assertOwned(owned, remittance, remittance.senderIdentityKey, originator)\n })\n )\n const outpoint = outpointString(sourceTXID, input.sourceOutputIndex)\n const signed = { outpoint, lockingScript: source.lockingScript, satoshis: source.satoshis }\n await eachInOrder(new Set(tokens.consumed.map(consumed => consumed.assetId)), async assetId => {\n const assetInputs = tokens.consumed.filter(consumed => consumed.assetId === assetId)\n const admitted = await this.spendable(assetId, assetInputs)\n if (!admitted.has(outpoint) && assetId === token.assetId)\n throw new Error('BRC-207: the signed input is not admitted and unspent in its overlay')\n if (assetInputs.some(consumed => !admitted.has(consumed.outpoint)))\n throw new Error(`BRC-207: a ${assetId} input is not admitted and unspent in its overlay`)\n })\n const preimage = this.preimage(tx, inputIndex, signed, sighashType)\n const kept = (vout: number): boolean =>\n ownedOutputs.some(remittance => remittance.outputIndex === vout)\n await this.approve(originator, {\n type: 'color_signature',\n inputIndex,\n ...transactionConsent(\n tx,\n tokens,\n [token],\n kept,\n vout => !kept(vout),\n [{ outpoint, inputIndex, sighashType }],\n kept(0)\n )\n })\n return await next({\n protocolID: args.protocolID,\n keyID: args.keyID,\n counterparty: args.counterparty,\n privileged: args.privileged,\n privilegedReason: args.privilegedReason,\n seekPermission: args.seekPermission,\n hashToDirectlySign: hash256(preimage)\n })\n }\n\n /* ----------------------------------------------------------------------\n * Read views\n * ---------------------------------------------------------------------- */\n\n protected async listOutputs(\n args: ListOutputsArgs,\n originator: string,\n next: PermissionsModuleNext\n ): Promise<unknown> {\n const seekPermission = args.seekPermission !== false\n if (args.basket === ASSETS_SELECTOR) {\n await this.authorizeRead(originator, { basket: args.basket, seekPermission })\n return await this.inventory(args, originator)\n }\n const balance = parseBalanceSelector(args.basket)\n if (balance !== undefined) {\n await this.authorizeRead(originator, { basket: args.basket, ...balance, seekPermission })\n return await this.balance(balance.assetId, balance.role, args, originator)\n }\n const held = parseAssetBasket(args.basket)\n if (held !== undefined) {\n await this.authorizeRead(originator, { basket: args.basket, ...held, seekPermission })\n return await next(args)\n }\n throw new Error('BRC-207: unknown p color basket selector')\n }\n\n /** `p color balance`: exact sum of available token units, or count of available authorities. */\n protected async balance(\n assetId: string,\n role: TokenRole,\n args: ListOutputsArgs,\n originator: string\n ): Promise<ListOutputsResult> {\n // As in BTMS, a read reports wallet state alone: the basket's unreserved, unspent outputs.\n // The overlay is consulted only when spending.\n const held = (await this.listBasket(assetBasket(assetId, role), originator, args))\n .map(output => {\n const source = this.sourceOutput(output)\n return readTokenOutput(source.lockingScript, parseOutpoint(output.outpoint))\n })\n .filter(token => token?.assetId === assetId && token.role === role)\n const total = held.reduce((sum, token) => sum + (role === 'value' ? token!.amount : 1n), 0n)\n return { totalOutputs: total.toString(), outputs: [] }\n }\n\n /** `p color assets`: every held token output across all per-asset baskets, with its state. */\n protected async inventory(args: ListOutputsArgs, originator: string): Promise<ListOutputsResult> {\n const entireTransactions = args.include === 'entire transactions'\n const listed = await this.wallet.listOutputs(\n {\n basket: toolbox.specOpBasketPrefixOutputs,\n tags: [COLOR_BASKET_NAMESPACE],\n include: entireTransactions ? 'entire transactions' : 'locking scripts',\n includeCustomInstructions: args.includeCustomInstructions,\n includeTags: true,\n includeLabels: args.includeLabels\n },\n originator\n )\n const beef =\n entireTransactions && listed.BEEF !== undefined ? Beef.fromBinary(listed.BEEF) : undefined\n const views = inventoryRecords(listed.outputs, beef)\n .map(inventoryView)\n .filter(view => matchesTags(view.tags, args.tags ?? [], args.tagQueryMode))\n const limit = args.limit ?? 10\n const offset = args.offset ?? 0\n const ordered = offset < 0 ? [...views].reverse() : views\n const start = offset < 0 ? -offset - 1 : offset\n const page = ordered.slice(start, start + limit)\n // Only the returned page is decrypted and carried in the BEEF.\n const result: ListOutputsResult = {\n totalOutputs: views.length,\n outputs: await Promise.all(\n page.map(async view => await this.inventoryOutput(view, args, originator))\n )\n }\n if (beef !== undefined) result.BEEF = pageBeef(beef, page)\n return result\n }\n\n /** One inventory record as a BRC-100 output with the fields the caller asked for. */\n protected async inventoryOutput(\n view: InventoryView,\n args: ListOutputsArgs,\n originator: string\n ): Promise<WalletOutput> {\n const { record, state, tags } = view\n const output: WalletOutput = {\n satoshis: record.output.satoshis,\n spendable: state === 'available',\n outpoint: record.output.outpoint\n }\n if (args.include === 'locking scripts')\n output.lockingScript = record.source.lockingScript.toHex()\n if (args.includeCustomInstructions === true && record.output.customInstructions !== undefined) {\n output.customInstructions = await maybeDecryptMetadata(\n this.wallet,\n record.output.customInstructions,\n originator\n )\n }\n if (args.includeTags === true) output.tags = tags\n if (args.includeLabels === true) output.labels = record.output.labels\n return output\n }\n\n /* ----------------------------------------------------------------------\n * Shared helpers\n * ---------------------------------------------------------------------- */\n\n /** Validates a `p color` key reference and returns its asset selector and remittance strings. */\n protected parseKeyArgs(args: {\n protocolID?: unknown\n keyID?: unknown\n }): ReturnType<typeof parseColorProtocolID> {\n if (args.keyID !== COLOR_KEY_ID) throw new Error('BRC-207: p color keys use keyID \"color\"')\n return parseColorProtocolID(args.protocolID)\n }\n\n protected async identity(): Promise<string> {\n if (this.identityKey === undefined) {\n const pending = this.wallet\n .getPublicKey({ identityKey: true })\n .then(({ publicKey }) => publicKey)\n this.identityKey = pending\n // A rejected lookup is not cached; the next call asks the wallet again.\n pending.catch(() => {\n if (this.identityKey === pending) this.identityKey = undefined\n })\n }\n return await this.identityKey\n }\n\n protected async publicKey(\n custody: Pick<Custody, 'assetId' | 'derivationPrefix' | 'derivationSuffix'>,\n counterparty: WalletCounterparty,\n originator: string\n ): Promise<string> {\n const { publicKey } = await this.wallet.getPublicKey(\n {\n protocolID: colorProtocolID(\n custody.assetId,\n custody.derivationPrefix,\n custody.derivationSuffix\n ),\n keyID: COLOR_KEY_ID,\n counterparty,\n forSelf: true\n },\n originator\n )\n return publicKey\n }\n\n /** Fails unless the output is a P2PKH remainder locked to this wallet's derived `p color` key. */\n protected async assertOwned(\n token: TokenOutput,\n custody: Pick<Custody, 'assetId' | 'derivationPrefix' | 'derivationSuffix'>,\n counterparty: WalletCounterparty,\n originator: string\n ): Promise<void> {\n if (token.pubKeyHash === undefined)\n throw new Error('BRC-207: a managed token output must have a P2PKH remainder')\n const publicKey = await this.publicKey(custody, counterparty, originator)\n if (toHex(hash160(toArray(publicKey, 'hex'))) !== toHex(token.pubKeyHash)) {\n throw new Error(\"BRC-207: the token output is not locked to this wallet's p color key\")\n }\n }\n\n /**\n * Authenticates the asset's deploy through the overlay and fails when it declares\n * required processing profiles. The deploy bytes hash to the asset ID, so no SPV is needed.\n */\n protected async assertSupportedAsset(assetId: string): Promise<void> {\n let check = this.supportedAssets.get(assetId)\n if (check === undefined) {\n check = (async () => {\n const { txid, vout } = parseAssetId(assetId)\n const outpoint = outpointString(txid, vout)\n const deploy = readOutputList(await this.provider.admission(assetId, [outpoint]), [\n outpoint\n ]).get(outpoint)\n if (deploy === undefined)\n throw new Error(`BRC-207: the overlay has no admitted deploy for ${assetId}`)\n if (!isDeployOutput(deploy.lockingScript, { txid, vout })) {\n throw new Error(`BRC-207: ${assetId} is not a token deploy`)\n }\n })()\n this.supportedAssets.set(assetId, check)\n check.catch(() => this.supportedAssets.delete(assetId))\n }\n await check\n }\n\n /** The queried outputs the overlay reports admitted and unspent, matched to their source bytes. */\n protected async spendable(\n assetId: string,\n outputs: readonly SourceOutput[]\n ): Promise<Set<string>> {\n const outpoints = outputs.map(output => output.outpoint)\n const listed = readOutputList(await this.provider.spendability(assetId, outpoints), outpoints)\n for (const output of outputs) {\n const answer = listed.get(output.outpoint)\n if (\n answer !== undefined &&\n (answer.satoshis !== output.satoshis ||\n answer.lockingScript.toHex() !== output.lockingScript.toHex())\n ) {\n throw new Error(\n `BRC-207: the overlay answer for ${output.outpoint} does not match its source output`\n )\n }\n }\n return new Set(listed.keys())\n }\n\n /** All spendable outputs of one basket, with locking scripts and custom instructions. */\n protected async listBasket(\n basket: string,\n originator: string,\n filter: Pick<ListOutputsArgs, 'tags' | 'tagQueryMode' | 'includeTags'>\n ): Promise<WalletOutput[]> {\n const outputs: WalletOutput[] = []\n for (;;) {\n const page = await this.wallet.listOutputs(\n {\n basket,\n tags: filter.tags,\n tagQueryMode: filter.tagQueryMode,\n includeTags: filter.includeTags,\n include: 'locking scripts',\n includeCustomInstructions: true,\n limit: LIST_PAGE_LIMIT,\n offset: outputs.length\n },\n originator\n )\n outputs.push(...page.outputs)\n if (page.outputs.length < LIST_PAGE_LIMIT) return outputs\n }\n }\n\n protected sourceOutput(output: WalletOutput): SourceOutput {\n if (output.lockingScript === undefined)\n throw new Error('BRC-207: the wallet omitted a locking script')\n return {\n outpoint: output.outpoint,\n lockingScript: LockingScript.fromHex(output.lockingScript),\n satoshis: output.satoshis\n }\n }\n\n protected preimage(\n tx: Transaction,\n inputIndex: number,\n source: SourceOutput,\n scope: number\n ): number[] {\n if ((scope & 0x1f) === TransactionSignature.SIGHASH_SINGLE && inputIndex >= tx.outputs.length) {\n throw new Error('BRC-207: SIGHASH_SINGLE requires an output at the signed input index')\n }\n const { txid, vout } = parseOutpoint(source.outpoint)\n return TransactionSignature.format({\n sourceTXID: txid,\n sourceOutputIndex: vout,\n sourceSatoshis: source.satoshis,\n transactionVersion: tx.version,\n otherInputs: tx.inputs.filter((_, index) => index !== inputIndex),\n allInputs: tx.inputs,\n outputs: tx.outputs,\n inputIndex,\n subscript: source.lockingScript,\n inputSequence: tx.inputs[inputIndex].sequence ?? 0xffffffff,\n lockTime: tx.lockTime,\n scope\n })\n }\n\n /** Unlocking scripts for this module's inputs of `template`, keyed by input index. */\n protected async signInputs(\n template: Transaction,\n inputs: readonly ManagedInput[],\n scopes: ReadonlyMap<string, number>,\n originator: string,\n missing: string\n ): Promise<Record<number, { unlockingScript: string }>> {\n const indexed = inputs.map(input => {\n const index = template.inputs.findIndex(\n candidate => inputOutpoint(candidate) === input.outpoint\n )\n if (index < 0) throw new Error(missing)\n return { index, input }\n })\n const scripts = await Promise.all(\n indexed.map(\n async ({ index, input }) =>\n await this.unlock(\n template,\n index,\n input,\n scopes.get(input.outpoint) ?? DEFAULT_SIGHASH,\n originator\n )\n )\n )\n return Object.fromEntries(\n indexed.map(({ index }, position) => [index, { unlockingScript: scripts[position] }])\n )\n }\n\n /** P2PKH unlocking script for a managed input, signed with its `p color` key. */\n protected async unlock(\n tx: Transaction,\n inputIndex: number,\n input: ManagedInput,\n scope: number,\n originator: string\n ): Promise<string> {\n const protocolID = colorProtocolID(\n input.custody.assetId,\n input.custody.derivationPrefix,\n input.custody.derivationSuffix\n )\n const counterparty = input.custody.senderIdentityKey\n const { signature } = await this.wallet.createSignature(\n {\n protocolID,\n keyID: COLOR_KEY_ID,\n counterparty,\n hashToDirectlySign: hash256(this.preimage(tx, inputIndex, input, scope))\n },\n originator\n )\n const der = Signature.fromDER(signature)\n const checksig = new TransactionSignature(der.r, der.s, scope).toChecksigFormat()\n const publicKey = toArray(await this.publicKey(input.custody, counterparty, originator), 'hex')\n return new UnlockingScript([\n { op: checksig.length, data: checksig },\n { op: publicKey.length, data: publicKey }\n ]).toHex()\n }\n\n protected async approve(originator: string, request: Record<string, unknown>): Promise<void> {\n const approved = await this.requestTokenAccess(originator, JSON.stringify(request))\n if (approved !== true)\n throw new Error(`BRC-207: the user declined the ${String(request.type)} request`)\n }\n\n /** Every `p color` read asks the host; the host decides whether an existing grant covers it. */\n /**\n * Asks the host to approve a read, naming what is read: the `basket` requested (with the\n * `assetId` and `role` of a balance or holdings read) or the `p color` `labels` of a\n * listActions, and the caller's `seekPermission`.\n */\n protected async authorizeRead(originator: string, read: Record<string, unknown>): Promise<void> {\n await this.approve(originator, { type: 'color_access', ...read })\n }\n}\n","import { ColorPermissionModule } from './ColorPermissionModule.js'\nimport type { ColorPermissionModuleOptions } from './types.js'\n\nexport {\n ColorPermissionModule,\n actionConsent,\n assertPlanAssets,\n assertTransactionOperations,\n assertUnlocks,\n authorityOperation,\n deployOperation,\n readSentToken,\n requiredOperations,\n sighashScopes,\n submissionAssets,\n supplyChange,\n tokenSources,\n transactionConsent,\n transactionTokens,\n tryReadTokenOutput\n} from './ColorPermissionModule.js'\nexport type {\n Custody,\n Holding,\n ManagedInput,\n ReleasedSignature,\n SourceOutput,\n TransactionTokens\n} from './ColorPermissionModule.js'\nexport {\n UnsupportedProfileError,\n assertNoRequiredProfiles,\n readAnyTokenOutput,\n readJsonTokenOutput,\n readTokenOutput\n} from './tokenOutputs.js'\nexport type { JsonOperation, TokenOutput } from './tokenOutputs.js'\nexport { ColorPlan, COLOR_PLAN_LABEL_PREFIX, COLOR_OPERATIONS } from './ColorPlan.js'\nexport type { ColorOperation, ColorOperationName, ColorRemittance } from './ColorPlan.js'\nexport {\n ASSETS_SELECTOR,\n COLOR_KEY_ID,\n ISSUE,\n assetBasket,\n assetTag,\n colorProtocolID,\n colorTopic,\n parseAssetBasket,\n parseBalanceSelector,\n parseColorProtocolID\n} from './identifiers.js'\nexport type { TokenRole } from './identifiers.js'\nexport type {\n ColorOverlayProvider,\n ColorPermissionModuleOptions,\n ColorTokenAccessHandler\n} from './types.js'\n\nexport const createColorModule = (options: ColorPermissionModuleOptions): ColorPermissionModule =>\n new ColorPermissionModule(options)\n"],"mappings":";;;;;;;;AAKA,MAAa,QAAQ;;AAGrB,MAAa,eAAe;;AAG5B,MAAa,kBAAkB;;AAG/B,MAAa,yBAAyB;AAItC,MAAM,WAAW;AACjB,MAAM,YAAY;AAClB,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,eAAe;AACrB,MAAM,aAAa;AACnB,MAAMA,eAAa;AACnB,MAAM,2BAA2B;AAEjC,MAAMC,iBAAe,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;AAO9E,SAAS,OAAO,MAAkC;CAChD,MAAM,QAAQ,OAAO,IAAI;CACzB,OAAO,SAASD,eAAa,QAAQ,KAAA;AACvC;;AAGA,SAAgB,aAAa,SAA4B;CACvD,MAAM,QAAQ,OAAO,YAAY,WAAW,SAAS,KAAK,OAAO,IAAI;CACrE,MAAM,OAAO,SAAS,OAAO,KAAA,IAAY,OAAO,MAAM,EAAE;CACxD,IAAI,SAAS,QAAQ,SAAS,KAAA,GAAW,MAAM,IAAI,MAAM,2BAA2B;CACpF,OAAO;EAAE,MAAM,MA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