{"version":3,"file":"index.cjs","names":["bytesToBase64","v","vCryptoGenericNetworkId","vNearTransactionHash"],"sources":["../src/nice_action/actions/impl/new_key_transfer_completion.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport * as v from \"valibot\";\nimport { bytesToBase64 } from \"../../../utils/serialization/canonical_json\";\nimport {\n  type TCryptoGenericNetworkId,\n  vCryptoGenericNetworkId,\n  vNearTransactionHash,\n} from \"./act_impl_meteor_wallet_core.schemas\";\n\n/**\n * Wallet-completion primitives for the new-key transfer stabilization:\n *\n * - SD2 backup-confirmation evidence — the journal-level proof a wallet must hold before it may\n *   mark a seed-phrase session `backed_up` and publish destination keys. A UI boolean is never\n *   sufficient; the wallet's journal-mutation API takes this object and validates it.\n * - SD13 activation self-test (\"liveness transfer\") — the optional 1-yoctoNEAR transfer each\n *   transferred account sends to the team-owned migration receiver during the verify turn, after\n *   proof + import, as an end-to-end signing check. Strictly additive to the AddKey proof.\n *\n * Both wallets and the demo references consume these single definitions so the receiver ids,\n * bounds, and outcome shapes can never drift per consumer.\n */\n\n// --- SD2: backup-confirmation evidence ---------------------------------------\n\nexport const NEW_KEY_TRANSFER_BACKUP_EVIDENCE_FORMAT_VERSION = 1;\n\nexport const NEW_KEY_TRANSFER_BACKUP_METHODS = [\n  /** The user re-selected every word, in order, from a shuffled grid. */\n  \"full_phrase_word_selection\",\n  /** The user re-entered every word, in order. */\n  \"full_phrase_reentry\",\n  /**\n   * The user identified the phrase's first and last words among decoys. The wallet must validate\n   * the two selected words against the session phrase itself — never a UI boolean — and the\n   * evidence hash still commits to the full phrase that was backed up.\n   */\n  \"first_last_word_selection\",\n] as const;\n\n/** How many words a `first_last_word_selection` confirmation proves: exactly the two endpoints. */\nexport const NEW_KEY_TRANSFER_FIRST_LAST_CONFIRMED_WORD_COUNT = 2;\n\n/**\n * Normalize a recovery phrase exactly the way derivation does (trim, collapse whitespace,\n * lowercase, NFKD) so the evidence hash is stable across renderings of the same phrase.\n */\nexport const normalizeNewKeyTransferRecoveryPhrase = (phrase: string): string =>\n  phrase.trim().replace(/\\s+/g, \" \").toLowerCase().normalize(\"NFKD\");\n\n/**\n * One-way commitment to the confirmed phrase. The evidence stores ONLY this hash — never words,\n * word indexes' values, or any recoverable fragment of the phrase.\n */\nexport const hashNewKeyTransferRecoveryPhrase = (phrase: string): string =>\n  bytesToBase64(sha256(new TextEncoder().encode(normalizeNewKeyTransferRecoveryPhrase(phrase))));\n\nconst vSafeEpochMillis = v.pipe(\n  v.number(),\n  v.check(\n    (value) => Number.isSafeInteger(value) && value > 0,\n    \"Timestamps must be positive safe-integer epoch milliseconds\",\n  ),\n);\n\nexport const vNewKeyTransferBackupEvidenceV1 = v.pipe(\n  v.object({\n    formatVersion: v.literal(NEW_KEY_TRANSFER_BACKUP_EVIDENCE_FORMAT_VERSION),\n    method: v.picklist(NEW_KEY_TRANSFER_BACKUP_METHODS),\n    /** Phrase length in words. The transfer flow issues standard 12- or 24-word phrases only. */\n    wordCount: v.picklist([12, 24]),\n    /** How many words the user confirmed. The per-method requirement is enforced below. */\n    confirmedWordCount: v.pipe(v.number(), v.integer(), v.minValue(1)),\n    /** {@link hashNewKeyTransferRecoveryPhrase} of the confirmed phrase (standard base64, 32 bytes). */\n    phraseSha256Base64: v.pipe(v.string(), v.length(44)),\n    confirmedAt: vSafeEpochMillis,\n  }),\n  v.check(\n    (evidence) =>\n      evidence.method === \"first_last_word_selection\"\n        ? evidence.confirmedWordCount === NEW_KEY_TRANSFER_FIRST_LAST_CONFIRMED_WORD_COUNT\n        : evidence.confirmedWordCount === evidence.wordCount,\n    \"Full-phrase methods must confirm every word; the first/last spot-check confirms exactly two\",\n  ),\n);\n\nexport type TNewKeyTransferBackupEvidenceV1 = v.InferOutput<typeof vNewKeyTransferBackupEvidenceV1>;\n\n/**\n * The store-level gate for advancing `backup_required -> backed_up`: the evidence must parse, be\n * complete, and commit to exactly the session phrase the wallet holds.\n */\nexport const isCompleteNewKeyTransferBackupEvidence = (input: {\n  evidence: unknown;\n  sessionPhrase: string;\n}): boolean => {\n  const parsed = v.safeParse(vNewKeyTransferBackupEvidenceV1, input.evidence);\n  if (!parsed.success) return false;\n  return parsed.output.phraseSha256Base64 === hashNewKeyTransferRecoveryPhrase(input.sessionPhrase);\n};\n\n// --- SD13: activation self-test (liveness transfer) --------------------------\n\n/**\n * Team-owned migration receivers. These accounts MUST exist and be controlled by the Meteor team\n * on their networks before the self-test is enabled anywhere (stabilization plan Phase 6.6) — a\n * NEAR transfer to a non-existent named account fails.\n */\nexport const NEW_KEY_TRANSFER_LIVENESS_RECEIVER_ACCOUNT_IDS = {\n  mainnet: \"meteor-migrate.near\",\n  testnet: \"meteor-migrate.testnet\",\n} as const satisfies Record<TCryptoGenericNetworkId, string>;\n\nexport const resolveNewKeyTransferLivenessReceiver = (networkId: TCryptoGenericNetworkId): string =>\n  NEW_KEY_TRANSFER_LIVENESS_RECEIVER_ACCOUNT_IDS[v.parse(vCryptoGenericNetworkId, networkId)];\n\n/** The self-test sends exactly this amount; its value is deliberately irrelevant. */\nexport const NEW_KEY_TRANSFER_LIVENESS_AMOUNT_YOCTO = 1n;\n\n/**\n * Available-balance floor below which the self-test is skipped rather than attempted: a transfer\n * action costs ~0.00005 N in gas, so 0.0005 N keeps a 10× margin without ever blocking a\n * low-balance account's completion (Phase 0.4 default).\n */\nexport const NEW_KEY_TRANSFER_LIVENESS_MIN_AVAILABLE_BALANCE_YOCTO = 500_000_000_000_000_000_000n;\n\n/** Bounded fan-out so a 30-account batch fits the 5-minute turn window with margin (Phase 0.4). */\nexport const NEW_KEY_TRANSFER_LIVENESS_MAX_CONCURRENCY = 4;\n\n/** Bounded broadcast attempts before an uncertain outcome becomes `skipped` (never a block). */\nexport const NEW_KEY_TRANSFER_LIVENESS_MAX_ATTEMPTS = 2;\n\nexport const NEW_KEY_TRANSFER_LIVENESS_SKIP_REASONS = [\n  \"policy_disabled\",\n  \"insufficient_balance\",\n  \"rpc_uncertain\",\n] as const;\n\nexport const NEW_KEY_TRANSFER_LIVENESS_FAILURE_REASONS = [\n  /** The wallet could not produce a valid signature with the destination signer. */\n  \"signing_failed\",\n  /** The chain definitively rejected/failed the signed self-test transaction. */\n  \"execution_failed\",\n] as const;\n\n/**\n * The wallet-journal record of one account's self-test. `confirmed` and `failed` are terminal;\n * a re-entrant verify reuses a journaled `confirmed`/`skipped` outcome and NEVER re-sends a\n * confirmed test, while `failed` is retried on the next verify. Maps onto the wire as:\n * `confirmed`/`skipped` → `secured` + `liveness`; `failed` → `verified_pending_completion` +\n * `pendingFact: \"liveness_check_failed\"`.\n */\nexport const vNewKeyTransferLivenessOutcomeV1 = v.union([\n  v.object({\n    status: v.literal(\"confirmed\"),\n    transactionHash: vNearTransactionHash,\n    confirmedAt: vSafeEpochMillis,\n  }),\n  v.object({\n    status: v.literal(\"skipped\"),\n    reason: v.picklist(NEW_KEY_TRANSFER_LIVENESS_SKIP_REASONS),\n  }),\n  v.object({\n    status: v.literal(\"failed\"),\n    reason: v.picklist(NEW_KEY_TRANSFER_LIVENESS_FAILURE_REASONS),\n    failedAt: vSafeEpochMillis,\n  }),\n]);\n\nexport type TNewKeyTransferLivenessOutcomeV1 = v.InferOutput<\n  typeof vNewKeyTransferLivenessOutcomeV1\n>;\n\nexport const parseNewKeyTransferLivenessOutcomeV1 = (\n  outcome: unknown,\n): TNewKeyTransferLivenessOutcomeV1 => v.parse(vNewKeyTransferLivenessOutcomeV1, outcome);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,kDAAkD;AAE/D,MAAa,kCAAkC;CAE7C;CAEA;CAMA;AACF;;AAGA,MAAa,mDAAmD;;;;;AAMhE,MAAa,yCAAyC,WACpD,OAAO,KAAK,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC,UAAU,MAAM;;;;;AAMnE,MAAa,oCAAoC,WAC/CA,cAAAA,eAAAA,GAAAA,sBAAAA,OAAAA,CAAqB,IAAI,YAAY,CA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