@swapkit/wallet-hardware 4.9.10 → 4.9.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,9 +2,9 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/trezor/index.ts"],
4
4
  "sourcesContent": [
5
- "import { HDKey, type Versions } from \"@scure/bip32\";\nimport {\n Chain,\n type DerivationPathArray,\n derivationPathToString,\n FeeOption,\n filterSupportedChains,\n type GenericTransferParams,\n NetworkDerivationPath,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n WalletOption,\n} from \"@swapkit/helpers\";\nimport {\n assertDerivationIndex,\n createHDWalletHelpers,\n getNetworkForChain,\n getUTXOAccountIndexFromPath,\n getUTXOAccountPath,\n getUtxoApi,\n type UTXOToolboxes,\n type UTXOType,\n} from \"@swapkit/toolboxes/utxo\";\nimport type { BTCNetwork, PCZT, Transaction, ZcashTransaction } from \"@swapkit/utxo-signer\";\nimport { BCHSigHash, NETWORKS, ZcashConsensusBranchId, ZcashVersionGroupId } from \"@swapkit/utxo-signer\";\nimport { createWallet, getWalletSupportedChains, type HardwareExtendedPublicKeyInfo } from \"@swapkit/wallet-core\";\n\ntype TrezorBip32Derivation = [Uint8Array, { fingerprint: number; path: number[] }];\ntype TrezorCoreMode = \"auto\" | \"iframe\" | \"popup\" | \"suite-desktop\" | \"suite-web\";\ntype TrezorTransport = \"BridgeTransport\" | \"WebUsbTransport\" | \"NodeUsbTransport\";\ntype ConnectTrezorOptions = { address?: string };\ntype TrezorExtendedPublicKeyInfo = {\n accountIndex: number;\n chainCode?: string;\n depth?: number;\n fingerprint?: number;\n path: string;\n publicKey?: string;\n xpub: string;\n xpubSegwit?: string;\n};\n\nconst TREZOR_CORE_MODES = new Set<TrezorCoreMode>([\"auto\", \"iframe\", \"popup\", \"suite-desktop\", \"suite-web\"]);\nconst TREZOR_TRANSPORTS = new Set<TrezorTransport>([\"BridgeTransport\", \"WebUsbTransport\", \"NodeUsbTransport\"]);\nconst DEFAULT_TREZOR_MANIFEST = { appName: \"SwapKit\", appUrl: \"https://swapkit.dev\", email: \"support@swapkit.dev\" };\nconst DEFAULT_TREZOR_TRANSPORTS = [\"WebUsbTransport\" as const];\nconst TREZOR_KEEP_SESSION_PARAMS = { keepSession: true } as const;\nconst trezorXpubCache = new Map<string, TrezorExtendedPublicKeyInfo>();\nlet trezorSessionDispose: Promise<void> | undefined;\nconst EXTENDED_KEY_VERSION_CANDIDATES = [\n NETWORKS.bitcoin.bip32,\n NETWORKS.bitcoinCash.bip32,\n NETWORKS.dash.bip32,\n NETWORKS.dogecoin.bip32,\n NETWORKS.litecoin.bip32,\n];\n\nasync function disconnectTrezorSession() {\n trezorXpubCache.clear();\n\n const dispose = (async () => {\n try {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n await TrezorConnect.dispose();\n } catch {\n // Ignore stale or already-disposed sessions.\n }\n })();\n\n trezorSessionDispose = dispose;\n await dispose;\n\n if (trezorSessionDispose === dispose) {\n trezorSessionDispose = undefined;\n }\n}\n\nfunction normalizeTrezorCoreMode(coreMode: unknown): TrezorCoreMode | undefined {\n return typeof coreMode === \"string\" && TREZOR_CORE_MODES.has(coreMode as TrezorCoreMode)\n ? (coreMode as TrezorCoreMode)\n : undefined;\n}\n\nfunction normalizeTrezorTransports(transports: unknown): TrezorTransport[] | undefined {\n if (!Array.isArray(transports)) return undefined;\n\n const normalized = transports.filter(\n (transport): transport is TrezorTransport =>\n typeof transport === \"string\" && TREZOR_TRANSPORTS.has(transport as TrezorTransport),\n );\n\n return normalized.length > 0 ? normalized : undefined;\n}\n\nfunction getTrezorManifestValue(value: unknown, fallback: string) {\n return typeof value === \"string\" && value.trim() ? value : fallback;\n}\n\nfunction getDefaultTrezorAppUrl() {\n return typeof globalThis.location !== \"undefined\" && globalThis.location.origin\n ? globalThis.location.origin\n : DEFAULT_TREZOR_MANIFEST.appUrl;\n}\n\nasync function initTrezorConnect() {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n\n const trezorConfig = SKConfig.get(\"integrations\").trezor as Record<string, unknown> | undefined;\n const {\n connectSrc,\n coreMode,\n debug,\n interactionTimeout,\n lazyLoad,\n pendingTransportEvent,\n popup,\n transportReconnect,\n transports,\n ...manifestConfig\n } = trezorConfig ?? {};\n const manifest = {\n ...manifestConfig,\n appName: getTrezorManifestValue(trezorConfig?.appName, DEFAULT_TREZOR_MANIFEST.appName),\n appUrl: getTrezorManifestValue(trezorConfig?.appUrl, getDefaultTrezorAppUrl()),\n email: getTrezorManifestValue(trezorConfig?.email, DEFAULT_TREZOR_MANIFEST.email),\n };\n const isLocalhost =\n typeof globalThis.location !== \"undefined\" && [\"localhost\", \"127.0.0.1\"].includes(globalThis.location.hostname);\n const resolvedCoreMode = normalizeTrezorCoreMode(coreMode) ?? \"popup\";\n const resolvedTransports = normalizeTrezorTransports(transports) ?? DEFAULT_TREZOR_TRANSPORTS;\n\n if (trezorSessionDispose) {\n await trezorSessionDispose;\n }\n\n if (isLocalhost) {\n await TrezorConnect.dispose();\n }\n\n await TrezorConnect.init({\n connectSrc: connectSrc as string | undefined,\n coreMode: resolvedCoreMode,\n debug: debug as boolean | undefined,\n interactionTimeout: interactionTimeout as number | undefined,\n lazyLoad: (lazyLoad as boolean | undefined) ?? false,\n manifest,\n pendingTransportEvent: pendingTransportEvent as boolean | undefined,\n popup: (popup as boolean | undefined) ?? true,\n transportReconnect: transportReconnect as boolean | undefined,\n transports: resolvedTransports,\n });\n\n return { coreMode: resolvedCoreMode, isLocalhost, popup: (popup as boolean | undefined) ?? true, TrezorConnect };\n}\n\nexport function normalizeTrezorExtendedPublicKey(xpub: string, chain: UTXOChain) {\n const targetVersions = getNetworkForChain(chain).bip32;\n const candidates = [\n targetVersions,\n ...EXTENDED_KEY_VERSION_CANDIDATES.filter(\n (versions) => versions.public !== targetVersions.public || versions.private !== targetVersions.private,\n ),\n ];\n let lastError: unknown;\n\n for (const versions of candidates) {\n try {\n const key = HDKey.fromExtendedKey(xpub, versions as Versions);\n if (!(key.publicKey && key.chainCode)) throw new Error(\"Extended key is missing public key data\");\n\n return new HDKey({\n chainCode: key.chainCode,\n depth: key.depth,\n index: key.index,\n parentFingerprint: key.parentFingerprint,\n publicKey: key.publicKey,\n versions: targetVersions,\n }).publicExtendedKey;\n } catch (error) {\n lastError = error;\n }\n }\n\n throw lastError instanceof Error ? lastError : new Error(\"Unable to parse Trezor extended public key\");\n}\n\nfunction tryNormalizeTrezorExtendedPublicKey(xpub: string | undefined, chain: UTXOChain) {\n if (!xpub) return undefined;\n\n try {\n return normalizeTrezorExtendedPublicKey(xpub, chain);\n } catch {\n return xpub;\n }\n}\n\nfunction decodeOpReturnData(script: Uint8Array): string | null {\n if (script.length < 2 || script[0] !== 0x6a) return null;\n const dataLen = script[1];\n if (dataLen === undefined || script.length < 2 + dataLen) return null;\n return Buffer.from(script.slice(2, 2 + dataLen)).toString(\"hex\");\n}\n\nfunction getScriptType(derivationPath: DerivationPathArray) {\n switch (derivationPath[0]) {\n case 84:\n return { input: \"SPENDWITNESS\", output: \"PAYTOWITNESS\" } as const;\n case 49:\n return { input: \"SPENDP2SHWITNESS\", output: \"PAYTOP2SHWITNESS\" } as const;\n case 44:\n return { input: \"SPENDADDRESS\", output: \"PAYTOADDRESS\" } as const;\n default:\n return null;\n }\n}\n\nfunction hardenDerivationPath(derivationPath: DerivationPathArray): number[] {\n return derivationPath.map((pathElement, index) =>\n index < 3 ? ((pathElement as number) | 0x80000000) >>> 0 : (pathElement as number),\n );\n}\n\nfunction isTrezorBip32Derivation(value: unknown): value is TrezorBip32Derivation {\n return (\n Array.isArray(value) &&\n value[0] instanceof Uint8Array &&\n typeof value[1] === \"object\" &&\n value[1] !== null &&\n typeof (value[1] as { fingerprint?: unknown }).fingerprint === \"number\" &&\n Array.isArray((value[1] as { path?: unknown }).path)\n );\n}\n\nfunction getFirstBip32Derivation(input: { bip32Derivation?: unknown }): TrezorBip32Derivation | undefined {\n if (!Array.isArray(input.bip32Derivation)) return undefined;\n const [firstDerivation] = input.bip32Derivation;\n\n return isTrezorBip32Derivation(firstDerivation) ? firstDerivation : undefined;\n}\n\nfunction getPrevoutAmount(input: {\n index?: number;\n nonWitnessUtxo?: { outputs?: Array<{ amount?: bigint | number }> };\n witnessUtxo?: { amount?: bigint | number };\n}) {\n if (input.witnessUtxo?.amount !== undefined) return input.witnessUtxo.amount.toString();\n\n const prevout = input.index !== undefined ? input.nonWitnessUtxo?.outputs?.[input.index] : undefined;\n if (prevout?.amount !== undefined) return prevout.amount.toString();\n\n return undefined;\n}\n\nexport function normalizeTrezorSignature(signatureHex: string, chain: Chain) {\n const signature = Buffer.from(signatureHex, \"hex\");\n const derLength = signature[1] !== undefined ? signature[1] + 2 : undefined;\n\n if (derLength !== undefined && signature.length === derLength) {\n return new Uint8Array([...signature, chain === Chain.BitcoinCash ? BCHSigHash.ALL : 0x01]);\n }\n\n return new Uint8Array(signature);\n}\n\nfunction buildPCZTInputsForTrezor(\n pczt: PCZT,\n address_n: number[],\n hexEncode: { encode: (data: Uint8Array) => string },\n) {\n const inputs = [];\n for (let i = 0; i < pczt.inputsLength; i++) {\n const input = pczt.getInput(i);\n inputs.push({\n address_n,\n amount: input.value.toString(),\n prev_hash: hexEncode.encode(new Uint8Array([...input.txid].reverse())),\n prev_index: input.index,\n script_type: \"SPENDADDRESS\" as const,\n });\n }\n return inputs;\n}\n\nasync function buildPCZTOutputsForTrezor(pczt: PCZT, address_n: number[], myAddress: string, chain: Chain) {\n const outputs = [];\n for (let i = 0; i < pczt.outputsLength; i++) {\n const output = pczt.getOutput(i);\n const script = output.scriptPubkey;\n\n if (output.value === 0n && script?.length > 0 && script[0] === 0x6a) {\n const opReturnData = decodeOpReturnData(script);\n if (opReturnData) {\n outputs.push({ amount: \"0\", op_return_data: opReturnData, script_type: \"PAYTOOPRETURN\" as const });\n continue;\n }\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Malformed OP_RETURN output cannot be signed\" },\n });\n }\n\n const outputAddress = await decodeOutputAddress(script);\n\n if (!outputAddress && output.value > 0n) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address from scriptPubkey\" },\n });\n }\n\n const isChangeAddress = outputAddress === myAddress;\n\n if (isChangeAddress) {\n outputs.push({ address_n, amount: output.value.toString(), script_type: \"PAYTOADDRESS\" as const });\n } else {\n outputs.push({ address: outputAddress, amount: output.value.toString(), script_type: \"PAYTOADDRESS\" as const });\n }\n }\n return outputs;\n}\n\nasync function decodeOutputAddress(script: Uint8Array): Promise<string | undefined> {\n try {\n const { OutScript, Address } = await import(\"@swapkit/utxo-signer\");\n const decoded = OutScript.decode(script);\n if (decoded.type === \"pkh\" || decoded.type === \"pk\") {\n return Address(NETWORKS.zcash).encode(decoded);\n }\n } catch {\n // ignore decode errors\n }\n return undefined;\n}\n\nasync function extractSignaturesFromSignedTx(signedTxHex: string, pczt: PCZT): Promise<PCZT> {\n const { ZcashTransaction: ZcashTx, Script } = await import(\"@swapkit/utxo-signer\");\n const signedTx = ZcashTx.fromHex(signedTxHex, { allowUnknownOutputs: true });\n const signedPczt = pczt.clone();\n\n for (let i = 0; i < signedTx.inputsLength; i++) {\n const signedInput = signedTx.getInput(i);\n const script = signedInput.script;\n if (script && script.length > 0) {\n const scriptParts = Script.decode(script);\n if (scriptParts.length >= 2) {\n signedPczt.addSignature(i, scriptParts[1] as Uint8Array, scriptParts[0] as Uint8Array);\n }\n }\n }\n return signedPczt;\n}\n\nfunction buildZcashTxInputsForTrezor(\n tx: ZcashTransaction,\n utxoInputs: UTXOType[],\n address_n: number[],\n hexEncode: { encode: (data: Uint8Array) => string },\n) {\n const inputs = [];\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n const utxoInfo = utxoInputs[i];\n inputs.push({\n address_n,\n amount: utxoInfo?.value?.toString() || \"0\",\n prev_hash: input.txid ? hexEncode.encode(new Uint8Array([...input.txid].reverse())) : \"\",\n prev_index: input.index ?? 0,\n script_type: \"SPENDADDRESS\" as const,\n });\n }\n return inputs;\n}\n\nfunction buildZcashTxOutputsForTrezor(tx: ZcashTransaction, address_n: number[], myAddress: string, chain: Chain) {\n const outputs = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const outputAddress = tx.getOutputAddress(i, NETWORKS.zcash);\n const script = output.script;\n\n if (output.amount === 0n && script?.length > 0 && script[0] === 0x6a) {\n const opReturnData = decodeOpReturnData(script);\n if (opReturnData) {\n outputs.push({ amount: \"0\", op_return_data: opReturnData, script_type: \"PAYTOOPRETURN\" as const });\n continue;\n }\n continue;\n }\n\n if (!outputAddress && (output.amount ?? 0n) > 0n) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address\" },\n });\n }\n\n const isChangeAddress = outputAddress === myAddress;\n const outputParam = isChangeAddress || !outputAddress ? { address_n } : { address: outputAddress };\n outputs.push({ ...outputParam, amount: output.amount?.toString() || \"0\", script_type: \"PAYTOADDRESS\" as const });\n }\n return outputs;\n}\n\nfunction buildUtxoOutputsForTrezor(\n tx: Transaction,\n network: BTCNetwork,\n address_n: number[],\n myAddress: string,\n memo: string,\n chain: Chain,\n scriptType: { input: string; output: string },\n toCashAddress: (addr: string) => string,\n stripPrefix: (addr: string) => string,\n) {\n const outputs: any[] = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const outputAddress = tx.getOutputAddress(i, network);\n\n if (!outputAddress) {\n const opReturnData = output.script ? decodeOpReturnData(output.script) : null;\n if (opReturnData !== null || memo) {\n outputs.push({\n amount: \"0\",\n op_return_data: opReturnData ?? Buffer.from(memo).toString(\"hex\"),\n script_type: \"PAYTOOPRETURN\",\n });\n continue;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address from scriptPubkey\" },\n });\n }\n\n if (output.amount === undefined) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Output amount is missing\" },\n });\n }\n\n const isBch = chain === Chain.BitcoinCash;\n const cashAddrWithPrefix = isBch ? toCashAddress(outputAddress) : outputAddress;\n const isChangeAddress = isBch\n ? stripPrefix(cashAddrWithPrefix) === stripPrefix(myAddress)\n : cashAddrWithPrefix === myAddress;\n\n outputs.push(\n isChangeAddress\n ? { address_n, amount: output.amount.toString(), script_type: scriptType.output }\n : { address: cashAddrWithPrefix, amount: output.amount.toString(), script_type: \"PAYTOADDRESS\" },\n );\n }\n return outputs;\n}\n\nfunction shouldUseTrezorPsbtSigner(chain: Chain) {\n return chain === Chain.Bitcoin || chain === Chain.Litecoin;\n}\n\nfunction shouldUseTrezorSerializedSigner(chain: Chain) {\n return chain === Chain.BitcoinCash || chain === Chain.Dogecoin;\n}\n\nasync function getTrezorWallet<T extends Chain>({\n address: providedAddress,\n chain,\n derivationPath,\n}: {\n address?: string;\n chain: T;\n derivationPath: DerivationPathArray;\n}) {\n switch (chain) {\n case Chain.Arbitrum:\n case Chain.Aurora:\n case Chain.Avalanche:\n case Chain.Base:\n case Chain.Berachain:\n case Chain.BinanceSmartChain:\n case Chain.Ethereum:\n case Chain.Gnosis:\n case Chain.Monad:\n case Chain.Optimism:\n case Chain.Polygon:\n case Chain.XLayer: {\n const { getProvider, getEvmToolboxAsync } = await import(\"@swapkit/toolboxes/evm\");\n const { getEVMSigner } = await import(\"./evmSigner\");\n\n const provider = await getProvider(chain);\n const signer = await getEVMSigner({ chain, derivationPath, provider });\n const address = await signer.getAddress();\n const toolbox = await getEvmToolboxAsync(chain, { provider, signer });\n\n return { ...toolbox, address };\n }\n\n case Chain.Zcash: {\n const { getUtxoToolbox } = await import(\"@swapkit/toolboxes/utxo\");\n\n const derivationPathStr = derivationPathToString(derivationPath);\n\n const getAddress = async () => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { success, payload } = await TrezorConnect.getAddress({ coin: \"zcash\", path: derivationPathStr });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_address\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n return payload.address;\n };\n\n const address = await getAddress();\n\n const signer = {\n getAddress: async () => address,\n\n signPCZT: async (pczt: PCZT): Promise<PCZT> => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const global = pczt.getGlobal();\n\n const inputs = buildPCZTInputsForTrezor(pczt, address_n, hexEncode);\n const outputs = await buildPCZTOutputsForTrezor(pczt, address_n, address, chain);\n\n const result = await TrezorConnect.signTransaction({\n branchId: global.consensusBranchId,\n coin: \"zcash\",\n expiry: global.expiryHeight,\n inputs,\n locktime: global.lockTime,\n outputs: outputs as any,\n overwintered: true,\n version: global.txVersion,\n versionGroupId: global.versionGroupId,\n });\n\n if (!result.success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n }\n\n return extractSignaturesFromSignedTx(result.payload.serializedTx, pczt);\n },\n\n signTransaction: async (tx: ZcashTransaction, utxoInputs: UTXOType[]) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n\n const inputs = buildZcashTxInputsForTrezor(tx, utxoInputs, address_n, hexEncode);\n const outputs = buildZcashTxOutputsForTrezor(tx, address_n, address, chain);\n\n const result = await TrezorConnect.signTransaction({\n branchId: ZcashConsensusBranchId.NU6,\n coin: \"zcash\",\n expiry: 0,\n inputs,\n locktime: 0,\n outputs: outputs as any,\n overwintered: true,\n version: 4,\n versionGroupId: ZcashVersionGroupId.SAPLING,\n });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n },\n };\n\n const toolbox = getUtxoToolbox(Chain.Zcash);\n\n const transfer = async (params: GenericTransferParams) => {\n if (!(address && params.recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];\n\n const { tx, inputs: txInputs } = await toolbox.createTransaction({\n ...params,\n feeRate,\n fetchTxHex: false,\n sender: address,\n });\n\n const txHex = await signer.signTransaction(tx, txInputs);\n const broadcastResult = await toolbox.broadcastTx(txHex);\n\n return broadcastResult;\n };\n\n const transferWithPCZT = async (params: GenericTransferParams) => {\n if (!(address && params.recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const { createPCZT, OutScript } = await import(\"@swapkit/utxo-signer\");\n const { hex: hexEncode } = await import(\"@scure/base\");\n const { getUtxoApi } = await import(\"@swapkit/toolboxes/utxo\");\n\n const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];\n\n const utxos = await getUtxoApi(Chain.Zcash).getUtxos({ address });\n\n const { tx, inputs: txInputs } = await toolbox.createTransaction({\n ...params,\n feeRate,\n fetchTxHex: false,\n sender: address,\n });\n\n const pczt = createPCZT();\n\n for (const utxoInput of txInputs) {\n const utxo = utxos.find((u) => u.hash === utxoInput.hash && u.index === utxoInput.index);\n const scriptPubkey = utxo?.witnessUtxo?.script\n ? new Uint8Array(utxo.witnessUtxo.script)\n : OutScript.encode({ hash: hexEncode.decode((utxoInput as any).address || \"\"), type: \"pkh\" });\n\n pczt.addInput({\n index: utxoInput.index,\n scriptPubkey,\n txid: hexEncode.decode(utxoInput.hash).reverse() as unknown as Uint8Array,\n value: BigInt(utxoInput.value),\n });\n }\n\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n pczt.addOutput({ scriptPubkey: output.script || new Uint8Array(), value: output.amount || 0n });\n }\n\n const signedPczt = await signer.signPCZT(pczt);\n signedPczt.finalizeAllInputs();\n const finalTx = signedPczt.extract();\n const broadcastResult = await toolbox.broadcastTx(finalTx.toHex());\n\n return broadcastResult;\n };\n\n return {\n ...toolbox,\n address,\n signPCZT: signer.signPCZT,\n signTransaction: signer.signTransaction,\n transfer,\n transferWithPCZT,\n };\n }\n\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n case Chain.Dash:\n case Chain.Dogecoin:\n case Chain.Litecoin: {\n const { toCashAddress, getUtxoToolbox, stripPrefix } = await import(\"@swapkit/toolboxes/utxo\");\n const utxoChain = chain as UTXOChain;\n const scriptType = getScriptType(derivationPath);\n\n if (!scriptType) {\n throw new SwapKitError({ errorKey: \"wallet_trezor_derivation_path_not_supported\", info: { derivationPath } });\n }\n\n const resolvedScriptType = scriptType;\n const coin = chain.toLowerCase();\n\n const getAddress = async (path: DerivationPathArray = derivationPath) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const pathString = derivationPathToString(path);\n const { success, payload } = await TrezorConnect.getAddress({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: pathString,\n showOnTrezor: false,\n });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_address\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n if (chain === Chain.BitcoinCash) {\n return stripPrefix(payload.address);\n }\n\n return payload.address;\n };\n\n const address = providedAddress ?? (await getAddress());\n const baseToolbox = getUtxoToolbox(chain);\n\n const signTransaction = async (tx: Transaction, inputs: UTXOType[], memo = \"\") => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n memo,\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const trezorInputs = inputs.map(({ hash, index, value }) => ({\n address_n,\n amount: value,\n prev_hash: hash,\n prev_index: index,\n script_type: resolvedScriptType.input,\n }));\n\n const result = await TrezorConnect.signTransaction({ coin, inputs: trezorInputs, outputs });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n };\n\n const signPsbtTransaction = async (tx: Transaction): Promise<Transaction> => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n let fallbackPublicKey: Uint8Array | undefined;\n\n async function getFallbackDerivation(): Promise<TrezorBip32Derivation> {\n if (!fallbackPublicKey) {\n const accountInfo = await getExtendedPublicKeyInfo();\n const accountKey = HDKey.fromExtendedKey(accountInfo.xpub, network.bip32);\n const leaf = accountKey.derive(`m/${Number(derivationPath[3] ?? 0)}/${Number(derivationPath[4] ?? 0)}`);\n\n if (!leaf.publicKey) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: \"Unable to derive Trezor leaf public key from account xpub\" },\n });\n }\n\n fallbackPublicKey = leaf.publicKey;\n }\n\n return [fallbackPublicKey, { fingerprint: 0, path: address_n }];\n }\n\n const signerPubkeys: Uint8Array[] = [];\n const trezorInputs = [];\n\n for (let inputIndex = 0; inputIndex < tx.inputsLength; inputIndex++) {\n const input = tx.getInput(inputIndex);\n const existingDerivation = getFirstBip32Derivation(input);\n const derivation = existingDerivation ?? (await getFallbackDerivation());\n const amount = getPrevoutAmount(input);\n\n if (!input.txid || input.index === undefined || !amount) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: `Input ${inputIndex} is missing prevout data required by Trezor` },\n });\n }\n\n signerPubkeys[inputIndex] = derivation[0];\n\n if (!existingDerivation) {\n tx.updateInput(inputIndex, { bip32Derivation: [derivation] });\n }\n\n trezorInputs.push({\n address_n: derivation[1].path,\n amount,\n prev_hash: hexEncode.encode(input.txid),\n prev_index: input.index,\n script_type: resolvedScriptType.input,\n ...(input.sequence !== undefined ? { sequence: input.sequence } : {}),\n });\n }\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n \"\",\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const result = await TrezorConnect.signTransaction({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n inputs: trezorInputs,\n locktime: tx.lockTime,\n outputs,\n version: tx.version,\n });\n\n if (!result.success) {\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n }\n\n result.payload.signatures.forEach((signatureHex, inputIndex) => {\n const pubkey = signerPubkeys[inputIndex];\n if (!(signatureHex && pubkey)) return;\n\n tx.updateInput(inputIndex, { partialSig: [[pubkey, normalizeTrezorSignature(signatureHex, chain)]] });\n });\n\n return tx;\n };\n\n const signSerializedTransaction = async (tx: Transaction) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n\n const trezorInputs = [];\n for (let inputIndex = 0; inputIndex < tx.inputsLength; inputIndex++) {\n const input = tx.getInput(inputIndex);\n const amount = getPrevoutAmount(input);\n\n if (!input.txid || input.index === undefined || !amount) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: `Input ${inputIndex} is missing prevout data required by Trezor` },\n });\n }\n\n trezorInputs.push({\n address_n,\n amount,\n prev_hash: hexEncode.encode(input.txid),\n prev_index: input.index,\n script_type: resolvedScriptType.input,\n ...(input.sequence !== undefined ? { sequence: input.sequence } : {}),\n });\n }\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n \"\",\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const result = await TrezorConnect.signTransaction({\n coin,\n inputs: trezorInputs,\n locktime: tx.lockTime,\n outputs,\n version: tx.version,\n });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n };\n\n const signTransactionWithMultipleInputs = async (\n tx: Transaction,\n inputs: Array<{ hash: string; index: number; value: number; derivationIndex: number; isChange: boolean }>,\n memo = \"\",\n ) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const network = getNetworkForChain(chain as UTXOChain);\n const baseAddressN = hardenDerivationPath(derivationPath.slice(0, 3) as DerivationPathArray);\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n baseAddressN,\n address,\n memo,\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const trezorInputs = inputs.map(({ hash, index: inputIndex, value, derivationIndex, isChange }) => {\n const changePath = isChange ? 1 : 0;\n const inputAddressN = [...baseAddressN, changePath, derivationIndex];\n return {\n address_n: inputAddressN,\n amount: value,\n prev_hash: hash,\n prev_index: inputIndex,\n script_type: resolvedScriptType.input,\n };\n });\n\n const result = await TrezorConnect.signTransaction({ coin, inputs: trezorInputs, outputs });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n };\n\n const transferFromMultipleAddresses = async ({\n utxos,\n recipient,\n assetValue,\n memo,\n feeRate,\n feeOptionKey,\n }: {\n utxos: Array<{\n hash: string;\n index: number;\n value: number;\n txHex?: string;\n derivationIndex: number;\n isChange: boolean;\n address: string;\n }>;\n recipient: string;\n assetValue: { getBaseValue: (unit: string) => number; chain: string };\n memo?: string;\n feeRate?: number;\n feeOptionKey?: (typeof FeeOption)[keyof typeof FeeOption];\n }) => {\n const toolbox = getUtxoToolbox(chain);\n const txFeeRate = feeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];\n\n const { tx, inputs: selectedInputs } = await toolbox.createTransaction({\n assetValue: assetValue as any,\n feeRate: txFeeRate,\n fetchTxHex: true,\n memo,\n recipient,\n sender: address,\n });\n\n const inputsWithDerivation = selectedInputs.map((input: { hash: string; index: number; value: number }) => {\n const utxoInfo = utxos.find((u) => u.hash === input.hash && u.index === input.index);\n return { ...input, derivationIndex: utxoInfo?.derivationIndex ?? 0, isChange: utxoInfo?.isChange ?? false };\n });\n\n const signedTxHex = await signTransactionWithMultipleInputs(tx as Transaction, inputsWithDerivation, memo);\n return toolbox.broadcastTx(signedTxHex);\n };\n\n const transfer = async ({\n recipient,\n feeOptionKey,\n feeRate: paramFeeRate,\n memo,\n ...rest\n }: GenericTransferParams) => {\n if (!(address && recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, memo, recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const toolbox = getUtxoToolbox(chain);\n\n const feeRate = paramFeeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];\n\n const createTxMethod = (toolbox as UTXOToolboxes[\"BTC\"]).createTransaction;\n\n const { tx, inputs } = await createTxMethod({\n ...rest,\n feeRate,\n fetchTxHex: true,\n memo,\n recipient,\n sender: address,\n });\n\n const signedTxHex = await signTransaction(tx, inputs, memo);\n const txHash = await toolbox.broadcastTx(signedTxHex);\n\n return txHash;\n };\n\n const toolbox = shouldUseTrezorPsbtSigner(chain)\n ? await getUtxoToolbox(utxoChain, {\n signer: { getAddress: async () => address, signTransaction: signPsbtTransaction },\n })\n : baseToolbox;\n\n const signAndBroadcastTransaction = shouldUseTrezorSerializedSigner(chain)\n ? async (tx: Transaction) => baseToolbox.broadcastTx(await signSerializedTransaction(tx))\n : toolbox.signAndBroadcastTransaction;\n\n async function getExtendedPublicKeyInfo({ accountIndex }: { accountIndex?: number } = {}) {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const path = derivationPathToString(resolvedAccountPath);\n const cacheKey = `${chain}:${path}`;\n const cached = trezorXpubCache.get(cacheKey);\n if (cached) return cached;\n\n const result = await TrezorConnect.getPublicKey({ coin, path });\n const { success, payload } = result;\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n const xpub = normalizeTrezorExtendedPublicKey(payload.xpub, utxoChain);\n const xpubSegwit = tryNormalizeTrezorExtendedPublicKey(payload.xpubSegwit, utxoChain);\n const info = {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n chainCode: payload.chainCode,\n depth: payload.depth,\n fingerprint: payload.fingerprint,\n path: payload.serializedPath,\n publicKey: payload.publicKey,\n xpub,\n xpubSegwit,\n };\n\n trezorXpubCache.set(cacheKey, info);\n return info;\n }\n\n function getExtendedPublicKey(params: { accountIndex?: number } = {}) {\n return getExtendedPublicKeyInfo(params);\n }\n\n async function deriveAddressAtIndex({\n accountIndex,\n index,\n change = false,\n }: {\n accountIndex?: number;\n index: number;\n change?: boolean;\n }) {\n assertDerivationIndex(\"index\", index);\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const fullPath = `${derivationPathToString(resolvedAccountPath)}/${Number(change)}/${index}`;\n\n const { success, payload } = await TrezorConnect.getAddress({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: fullPath,\n showOnTrezor: false,\n });\n\n if (!success) {\n return undefined;\n }\n\n let finalAddress = payload.address;\n if (chain === Chain.BitcoinCash) {\n const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);\n finalAddress = bchToolbox.stripPrefix(payload.address);\n }\n\n const pubKeyResult = await TrezorConnect.getPublicKey({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: fullPath,\n scriptType: resolvedScriptType.input,\n showOnTrezor: false,\n });\n const pubkey = pubKeyResult.success ? pubKeyResult.payload.publicKey : \"\";\n\n return {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n address: finalAddress,\n change,\n index,\n path: fullPath,\n pubkey,\n };\n }\n\n async function deriveAddressesBatch({\n accountIndex,\n count,\n startIndex = 0,\n change = false,\n }: {\n accountIndex?: number;\n count: number;\n startIndex?: number;\n change?: boolean;\n }) {\n assertDerivationIndex(\"count\", count);\n assertDerivationIndex(\"startIndex\", startIndex);\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const accountPath = derivationPathToString(resolvedAccountPath);\n\n const paths = Array.from({ length: count }, (_, i) => ({\n coin,\n path: `${accountPath}/${Number(change)}/${startIndex + i}`,\n showOnTrezor: false,\n }));\n\n const { success, payload } = await TrezorConnect.getAddress({ ...TREZOR_KEEP_SESSION_PARAMS, bundle: paths });\n\n if (!success || !Array.isArray(payload)) {\n return [];\n }\n\n const addresses = await Promise.all(\n payload.map(async (result, i) => {\n let finalAddress = result.address;\n if (chain === Chain.BitcoinCash) {\n const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);\n finalAddress = bchToolbox.stripPrefix(result.address);\n }\n\n return {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n address: finalAddress,\n change,\n index: startIndex + i,\n path: `${accountPath}/${Number(change)}/${startIndex + i}`,\n pubkey: \"\",\n };\n }),\n );\n\n return addresses;\n }\n\n const hdHelpers = createHDWalletHelpers({\n chain,\n deriveAddress: deriveAddressAtIndex,\n getBalance: toolbox.getBalance,\n getUtxos: (addr: string) => getUtxoApi(chain).getUtxos({ address: addr, fetchTxHex: true }),\n });\n\n return {\n ...toolbox,\n ...hdHelpers,\n address,\n deriveAddressAtIndex,\n deriveAddresses: deriveAddressesBatch,\n getExtendedPublicKey,\n getExtendedPublicKeyInfo,\n signAndBroadcastTransaction,\n signTransaction,\n signTransactionWithMultipleInputs,\n transfer,\n transferFromMultipleAddresses,\n };\n }\n\n default:\n throw new SwapKitError({ errorKey: \"wallet_chain_not_supported\", info: { chain, wallet: WalletOption.TREZOR } });\n }\n}\n\nexport async function getTrezorExtendedPublicKey(\n chain: Chain,\n derivationPath?: DerivationPathArray,\n { accountIndex }: { accountIndex?: number } = {},\n): Promise<HardwareExtendedPublicKeyInfo | undefined> {\n if (![Chain.BitcoinCash, Chain.Bitcoin, Chain.Dash, Chain.Dogecoin, Chain.Litecoin].includes(chain)) {\n throw new SwapKitError({ errorKey: \"wallet_chain_not_supported\", info: { chain, wallet: WalletOption.TREZOR } });\n }\n\n const { TrezorConnect } = await initTrezorConnect();\n const utxoChain = chain as UTXOChain;\n const resolvedDerivationPath = derivationPath ?? (NetworkDerivationPath[chain] as DerivationPathArray);\n const coin = chain.toLowerCase();\n\n const resolvedAccountPath = getUTXOAccountPath({\n accountIndex,\n chain: utxoChain,\n derivationPath: resolvedDerivationPath,\n });\n const path = derivationPathToString(resolvedAccountPath);\n const cacheKey = `${chain}:${path}`;\n const cached = trezorXpubCache.get(cacheKey);\n if (cached) return cached;\n\n const { success, payload } = await TrezorConnect.getPublicKey({ coin, path, showOnTrezor: true });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n const info = {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n chainCode: payload.chainCode,\n depth: payload.depth,\n fingerprint: payload.fingerprint,\n path: payload.serializedPath,\n publicKey: payload.publicKey,\n xpub: normalizeTrezorExtendedPublicKey(payload.xpub, utxoChain),\n xpubSegwit: tryNormalizeTrezorExtendedPublicKey(payload.xpubSegwit, utxoChain),\n };\n\n trezorXpubCache.set(cacheKey, info);\n return info;\n}\n\nexport const trezorWallet = createWallet({\n connect: ({ addChain, supportedChains, walletType }) =>\n async function connectTrezor(\n chains: Chain[],\n derivationPath: DerivationPathArray,\n { address }: ConnectTrezorOptions = {},\n ) {\n const [chain] = filterSupportedChains({ chains, supportedChains, walletType });\n if (!chain) {\n throw new SwapKitError({\n errorKey: \"wallet_chain_not_supported\",\n info: { chain, wallet: WalletOption.TREZOR },\n });\n }\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n\n const trezorConfig = SKConfig.get(\"integrations\").trezor as Record<string, unknown> | undefined;\n const {\n connectSrc,\n coreMode,\n debug,\n interactionTimeout,\n lazyLoad,\n pendingTransportEvent,\n popup,\n transportReconnect,\n transports,\n ...manifestConfig\n } = trezorConfig ?? {};\n const manifest = {\n ...manifestConfig,\n appName: getTrezorManifestValue(trezorConfig?.appName, DEFAULT_TREZOR_MANIFEST.appName),\n appUrl: getTrezorManifestValue(trezorConfig?.appUrl, getDefaultTrezorAppUrl()),\n email: getTrezorManifestValue(trezorConfig?.email, DEFAULT_TREZOR_MANIFEST.email),\n };\n const isLocalhost =\n typeof globalThis.location !== \"undefined\" && [\"localhost\", \"127.0.0.1\"].includes(globalThis.location.hostname);\n const resolvedCoreMode = normalizeTrezorCoreMode(coreMode) ?? \"popup\";\n const resolvedTransports = normalizeTrezorTransports(transports) ?? DEFAULT_TREZOR_TRANSPORTS;\n\n if (trezorSessionDispose) {\n await trezorSessionDispose;\n }\n\n if (isLocalhost) {\n await TrezorConnect.dispose();\n }\n\n await TrezorConnect.init({\n connectSrc: connectSrc as string | undefined,\n coreMode: resolvedCoreMode,\n debug: debug as boolean | undefined,\n interactionTimeout: interactionTimeout as number | undefined,\n lazyLoad: (lazyLoad as boolean | undefined) ?? false,\n manifest,\n pendingTransportEvent: pendingTransportEvent as boolean | undefined,\n popup: (popup as boolean | undefined) ?? true,\n transportReconnect: transportReconnect as boolean | undefined,\n transports: resolvedTransports,\n });\n\n const wallet = await getTrezorWallet({ address, chain, derivationPath });\n\n addChain({ ...wallet, chain, disconnect: disconnectTrezorSession, walletType });\n\n return true;\n },\n directSigningSupport: {\n [Chain.Arbitrum]: true,\n [Chain.Aurora]: true,\n [Chain.Avalanche]: true,\n [Chain.Base]: true,\n [Chain.Berachain]: true,\n [Chain.BinanceSmartChain]: true,\n [Chain.Bitcoin]: true,\n [Chain.BitcoinCash]: true,\n [Chain.Ethereum]: true,\n [Chain.Gnosis]: true,\n [Chain.Dogecoin]: true,\n [Chain.Litecoin]: true,\n [Chain.Monad]: true,\n [Chain.Optimism]: true,\n [Chain.Polygon]: true,\n [Chain.XLayer]: true,\n // DASH/ZEC: pending PSBT→TrezorConnect converter validation (V3 plan PR)\n },\n getExtendedPublicKey: getTrezorExtendedPublicKey,\n name: \"connectTrezor\",\n supportedChains: [\n Chain.Arbitrum,\n Chain.Aurora,\n Chain.Avalanche,\n Chain.Base,\n Chain.Berachain,\n Chain.BinanceSmartChain,\n Chain.Bitcoin,\n Chain.BitcoinCash,\n Chain.Dash,\n Chain.Dogecoin,\n Chain.Ethereum,\n Chain.Gnosis,\n Chain.Litecoin,\n Chain.Monad,\n Chain.Optimism,\n Chain.Polygon,\n Chain.XLayer,\n Chain.Zcash,\n ],\n walletType: WalletOption.TREZOR,\n});\n\nexport const TREZOR_SUPPORTED_CHAINS = getWalletSupportedChains(trezorWallet);\n"
5
+ "import { HDKey, type Versions } from \"@scure/bip32\";\nimport {\n Chain,\n type DerivationPathArray,\n derivationPathToString,\n FeeOption,\n filterSupportedChains,\n type GenericTransferParams,\n NetworkDerivationPath,\n SKConfig,\n SwapKitError,\n type UTXOChain,\n WalletOption,\n} from \"@swapkit/helpers\";\nimport {\n assertDerivationIndex,\n createHDWalletHelpers,\n getNetworkForChain,\n getUTXOAccountIndexFromPath,\n getUTXOAccountPath,\n getUtxoApi,\n type UTXOToolboxes,\n type UTXOType,\n} from \"@swapkit/toolboxes/utxo\";\nimport type { BTCNetwork, PCZT, Transaction, ZcashTransaction } from \"@swapkit/utxo-signer\";\nimport { BCHSigHash, NETWORKS, ZcashConsensusBranchId, ZcashVersionGroupId } from \"@swapkit/utxo-signer\";\nimport { createWallet, getWalletSupportedChains, type HardwareExtendedPublicKeyInfo } from \"@swapkit/wallet-core\";\n\ntype TrezorBip32Derivation = [Uint8Array, { fingerprint: number; path: number[] }];\ntype TrezorCoreMode = \"auto\" | \"iframe\" | \"popup\" | \"suite-desktop\" | \"suite-web\";\ntype TrezorTransport = \"BridgeTransport\" | \"WebUsbTransport\" | \"NodeUsbTransport\";\ntype ConnectTrezorOptions = { address?: string };\ntype TrezorExtendedPublicKeyInfo = {\n accountIndex: number;\n chainCode?: string;\n depth?: number;\n fingerprint?: number;\n path: string;\n publicKey?: string;\n xpub: string;\n xpubSegwit?: string;\n};\n\nconst TREZOR_CORE_MODES = new Set<TrezorCoreMode>([\"auto\", \"iframe\", \"popup\", \"suite-desktop\", \"suite-web\"]);\nconst TREZOR_TRANSPORTS = new Set<TrezorTransport>([\"BridgeTransport\", \"WebUsbTransport\", \"NodeUsbTransport\"]);\nconst DEFAULT_TREZOR_MANIFEST = { appName: \"SwapKit\", appUrl: \"https://swapkit.dev\", email: \"support@swapkit.dev\" };\nconst DEFAULT_TREZOR_TRANSPORTS = [\"WebUsbTransport\" as const];\nconst TREZOR_KEEP_SESSION_PARAMS = { keepSession: true } as const;\nconst trezorXpubCache = new Map<string, TrezorExtendedPublicKeyInfo>();\nlet trezorSessionDispose: Promise<void> | undefined;\nconst EXTENDED_KEY_VERSION_CANDIDATES = [\n NETWORKS.bitcoin.bip32,\n NETWORKS.bitcoinCash.bip32,\n NETWORKS.dash.bip32,\n NETWORKS.dogecoin.bip32,\n NETWORKS.litecoin.bip32,\n];\n\nasync function disconnectTrezorSession() {\n trezorXpubCache.clear();\n\n const dispose = (async () => {\n try {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n await TrezorConnect.dispose();\n } catch {\n // Ignore stale or already-disposed sessions.\n }\n })();\n\n trezorSessionDispose = dispose;\n await dispose;\n\n if (trezorSessionDispose === dispose) {\n trezorSessionDispose = undefined;\n }\n}\n\nfunction normalizeTrezorCoreMode(coreMode: unknown): TrezorCoreMode | undefined {\n return typeof coreMode === \"string\" && TREZOR_CORE_MODES.has(coreMode as TrezorCoreMode)\n ? (coreMode as TrezorCoreMode)\n : undefined;\n}\n\nfunction normalizeTrezorTransports(transports: unknown): TrezorTransport[] | undefined {\n if (!Array.isArray(transports)) return undefined;\n\n const normalized = transports.filter(\n (transport): transport is TrezorTransport =>\n typeof transport === \"string\" && TREZOR_TRANSPORTS.has(transport as TrezorTransport),\n );\n\n return normalized.length > 0 ? normalized : undefined;\n}\n\nfunction getTrezorManifestValue(value: unknown, fallback: string) {\n return typeof value === \"string\" && value.trim() ? value : fallback;\n}\n\nfunction getDefaultTrezorAppUrl() {\n return typeof globalThis.location !== \"undefined\" && globalThis.location.origin\n ? globalThis.location.origin\n : DEFAULT_TREZOR_MANIFEST.appUrl;\n}\n\nasync function initTrezorConnect() {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n\n const trezorConfig = SKConfig.get(\"integrations\").trezor as Record<string, unknown> | undefined;\n const {\n connectSrc,\n coreMode,\n debug,\n interactionTimeout,\n lazyLoad,\n pendingTransportEvent,\n popup,\n transportReconnect,\n transports,\n ...manifestConfig\n } = trezorConfig ?? {};\n const manifest = {\n ...manifestConfig,\n appName: getTrezorManifestValue(trezorConfig?.appName, DEFAULT_TREZOR_MANIFEST.appName),\n appUrl: getTrezorManifestValue(trezorConfig?.appUrl, getDefaultTrezorAppUrl()),\n email: getTrezorManifestValue(trezorConfig?.email, DEFAULT_TREZOR_MANIFEST.email),\n };\n const isLocalhost =\n typeof globalThis.location !== \"undefined\" && [\"localhost\", \"127.0.0.1\"].includes(globalThis.location.hostname);\n const resolvedCoreMode = normalizeTrezorCoreMode(coreMode) ?? \"popup\";\n const resolvedTransports = normalizeTrezorTransports(transports) ?? DEFAULT_TREZOR_TRANSPORTS;\n\n if (trezorSessionDispose) {\n await trezorSessionDispose;\n }\n\n if (isLocalhost) {\n await TrezorConnect.dispose();\n }\n\n await TrezorConnect.init({\n connectSrc: connectSrc as string | undefined,\n coreMode: resolvedCoreMode,\n debug: debug as boolean | undefined,\n interactionTimeout: interactionTimeout as number | undefined,\n lazyLoad: (lazyLoad as boolean | undefined) ?? false,\n manifest,\n pendingTransportEvent: pendingTransportEvent as boolean | undefined,\n popup: (popup as boolean | undefined) ?? true,\n transportReconnect: transportReconnect as boolean | undefined,\n transports: resolvedTransports,\n });\n\n return { coreMode: resolvedCoreMode, isLocalhost, popup: (popup as boolean | undefined) ?? true, TrezorConnect };\n}\n\nexport function normalizeTrezorExtendedPublicKey(xpub: string, chain: UTXOChain) {\n const targetVersions = getNetworkForChain(chain).bip32;\n const candidates = [\n targetVersions,\n ...EXTENDED_KEY_VERSION_CANDIDATES.filter(\n (versions) => versions.public !== targetVersions.public || versions.private !== targetVersions.private,\n ),\n ];\n let lastError: unknown;\n\n for (const versions of candidates) {\n try {\n const key = HDKey.fromExtendedKey(xpub, versions as Versions);\n if (!(key.publicKey && key.chainCode)) throw new Error(\"Extended key is missing public key data\");\n\n return new HDKey({\n chainCode: key.chainCode,\n depth: key.depth,\n index: key.index,\n parentFingerprint: key.parentFingerprint,\n publicKey: key.publicKey,\n versions: targetVersions,\n }).publicExtendedKey;\n } catch (error) {\n lastError = error;\n }\n }\n\n throw lastError instanceof Error ? lastError : new Error(\"Unable to parse Trezor extended public key\");\n}\n\nfunction tryNormalizeTrezorExtendedPublicKey(xpub: string | undefined, chain: UTXOChain) {\n if (!xpub) return undefined;\n\n try {\n return normalizeTrezorExtendedPublicKey(xpub, chain);\n } catch {\n return xpub;\n }\n}\n\nfunction decodeOpReturnData(script: Uint8Array): string | null {\n if (script.length < 2 || script[0] !== 0x6a) return null;\n const dataLen = script[1];\n if (dataLen === undefined || script.length < 2 + dataLen) return null;\n return Buffer.from(script.slice(2, 2 + dataLen)).toString(\"hex\");\n}\n\nfunction getScriptType(derivationPath: DerivationPathArray) {\n switch (derivationPath[0]) {\n case 84:\n return { input: \"SPENDWITNESS\", output: \"PAYTOWITNESS\" } as const;\n case 49:\n return { input: \"SPENDP2SHWITNESS\", output: \"PAYTOP2SHWITNESS\" } as const;\n case 44:\n return { input: \"SPENDADDRESS\", output: \"PAYTOADDRESS\" } as const;\n default:\n return null;\n }\n}\n\nfunction hardenDerivationPath(derivationPath: DerivationPathArray): number[] {\n return derivationPath.map((pathElement, index) =>\n index < 3 ? ((pathElement as number) | 0x80000000) >>> 0 : (pathElement as number),\n );\n}\n\nfunction isTrezorBip32Derivation(value: unknown): value is TrezorBip32Derivation {\n return (\n Array.isArray(value) &&\n value[0] instanceof Uint8Array &&\n typeof value[1] === \"object\" &&\n value[1] !== null &&\n typeof (value[1] as { fingerprint?: unknown }).fingerprint === \"number\" &&\n Array.isArray((value[1] as { path?: unknown }).path)\n );\n}\n\nfunction getFirstBip32Derivation(input: { bip32Derivation?: unknown }): TrezorBip32Derivation | undefined {\n if (!Array.isArray(input.bip32Derivation)) return undefined;\n const [firstDerivation] = input.bip32Derivation;\n\n return isTrezorBip32Derivation(firstDerivation) ? firstDerivation : undefined;\n}\n\nfunction getPrevoutAmount(input: {\n index?: number;\n nonWitnessUtxo?: { outputs?: Array<{ amount?: bigint | number }> };\n witnessUtxo?: { amount?: bigint | number };\n}) {\n if (input.witnessUtxo?.amount !== undefined) return input.witnessUtxo.amount.toString();\n\n const prevout = input.index !== undefined ? input.nonWitnessUtxo?.outputs?.[input.index] : undefined;\n if (prevout?.amount !== undefined) return prevout.amount.toString();\n\n return undefined;\n}\n\nexport function normalizeTrezorSignature(signatureHex: string, chain: Chain) {\n const signature = Buffer.from(signatureHex, \"hex\");\n const derLength = signature[1] !== undefined ? signature[1] + 2 : undefined;\n\n if (derLength !== undefined && signature.length === derLength) {\n return new Uint8Array([...signature, chain === Chain.BitcoinCash ? BCHSigHash.ALL : 0x01]);\n }\n\n return new Uint8Array(signature);\n}\n\nfunction buildPCZTInputsForTrezor(\n pczt: PCZT,\n address_n: number[],\n hexEncode: { encode: (data: Uint8Array) => string },\n) {\n const inputs = [];\n for (let i = 0; i < pczt.inputsLength; i++) {\n const input = pczt.getInput(i);\n inputs.push({\n address_n,\n amount: input.value.toString(),\n prev_hash: hexEncode.encode(new Uint8Array([...input.txid].reverse())),\n prev_index: input.index,\n script_type: \"SPENDADDRESS\" as const,\n });\n }\n return inputs;\n}\n\nasync function buildPCZTOutputsForTrezor(pczt: PCZT, address_n: number[], myAddress: string, chain: Chain) {\n const outputs = [];\n for (let i = 0; i < pczt.outputsLength; i++) {\n const output = pczt.getOutput(i);\n const script = output.scriptPubkey;\n\n if (output.value === 0n && script?.length > 0 && script[0] === 0x6a) {\n const opReturnData = decodeOpReturnData(script);\n if (opReturnData) {\n outputs.push({ amount: \"0\", op_return_data: opReturnData, script_type: \"PAYTOOPRETURN\" as const });\n continue;\n }\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Malformed OP_RETURN output cannot be signed\" },\n });\n }\n\n const outputAddress = await decodeOutputAddress(script);\n\n if (!outputAddress && output.value > 0n) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address from scriptPubkey\" },\n });\n }\n\n const isChangeAddress = outputAddress === myAddress;\n\n if (isChangeAddress) {\n outputs.push({ address_n, amount: output.value.toString(), script_type: \"PAYTOADDRESS\" as const });\n } else {\n outputs.push({ address: outputAddress, amount: output.value.toString(), script_type: \"PAYTOADDRESS\" as const });\n }\n }\n return outputs;\n}\n\nasync function decodeOutputAddress(script: Uint8Array): Promise<string | undefined> {\n try {\n const { OutScript, Address } = await import(\"@swapkit/utxo-signer\");\n const decoded = OutScript.decode(script);\n if (decoded.type === \"pkh\" || decoded.type === \"pk\") {\n return Address(NETWORKS.zcash).encode(decoded);\n }\n } catch {\n // ignore decode errors\n }\n return undefined;\n}\n\nasync function extractSignaturesFromSignedTx(signedTxHex: string, pczt: PCZT): Promise<PCZT> {\n const { ZcashTransaction: ZcashTx, Script } = await import(\"@swapkit/utxo-signer\");\n const signedTx = ZcashTx.fromHex(signedTxHex, { allowUnknownOutputs: true });\n const signedPczt = pczt.clone();\n\n for (let i = 0; i < signedTx.inputsLength; i++) {\n const signedInput = signedTx.getInput(i);\n const script = signedInput.script;\n if (script && script.length > 0) {\n const scriptParts = Script.decode(script);\n if (scriptParts.length >= 2) {\n signedPczt.addSignature(i, scriptParts[1] as Uint8Array, scriptParts[0] as Uint8Array);\n }\n }\n }\n return signedPczt;\n}\n\nfunction buildZcashTxInputsForTrezor(\n tx: ZcashTransaction,\n utxoInputs: UTXOType[],\n address_n: number[],\n hexEncode: { encode: (data: Uint8Array) => string },\n) {\n const inputs = [];\n for (let i = 0; i < tx.inputsLength; i++) {\n const input = tx.getInput(i);\n const utxoInfo = utxoInputs[i];\n inputs.push({\n address_n,\n amount: utxoInfo?.value?.toString() || \"0\",\n prev_hash: input.txid ? hexEncode.encode(new Uint8Array([...input.txid].reverse())) : \"\",\n prev_index: input.index ?? 0,\n script_type: \"SPENDADDRESS\" as const,\n });\n }\n return inputs;\n}\n\nfunction buildZcashTxOutputsForTrezor(tx: ZcashTransaction, address_n: number[], myAddress: string, chain: Chain) {\n const outputs = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const outputAddress = tx.getOutputAddress(i, NETWORKS.zcash);\n const script = output.script;\n\n if (output.amount === 0n && script?.length > 0 && script[0] === 0x6a) {\n const opReturnData = decodeOpReturnData(script);\n if (opReturnData) {\n outputs.push({ amount: \"0\", op_return_data: opReturnData, script_type: \"PAYTOOPRETURN\" as const });\n continue;\n }\n continue;\n }\n\n if (!outputAddress && (output.amount ?? 0n) > 0n) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address\" },\n });\n }\n\n const isChangeAddress = outputAddress === myAddress;\n const outputParam = isChangeAddress || !outputAddress ? { address_n } : { address: outputAddress };\n outputs.push({ ...outputParam, amount: output.amount?.toString() || \"0\", script_type: \"PAYTOADDRESS\" as const });\n }\n return outputs;\n}\n\nfunction buildUtxoOutputsForTrezor(\n tx: Transaction,\n network: BTCNetwork,\n address_n: number[],\n myAddress: string,\n memo: string,\n chain: Chain,\n scriptType: { input: string; output: string },\n toCashAddress: (addr: string) => string,\n stripPrefix: (addr: string) => string,\n) {\n const outputs: any[] = [];\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n const outputAddress = tx.getOutputAddress(i, network);\n\n if (!outputAddress) {\n const opReturnData = output.script ? decodeOpReturnData(output.script) : null;\n if (opReturnData !== null || memo) {\n outputs.push({\n amount: \"0\",\n op_return_data: opReturnData ?? Buffer.from(memo).toString(\"hex\"),\n script_type: \"PAYTOOPRETURN\",\n });\n continue;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Unable to decode output address from scriptPubkey\" },\n });\n }\n\n if (output.amount === undefined) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: \"Output amount is missing\" },\n });\n }\n\n const isBch = chain === Chain.BitcoinCash;\n const cashAddrWithPrefix = isBch ? toCashAddress(outputAddress) : outputAddress;\n const isChangeAddress = isBch\n ? stripPrefix(cashAddrWithPrefix) === stripPrefix(myAddress)\n : cashAddrWithPrefix === myAddress;\n\n outputs.push(\n isChangeAddress\n ? { address_n, amount: output.amount.toString(), script_type: scriptType.output }\n : { address: cashAddrWithPrefix, amount: output.amount.toString(), script_type: \"PAYTOADDRESS\" },\n );\n }\n return outputs;\n}\n\nfunction shouldUseTrezorPsbtSigner(chain: Chain) {\n return chain === Chain.Bitcoin || chain === Chain.Litecoin;\n}\n\nfunction shouldUseTrezorSerializedSigner(chain: Chain) {\n return chain === Chain.BitcoinCash || chain === Chain.Dash || chain === Chain.Dogecoin;\n}\n\nasync function getTrezorWallet<T extends Chain>({\n address: providedAddress,\n chain,\n derivationPath,\n}: {\n address?: string;\n chain: T;\n derivationPath: DerivationPathArray;\n}) {\n switch (chain) {\n case Chain.Arbitrum:\n case Chain.Aurora:\n case Chain.Avalanche:\n case Chain.Base:\n case Chain.Berachain:\n case Chain.BinanceSmartChain:\n case Chain.Ethereum:\n case Chain.Gnosis:\n case Chain.Monad:\n case Chain.Optimism:\n case Chain.Polygon:\n case Chain.XLayer: {\n const { getProvider, getEvmToolboxAsync } = await import(\"@swapkit/toolboxes/evm\");\n const { getEVMSigner } = await import(\"./evmSigner\");\n\n const provider = await getProvider(chain);\n const signer = await getEVMSigner({ chain, derivationPath, provider });\n const address = await signer.getAddress();\n const toolbox = await getEvmToolboxAsync(chain, { provider, signer });\n\n return { ...toolbox, address };\n }\n\n case Chain.Zcash: {\n const { getUtxoToolbox } = await import(\"@swapkit/toolboxes/utxo\");\n\n const derivationPathStr = derivationPathToString(derivationPath);\n\n const getAddress = async () => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { success, payload } = await TrezorConnect.getAddress({ coin: \"zcash\", path: derivationPathStr });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_address\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n return payload.address;\n };\n\n const address = await getAddress();\n\n const signer = {\n getAddress: async () => address,\n\n signPCZT: async (pczt: PCZT): Promise<PCZT> => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const global = pczt.getGlobal();\n\n const inputs = buildPCZTInputsForTrezor(pczt, address_n, hexEncode);\n const outputs = await buildPCZTOutputsForTrezor(pczt, address_n, address, chain);\n\n const result = await TrezorConnect.signTransaction({\n branchId: global.consensusBranchId,\n coin: \"zcash\",\n expiry: global.expiryHeight,\n inputs,\n locktime: global.lockTime,\n outputs: outputs as any,\n overwintered: true,\n version: global.txVersion,\n versionGroupId: global.versionGroupId,\n });\n\n if (!result.success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n }\n\n return extractSignaturesFromSignedTx(result.payload.serializedTx, pczt);\n },\n\n signTransaction: async (tx: ZcashTransaction, utxoInputs: UTXOType[]) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n\n const inputs = buildZcashTxInputsForTrezor(tx, utxoInputs, address_n, hexEncode);\n const outputs = buildZcashTxOutputsForTrezor(tx, address_n, address, chain);\n\n const result = await TrezorConnect.signTransaction({\n branchId: ZcashConsensusBranchId.NU6,\n coin: \"zcash\",\n expiry: 0,\n inputs,\n locktime: 0,\n outputs: outputs as any,\n overwintered: true,\n version: 4,\n versionGroupId: ZcashVersionGroupId.SAPLING,\n });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n },\n };\n\n const toolbox = getUtxoToolbox(Chain.Zcash);\n\n const transfer = async (params: GenericTransferParams) => {\n if (!(address && params.recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];\n\n const { tx, inputs: txInputs } = await toolbox.createTransaction({\n ...params,\n feeRate,\n fetchTxHex: false,\n sender: address,\n });\n\n const txHex = await signer.signTransaction(tx, txInputs);\n const broadcastResult = await toolbox.broadcastTx(txHex);\n\n return broadcastResult;\n };\n\n const transferWithPCZT = async (params: GenericTransferParams) => {\n if (!(address && params.recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, recipient: params.recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const { createPCZT, OutScript } = await import(\"@swapkit/utxo-signer\");\n const { hex: hexEncode } = await import(\"@scure/base\");\n const { getUtxoApi } = await import(\"@swapkit/toolboxes/utxo\");\n\n const feeRate = params.feeRate || (await toolbox.getFeeRates())[params.feeOptionKey || FeeOption.Fast];\n\n const utxos = await getUtxoApi(Chain.Zcash).getUtxos({ address });\n\n const { tx, inputs: txInputs } = await toolbox.createTransaction({\n ...params,\n feeRate,\n fetchTxHex: false,\n sender: address,\n });\n\n const pczt = createPCZT();\n\n for (const utxoInput of txInputs) {\n const utxo = utxos.find((u) => u.hash === utxoInput.hash && u.index === utxoInput.index);\n const scriptPubkey = utxo?.witnessUtxo?.script\n ? new Uint8Array(utxo.witnessUtxo.script)\n : OutScript.encode({ hash: hexEncode.decode((utxoInput as any).address || \"\"), type: \"pkh\" });\n\n pczt.addInput({\n index: utxoInput.index,\n scriptPubkey,\n txid: hexEncode.decode(utxoInput.hash).reverse() as unknown as Uint8Array,\n value: BigInt(utxoInput.value),\n });\n }\n\n for (let i = 0; i < tx.outputsLength; i++) {\n const output = tx.getOutput(i);\n pczt.addOutput({ scriptPubkey: output.script || new Uint8Array(), value: output.amount || 0n });\n }\n\n const signedPczt = await signer.signPCZT(pczt);\n signedPczt.finalizeAllInputs();\n const finalTx = signedPczt.extract();\n const broadcastResult = await toolbox.broadcastTx(finalTx.toHex());\n\n return broadcastResult;\n };\n\n return {\n ...toolbox,\n address,\n signPCZT: signer.signPCZT,\n signTransaction: signer.signTransaction,\n transfer,\n transferWithPCZT,\n };\n }\n\n case Chain.Bitcoin:\n case Chain.BitcoinCash:\n case Chain.Dash:\n case Chain.Dogecoin:\n case Chain.Litecoin: {\n const { toCashAddress, getUtxoToolbox, stripPrefix } = await import(\"@swapkit/toolboxes/utxo\");\n const utxoChain = chain as UTXOChain;\n const scriptType = getScriptType(derivationPath);\n\n if (!scriptType) {\n throw new SwapKitError({ errorKey: \"wallet_trezor_derivation_path_not_supported\", info: { derivationPath } });\n }\n\n const resolvedScriptType = scriptType;\n const coin = chain.toLowerCase();\n\n const getAddress = async (path: DerivationPathArray = derivationPath) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const pathString = derivationPathToString(path);\n const { success, payload } = await TrezorConnect.getAddress({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: pathString,\n showOnTrezor: false,\n });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_address\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n if (chain === Chain.BitcoinCash) {\n return stripPrefix(payload.address);\n }\n\n return payload.address;\n };\n\n const address = providedAddress ?? (await getAddress());\n const baseToolbox = getUtxoToolbox(chain);\n\n const signTransaction = async (tx: Transaction, inputs: UTXOType[], memo = \"\") => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n memo,\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const trezorInputs = inputs.map(({ hash, index, value }) => ({\n address_n,\n amount: value,\n prev_hash: hash,\n prev_index: index,\n script_type: resolvedScriptType.input,\n }));\n\n const result = await TrezorConnect.signTransaction({ coin, inputs: trezorInputs, outputs });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n };\n\n const signPsbtTransaction = async (tx: Transaction): Promise<Transaction> => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n let fallbackPublicKey: Uint8Array | undefined;\n\n async function getFallbackDerivation(): Promise<TrezorBip32Derivation> {\n if (!fallbackPublicKey) {\n const accountInfo = await getExtendedPublicKeyInfo();\n const accountKey = HDKey.fromExtendedKey(accountInfo.xpub, network.bip32);\n const leaf = accountKey.derive(`m/${Number(derivationPath[3] ?? 0)}/${Number(derivationPath[4] ?? 0)}`);\n\n if (!leaf.publicKey) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: \"Unable to derive Trezor leaf public key from account xpub\" },\n });\n }\n\n fallbackPublicKey = leaf.publicKey;\n }\n\n return [fallbackPublicKey, { fingerprint: 0, path: address_n }];\n }\n\n const signerPubkeys: Uint8Array[] = [];\n const trezorInputs = [];\n\n for (let inputIndex = 0; inputIndex < tx.inputsLength; inputIndex++) {\n const input = tx.getInput(inputIndex);\n const existingDerivation = getFirstBip32Derivation(input);\n const derivation = existingDerivation ?? (await getFallbackDerivation());\n const amount = getPrevoutAmount(input);\n\n if (!input.txid || input.index === undefined || !amount) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: `Input ${inputIndex} is missing prevout data required by Trezor` },\n });\n }\n\n signerPubkeys[inputIndex] = derivation[0];\n\n if (!existingDerivation) {\n tx.updateInput(inputIndex, { bip32Derivation: [derivation] });\n }\n\n trezorInputs.push({\n address_n: derivation[1].path,\n amount,\n prev_hash: hexEncode.encode(input.txid),\n prev_index: input.index,\n script_type: resolvedScriptType.input,\n ...(input.sequence !== undefined ? { sequence: input.sequence } : {}),\n });\n }\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n \"\",\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const result = await TrezorConnect.signTransaction({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n inputs: trezorInputs,\n locktime: tx.lockTime,\n outputs,\n version: tx.version,\n });\n\n if (!result.success) {\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n }\n\n result.payload.signatures.forEach((signatureHex, inputIndex) => {\n const pubkey = signerPubkeys[inputIndex];\n if (!(signatureHex && pubkey)) return;\n\n tx.updateInput(inputIndex, { partialSig: [[pubkey, normalizeTrezorSignature(signatureHex, chain)]] });\n });\n\n return tx;\n };\n\n const signSerializedTransaction = async (tx: Transaction) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const { hex: hexEncode } = await import(\"@scure/base\");\n const address_n = hardenDerivationPath(derivationPath);\n const network = getNetworkForChain(chain as UTXOChain);\n\n const trezorInputs = [];\n for (let inputIndex = 0; inputIndex < tx.inputsLength; inputIndex++) {\n const input = tx.getInput(inputIndex);\n const amount = getPrevoutAmount(input);\n\n if (!input.txid || input.index === undefined || !amount) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: `Input ${inputIndex} is missing prevout data required by Trezor` },\n });\n }\n\n trezorInputs.push({\n address_n,\n amount,\n prev_hash: hexEncode.encode(input.txid),\n prev_index: input.index,\n script_type: resolvedScriptType.input,\n ...(input.sequence !== undefined ? { sequence: input.sequence } : {}),\n });\n }\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n address_n,\n address,\n \"\",\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const result = await TrezorConnect.signTransaction({\n coin,\n inputs: trezorInputs,\n locktime: tx.lockTime,\n outputs,\n version: tx.version,\n });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n const payload = result.payload as { error?: string; code?: string };\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, code: payload?.code ?? \"unknown\", error: payload?.error ?? \"unknown\", payload },\n });\n };\n\n const signTransactionWithMultipleInputs = async (\n tx: Transaction,\n inputs: Array<{ hash: string; index: number; value: number; derivationIndex: number; isChange: boolean }>,\n memo = \"\",\n ) => {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const network = getNetworkForChain(chain as UTXOChain);\n const baseAddressN = hardenDerivationPath(derivationPath.slice(0, 3) as DerivationPathArray);\n\n const outputs = buildUtxoOutputsForTrezor(\n tx,\n network,\n baseAddressN,\n address,\n memo,\n chain,\n resolvedScriptType,\n toCashAddress,\n stripPrefix,\n );\n\n const trezorInputs = inputs.map(({ hash, index: inputIndex, value, derivationIndex, isChange }) => {\n const changePath = isChange ? 1 : 0;\n const inputAddressN = [...baseAddressN, changePath, derivationIndex];\n return {\n address_n: inputAddressN,\n amount: value,\n prev_hash: hash,\n prev_index: inputIndex,\n script_type: resolvedScriptType.input,\n };\n });\n\n const result = await TrezorConnect.signTransaction({ coin, inputs: trezorInputs, outputs });\n\n if (result.success) {\n return result.payload.serializedTx;\n }\n\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_sign_transaction\",\n info: { chain, error: (result.payload as { error: string; code?: string }).error },\n });\n };\n\n const transferFromMultipleAddresses = async ({\n utxos,\n recipient,\n assetValue,\n memo,\n feeRate,\n feeOptionKey,\n }: {\n utxos: Array<{\n hash: string;\n index: number;\n value: number;\n txHex?: string;\n derivationIndex: number;\n isChange: boolean;\n address: string;\n }>;\n recipient: string;\n assetValue: { getBaseValue: (unit: string) => number; chain: string };\n memo?: string;\n feeRate?: number;\n feeOptionKey?: (typeof FeeOption)[keyof typeof FeeOption];\n }) => {\n const toolbox = getUtxoToolbox(chain);\n const txFeeRate = feeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];\n\n const { tx, inputs: selectedInputs } = await toolbox.createTransaction({\n assetValue: assetValue as any,\n feeRate: txFeeRate,\n fetchTxHex: true,\n memo,\n recipient,\n sender: address,\n });\n\n const inputsWithDerivation = selectedInputs.map((input: { hash: string; index: number; value: number }) => {\n const utxoInfo = utxos.find((u) => u.hash === input.hash && u.index === input.index);\n return { ...input, derivationIndex: utxoInfo?.derivationIndex ?? 0, isChange: utxoInfo?.isChange ?? false };\n });\n\n const signedTxHex = await signTransactionWithMultipleInputs(tx as Transaction, inputsWithDerivation, memo);\n return toolbox.broadcastTx(signedTxHex);\n };\n\n const transfer = async ({\n recipient,\n feeOptionKey,\n feeRate: paramFeeRate,\n memo,\n ...rest\n }: GenericTransferParams) => {\n if (!(address && recipient)) {\n throw new SwapKitError({\n errorKey: \"wallet_missing_params\",\n info: { address, memo, recipient, wallet: WalletOption.TREZOR },\n });\n }\n\n const toolbox = getUtxoToolbox(chain);\n\n const feeRate = paramFeeRate || (await toolbox.getFeeRates())[feeOptionKey || FeeOption.Fast];\n\n const createTxMethod = (toolbox as UTXOToolboxes[\"BTC\"]).createTransaction;\n\n const { tx, inputs } = await createTxMethod({\n ...rest,\n feeRate,\n fetchTxHex: true,\n memo,\n recipient,\n sender: address,\n });\n\n const signedTxHex = await signTransaction(tx, inputs, memo);\n const txHash = await toolbox.broadcastTx(signedTxHex);\n\n return txHash;\n };\n\n const toolbox = shouldUseTrezorPsbtSigner(chain)\n ? await getUtxoToolbox(utxoChain, {\n signer: { getAddress: async () => address, signTransaction: signPsbtTransaction },\n })\n : baseToolbox;\n\n const signAndBroadcastTransaction = shouldUseTrezorSerializedSigner(chain)\n ? async (tx: Transaction) => baseToolbox.broadcastTx(await signSerializedTransaction(tx))\n : toolbox.signAndBroadcastTransaction;\n\n async function getExtendedPublicKeyInfo({ accountIndex }: { accountIndex?: number } = {}) {\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const path = derivationPathToString(resolvedAccountPath);\n const cacheKey = `${chain}:${path}`;\n const cached = trezorXpubCache.get(cacheKey);\n if (cached) return cached;\n\n const result = await TrezorConnect.getPublicKey({ coin, path });\n const { success, payload } = result;\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n const xpub = normalizeTrezorExtendedPublicKey(payload.xpub, utxoChain);\n const xpubSegwit = tryNormalizeTrezorExtendedPublicKey(payload.xpubSegwit, utxoChain);\n const info = {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n chainCode: payload.chainCode,\n depth: payload.depth,\n fingerprint: payload.fingerprint,\n path: payload.serializedPath,\n publicKey: payload.publicKey,\n xpub,\n xpubSegwit,\n };\n\n trezorXpubCache.set(cacheKey, info);\n return info;\n }\n\n function getExtendedPublicKey(params: { accountIndex?: number } = {}) {\n return getExtendedPublicKeyInfo(params);\n }\n\n async function deriveAddressAtIndex({\n accountIndex,\n index,\n change = false,\n }: {\n accountIndex?: number;\n index: number;\n change?: boolean;\n }) {\n assertDerivationIndex(\"index\", index);\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const fullPath = `${derivationPathToString(resolvedAccountPath)}/${Number(change)}/${index}`;\n\n const { success, payload } = await TrezorConnect.getAddress({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: fullPath,\n showOnTrezor: false,\n });\n\n if (!success) {\n return undefined;\n }\n\n let finalAddress = payload.address;\n if (chain === Chain.BitcoinCash) {\n const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);\n finalAddress = bchToolbox.stripPrefix(payload.address);\n }\n\n const pubKeyResult = await TrezorConnect.getPublicKey({\n coin,\n ...TREZOR_KEEP_SESSION_PARAMS,\n path: fullPath,\n scriptType: resolvedScriptType.input,\n showOnTrezor: false,\n });\n const pubkey = pubKeyResult.success ? pubKeyResult.payload.publicKey : \"\";\n\n return {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n address: finalAddress,\n change,\n index,\n path: fullPath,\n pubkey,\n };\n }\n\n async function deriveAddressesBatch({\n accountIndex,\n count,\n startIndex = 0,\n change = false,\n }: {\n accountIndex?: number;\n count: number;\n startIndex?: number;\n change?: boolean;\n }) {\n assertDerivationIndex(\"count\", count);\n assertDerivationIndex(\"startIndex\", startIndex);\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n const resolvedAccountPath = getUTXOAccountPath({ accountIndex, chain: utxoChain, derivationPath });\n const accountPath = derivationPathToString(resolvedAccountPath);\n\n const paths = Array.from({ length: count }, (_, i) => ({\n coin,\n path: `${accountPath}/${Number(change)}/${startIndex + i}`,\n showOnTrezor: false,\n }));\n\n const { success, payload } = await TrezorConnect.getAddress({ ...TREZOR_KEEP_SESSION_PARAMS, bundle: paths });\n\n if (!success || !Array.isArray(payload)) {\n return [];\n }\n\n const addresses = await Promise.all(\n payload.map(async (result, i) => {\n let finalAddress = result.address;\n if (chain === Chain.BitcoinCash) {\n const bchToolbox = await getUtxoToolbox(chain as typeof Chain.BitcoinCash);\n finalAddress = bchToolbox.stripPrefix(result.address);\n }\n\n return {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n address: finalAddress,\n change,\n index: startIndex + i,\n path: `${accountPath}/${Number(change)}/${startIndex + i}`,\n pubkey: \"\",\n };\n }),\n );\n\n return addresses;\n }\n\n const hdHelpers = createHDWalletHelpers({\n chain,\n deriveAddress: deriveAddressAtIndex,\n getBalance: toolbox.getBalance,\n getUtxos: (addr: string) => getUtxoApi(chain).getUtxos({ address: addr, fetchTxHex: true }),\n });\n\n return {\n ...toolbox,\n ...hdHelpers,\n address,\n deriveAddressAtIndex,\n deriveAddresses: deriveAddressesBatch,\n getExtendedPublicKey,\n getExtendedPublicKeyInfo,\n signAndBroadcastTransaction,\n signTransaction,\n signTransactionWithMultipleInputs,\n transfer,\n transferFromMultipleAddresses,\n };\n }\n\n default:\n throw new SwapKitError({ errorKey: \"wallet_chain_not_supported\", info: { chain, wallet: WalletOption.TREZOR } });\n }\n}\n\nexport async function getTrezorExtendedPublicKey(\n chain: Chain,\n derivationPath?: DerivationPathArray,\n { accountIndex }: { accountIndex?: number } = {},\n): Promise<HardwareExtendedPublicKeyInfo | undefined> {\n if (![Chain.BitcoinCash, Chain.Bitcoin, Chain.Dash, Chain.Dogecoin, Chain.Litecoin].includes(chain)) {\n throw new SwapKitError({ errorKey: \"wallet_chain_not_supported\", info: { chain, wallet: WalletOption.TREZOR } });\n }\n\n const { TrezorConnect } = await initTrezorConnect();\n const utxoChain = chain as UTXOChain;\n const resolvedDerivationPath = derivationPath ?? (NetworkDerivationPath[chain] as DerivationPathArray);\n const coin = chain.toLowerCase();\n\n const resolvedAccountPath = getUTXOAccountPath({\n accountIndex,\n chain: utxoChain,\n derivationPath: resolvedDerivationPath,\n });\n const path = derivationPathToString(resolvedAccountPath);\n const cacheKey = `${chain}:${path}`;\n const cached = trezorXpubCache.get(cacheKey);\n if (cached) return cached;\n\n const { success, payload } = await TrezorConnect.getPublicKey({ coin, path, showOnTrezor: true });\n\n if (!success) {\n throw new SwapKitError({\n errorKey: \"wallet_trezor_failed_to_get_public_key\",\n info: { chain, error: (payload as { error: string; code?: string }).error || \"Unknown error\" },\n });\n }\n\n const info = {\n accountIndex: getUTXOAccountIndexFromPath(resolvedAccountPath),\n chainCode: payload.chainCode,\n depth: payload.depth,\n fingerprint: payload.fingerprint,\n path: payload.serializedPath,\n publicKey: payload.publicKey,\n xpub: normalizeTrezorExtendedPublicKey(payload.xpub, utxoChain),\n xpubSegwit: tryNormalizeTrezorExtendedPublicKey(payload.xpubSegwit, utxoChain),\n };\n\n trezorXpubCache.set(cacheKey, info);\n return info;\n}\n\nexport const trezorWallet = createWallet({\n connect: ({ addChain, supportedChains, walletType }) =>\n async function connectTrezor(\n chains: Chain[],\n derivationPath: DerivationPathArray,\n { address }: ConnectTrezorOptions = {},\n ) {\n const [chain] = filterSupportedChains({ chains, supportedChains, walletType });\n if (!chain) {\n throw new SwapKitError({\n errorKey: \"wallet_chain_not_supported\",\n info: { chain, wallet: WalletOption.TREZOR },\n });\n }\n\n const TrezorConnect = (await import(\"@trezor/connect-web\")).default;\n\n const trezorConfig = SKConfig.get(\"integrations\").trezor as Record<string, unknown> | undefined;\n const {\n connectSrc,\n coreMode,\n debug,\n interactionTimeout,\n lazyLoad,\n pendingTransportEvent,\n popup,\n transportReconnect,\n transports,\n ...manifestConfig\n } = trezorConfig ?? {};\n const manifest = {\n ...manifestConfig,\n appName: getTrezorManifestValue(trezorConfig?.appName, DEFAULT_TREZOR_MANIFEST.appName),\n appUrl: getTrezorManifestValue(trezorConfig?.appUrl, getDefaultTrezorAppUrl()),\n email: getTrezorManifestValue(trezorConfig?.email, DEFAULT_TREZOR_MANIFEST.email),\n };\n const isLocalhost =\n typeof globalThis.location !== \"undefined\" && [\"localhost\", \"127.0.0.1\"].includes(globalThis.location.hostname);\n const resolvedCoreMode = normalizeTrezorCoreMode(coreMode) ?? \"popup\";\n const resolvedTransports = normalizeTrezorTransports(transports) ?? DEFAULT_TREZOR_TRANSPORTS;\n\n if (trezorSessionDispose) {\n await trezorSessionDispose;\n }\n\n if (isLocalhost) {\n await TrezorConnect.dispose();\n }\n\n await TrezorConnect.init({\n connectSrc: connectSrc as string | undefined,\n coreMode: resolvedCoreMode,\n debug: debug as boolean | undefined,\n interactionTimeout: interactionTimeout as number | undefined,\n lazyLoad: (lazyLoad as boolean | undefined) ?? false,\n manifest,\n pendingTransportEvent: pendingTransportEvent as boolean | undefined,\n popup: (popup as boolean | undefined) ?? true,\n transportReconnect: transportReconnect as boolean | undefined,\n transports: resolvedTransports,\n });\n\n const wallet = await getTrezorWallet({ address, chain, derivationPath });\n\n addChain({ ...wallet, chain, disconnect: disconnectTrezorSession, walletType });\n\n return true;\n },\n directSigningSupport: {\n [Chain.Arbitrum]: true,\n [Chain.Aurora]: true,\n [Chain.Avalanche]: true,\n [Chain.Base]: true,\n [Chain.Berachain]: true,\n [Chain.BinanceSmartChain]: true,\n [Chain.Bitcoin]: true,\n [Chain.BitcoinCash]: true,\n [Chain.Dash]: true,\n [Chain.Ethereum]: true,\n [Chain.Gnosis]: true,\n [Chain.Dogecoin]: true,\n [Chain.Litecoin]: true,\n [Chain.Monad]: true,\n [Chain.Optimism]: true,\n [Chain.Polygon]: true,\n [Chain.XLayer]: true,\n // ZEC: pending PCZT/TrezorConnect validation\n },\n getExtendedPublicKey: getTrezorExtendedPublicKey,\n name: \"connectTrezor\",\n supportedChains: [\n Chain.Arbitrum,\n Chain.Aurora,\n Chain.Avalanche,\n Chain.Base,\n Chain.Berachain,\n Chain.BinanceSmartChain,\n Chain.Bitcoin,\n Chain.BitcoinCash,\n Chain.Dash,\n Chain.Dogecoin,\n Chain.Ethereum,\n Chain.Gnosis,\n Chain.Litecoin,\n Chain.Monad,\n Chain.Optimism,\n Chain.Polygon,\n Chain.XLayer,\n Chain.Zcash,\n ],\n walletType: WalletOption.TREZOR,\n});\n\nexport const TREZOR_SUPPORTED_CHAINS = getWalletSupportedChains(trezorWallet);\n"
6
6
  ],
7
- "mappings": "yCAAA,gBAAS,sBACT,gBACE,4BAEA,eACA,4BACA,4BAEA,eACA,mBACA,kBAEA,yBAEF,gCACE,4BACA,yBACA,iCACA,yBACA,iBACA,iCAKF,qBAAS,eAAY,4BAAU,0BAAwB,8BACvD,uBAAS,+BAAc,8BAiBvB,IAAM,GAAoB,IAAI,IAAoB,CAAC,OAAQ,SAAU,QAAS,gBAAiB,WAAW,CAAC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WAAY,IAClB,EAAM,mBAAoB,IAC1B,EAAM,SAAU,IAChB,EAAM,aAAc,IACpB,EAAM,MAAO,IACb,EAAM,UAAW,IACjB,EAAM,QAAS,IACf,EAAM,UAAW,IACjB,EAAM,UAAW,IACjB,EAAM,OAAQ,IACd,EAAM,UAAW,IACjB,EAAM,SAAU,IAChB,EAAM,QAAS,EAElB,EACA,qBAAsB,GACtB,KAAM,gBACN,gBAAiB,CACf,EAAM,SACN,EAAM,OACN,EAAM,UACN,EAAM,KACN,EAAM,UACN,EAAM,kBACN,EAAM,QACN,EAAM,YACN,EAAM,KACN,EAAM,SACN,EAAM,SACN,EAAM,OACN,EAAM,SACN,EAAM,MACN,EAAM,SACN,EAAM,QACN,EAAM,OACN,EAAM,KACR,EACA,WAAY,EAAa,MAC3B,CAAC,EAEY,GAA0B,GAAyB,EAAY",
8
+ "debugId": "4A73B0E1ED0F2E9D64756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -4,6 +4,7 @@ import type { UTXOType } from "@swapkit/toolboxes/utxo";
4
4
  import type { PCZT, Transaction } from "@swapkit/utxo-signer";
5
5
  export declare const BitcoinLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
6
6
  connect: () => Promise<void>;
7
+ disconnect: () => Promise<void>;
7
8
  getAddress: () => Promise<string>;
8
9
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
9
10
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -16,6 +17,7 @@ export declare const BitcoinLedger: (derivationPathArray?: DerivationPathArray |
16
17
  };
17
18
  export declare const LitecoinLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
18
19
  connect: () => Promise<void>;
20
+ disconnect: () => Promise<void>;
19
21
  getAddress: () => Promise<string>;
20
22
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
21
23
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -28,6 +30,7 @@ export declare const LitecoinLedger: (derivationPathArray?: DerivationPathArray
28
30
  };
29
31
  export declare const BitcoinCashLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
30
32
  connect: () => Promise<void>;
33
+ disconnect: () => Promise<void>;
31
34
  getAddress: () => Promise<string>;
32
35
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
33
36
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -40,6 +43,7 @@ export declare const BitcoinCashLedger: (derivationPathArray?: DerivationPathArr
40
43
  };
41
44
  export declare const DogecoinLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
42
45
  connect: () => Promise<void>;
46
+ disconnect: () => Promise<void>;
43
47
  getAddress: () => Promise<string>;
44
48
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
45
49
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -52,6 +56,7 @@ export declare const DogecoinLedger: (derivationPathArray?: DerivationPathArray
52
56
  };
53
57
  export declare const DashLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
54
58
  connect: () => Promise<void>;
59
+ disconnect: () => Promise<void>;
55
60
  getAddress: () => Promise<string>;
56
61
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
57
62
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -64,6 +69,7 @@ export declare const DashLedger: (derivationPathArray?: DerivationPathArray | st
64
69
  };
65
70
  export declare const ZcashLedger: (derivationPathArray?: DerivationPathArray | string, injectedTransport?: Transport) => {
66
71
  connect: () => Promise<void>;
72
+ disconnect: () => Promise<void>;
67
73
  getAddress: () => Promise<string>;
68
74
  getExtendedPublicKey: (path?: string, xpubVersion?: number) => Promise<string>;
69
75
  signPCZT: (pczt: PCZT) => Promise<PCZT>;
@@ -1 +1 @@
1
- {"version":3,"file":"utxo.d.ts","sourceRoot":"","sources":["../../../../src/ledger/clients/utxo.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,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AE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAE/E,eAAO,MAAM,YAAY;;;;;;;;;CAyEvB,CAAC;AAEH,eAAO,MAAM,uBAAuB,mYAAyC,CAAC;AAW9E,wBAAsB,0BAA0B,CAC9C,KAAK,EAAE,KAAK,EACZ,cAAc,CAAC,EAAE,mBAAmB,EACpC,EAAE,YAAY,EAAE,GAAE;IAAE,YAAY,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/C,OAAO,CAAC,6BAA6B,GAAG,SAAS,CAAC,CAgBpD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/ledger/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAEL,KAAK,EACL,KAAK,mBAAmB,EAUzB,MAAM,kBAAkB,CAAC;AAe1B,OAAO,EAA0C,KAAK,6BAA6B,EAAE,MAAM,sBAAsB,CAAC;AAGlH;;;;;;;GAOG;AACH,MAAM,MAAM,oBAAoB,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,SAAS,CAAA;CAAE,CAAC;AAE/E,eAAO,MAAM,YAAY;;;;;;;;;CAyEvB,CAAC;AAEH,eAAO,MAAM,uBAAuB,mYAAyC,CAAC;AAW9E,wBAAsB,0BAA0B,CAC9C,KAAK,EAAE,KAAK,EACZ,cAAc,CAAC,EAAE,mBAAmB,EACpC,EAAE,YAAY,EAAE,GAAE;IAAE,YAAY,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/C,OAAO,CAAC,6BAA6B,GAAG,SAAS,CAAC,CAmBpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/trezor/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,KAAK,EACL,KAAK,mBAAmB,EAQxB,KAAK,SAAS,EAEf,MAAM,kBAAk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CAAC,6BAA6B,GAAG,SAAS,CAAC,CA0CpD;AAED,eAAO,MAAM,YAAY;;;;;;;;;CA+GvB,CAAC;AAEH,eAAO,MAAM,uBAAuB,6SAAyC,CAAC"}
package/package.json CHANGED
@@ -109,5 +109,5 @@
109
109
  "type-check:go": "tsgo"
110
110
  },
111
111
  "type": "module",
112
- "version": "4.9.10"
112
+ "version": "4.9.12"
113
113
  }
@@ -106,24 +106,25 @@ const BaseLedgerUTXO = ({
106
106
  // Per-call state — each BitcoinLedger/LitecoinLedger/... invocation has its own
107
107
  // transport + btcApp so different consumers (e.g. concurrent MCP sessions) cannot
108
108
  // cross-contaminate each other's Ledger device handle.
109
- let btcApp: InstanceType<typeof BitcoinApp>;
109
+ let btcApp: InstanceType<typeof BitcoinApp> | undefined;
110
110
  let transport: any = null;
111
111
 
112
- async function checkBtcAppAndCreateTransportWebUSB(checkBtcApp = true) {
113
- if (checkBtcApp && !btcApp) {
114
- new SwapKitError("wallet_ledger_connection_error", {
115
- message: `Ledger connection failed:\n${JSON.stringify({ btcApp, checkBtcApp })}`,
116
- });
117
- }
118
-
112
+ async function createTransportWebUSB() {
119
113
  transport ||= injectedTransport ?? (await getLedgerTransport());
114
+ const BitcoinApp = (await import("@ledgerhq/hw-app-btc")).default;
115
+
116
+ btcApp ||= new BitcoinApp({ currency: chain, transport });
117
+ return btcApp;
120
118
  }
121
119
 
122
- async function createTransportWebUSB() {
123
- transport = injectedTransport ?? (await getLedgerTransport());
124
- const BitcoinApp = (await import("@ledgerhq/hw-app-btc")).default;
120
+ async function getBtcApp() {
121
+ return btcApp || (await createTransportWebUSB());
122
+ }
125
123
 
126
- btcApp = new BitcoinApp({ currency: chain, transport });
124
+ async function disconnect() {
125
+ if (!injectedTransport) await transport?.close?.();
126
+ btcApp = undefined;
127
+ transport = null;
127
128
  }
128
129
 
129
130
  const derivationPath =
@@ -135,17 +136,15 @@ const BaseLedgerUTXO = ({
135
136
 
136
137
  return {
137
138
  connect: async () => {
138
- await checkBtcAppAndCreateTransportWebUSB(false);
139
- const BitcoinApp = (await import("@ledgerhq/hw-app-btc")).default;
140
-
141
- btcApp = new BitcoinApp({ currency: chain, transport });
139
+ await getBtcApp();
142
140
  },
141
+ disconnect,
143
142
  getAddress: async () => {
144
143
  const { toCashAddress } = await import("@swapkit/toolboxes/utxo");
145
144
 
146
- await checkBtcAppAndCreateTransportWebUSB(false);
145
+ const app = await getBtcApp();
147
146
 
148
- const { bitcoinAddress: address } = await btcApp.getWalletPublicKey(derivationPath, { format });
147
+ const { bitcoinAddress: address } = await app.getWalletPublicKey(derivationPath, { format });
149
148
 
150
149
  if (!address) {
151
150
  throw new SwapKitError("wallet_ledger_get_address_error", {
@@ -158,9 +157,9 @@ const BaseLedgerUTXO = ({
158
157
  : address;
159
158
  },
160
159
  getExtendedPublicKey: async (path = "84'/0'/0'", xpubVersion = 76067358) => {
161
- await checkBtcAppAndCreateTransportWebUSB(false);
160
+ const app = await getBtcApp();
162
161
 
163
- return btcApp.getWalletXpub({ path, xpubVersion });
162
+ return app.getWalletXpub({ path, xpubVersion });
164
163
  },
165
164
 
166
165
  signPCZT: async (pczt: PCZT): Promise<PCZT> => {
@@ -170,7 +169,7 @@ const BaseLedgerUTXO = ({
170
169
  });
171
170
  }
172
171
 
173
- await createTransportWebUSB();
172
+ const app = await getBtcApp();
174
173
 
175
174
  const { ZcashTransaction, Script } = await import("@swapkit/utxo-signer");
176
175
 
@@ -212,7 +211,7 @@ const BaseLedgerUTXO = ({
212
211
  }
213
212
 
214
213
  const signedTxHex = await signUTXOTransaction(
215
- { btcApp, chain, derivationPath, inputUtxos, tx: unsignedTx as unknown as Transaction },
214
+ { btcApp: app, chain, derivationPath, inputUtxos, tx: unsignedTx as unknown as Transaction },
216
215
  {
217
216
  ...additionalSignParams,
218
217
  expiryHeight: (() => {
@@ -240,9 +239,9 @@ const BaseLedgerUTXO = ({
240
239
  return signedPczt;
241
240
  },
242
241
  signTransaction: async (tx: Transaction, inputUtxos: UTXOType[]) => {
243
- await createTransportWebUSB();
242
+ const app = await getBtcApp();
244
243
 
245
- return signUTXOTransaction({ btcApp, chain, derivationPath, inputUtxos, tx }, additionalSignParams);
244
+ return signUTXOTransaction({ btcApp: app, chain, derivationPath, inputUtxos, tx }, additionalSignParams);
246
245
  },
247
246
 
248
247
  /**
@@ -250,10 +249,10 @@ const BaseLedgerUTXO = ({
250
249
  * Each input can be signed with its own derivation path.
251
250
  */
252
251
  signTransactionWithMultiplePaths: async (tx: Transaction, inputUtxos: UTXOType[], derivationPaths: string[]) => {
253
- await createTransportWebUSB();
252
+ const app = await getBtcApp();
254
253
 
255
254
  return signUTXOTransactionWithMultiplePaths(
256
- { btcApp, chain, derivationPaths, inputUtxos, tx },
255
+ { btcApp: app, chain, derivationPaths, inputUtxos, tx },
257
256
  additionalSignParams,
258
257
  );
259
258
  },
@@ -143,9 +143,12 @@ export async function getLedgerExtendedPublicKey(
143
143
  const path = derivationPathToString(accountPath);
144
144
  const ledgerPath = chain === Chain.Bitcoin || chain === Chain.Litecoin ? path : path.replace(/^m\//, "");
145
145
  const xpubVersion = getNetworkForChain(utxoChain).bip32.public;
146
- const xpub = await signer.getExtendedPublicKey(ledgerPath, xpubVersion);
147
-
148
- return { accountIndex: getUTXOAccountIndexFromPath(accountPath), path, xpub };
146
+ try {
147
+ const xpub = await signer.getExtendedPublicKey(ledgerPath, xpubVersion);
148
+ return { accountIndex: getUTXOAccountIndexFromPath(accountPath), path, xpub };
149
+ } finally {
150
+ await (signer as { disconnect?: () => Promise<void> }).disconnect?.();
151
+ }
149
152
  }
150
153
 
151
154
  async function getWalletMethods({
@@ -462,7 +462,7 @@ function shouldUseTrezorPsbtSigner(chain: Chain) {
462
462
  }
463
463
 
464
464
  function shouldUseTrezorSerializedSigner(chain: Chain) {
465
- return chain === Chain.BitcoinCash || chain === Chain.Dogecoin;
465
+ return chain === Chain.BitcoinCash || chain === Chain.Dash || chain === Chain.Dogecoin;
466
466
  }
467
467
 
468
468
  async function getTrezorWallet<T extends Chain>({
@@ -1337,6 +1337,7 @@ export const trezorWallet = createWallet({
1337
1337
  [Chain.BinanceSmartChain]: true,
1338
1338
  [Chain.Bitcoin]: true,
1339
1339
  [Chain.BitcoinCash]: true,
1340
+ [Chain.Dash]: true,
1340
1341
  [Chain.Ethereum]: true,
1341
1342
  [Chain.Gnosis]: true,
1342
1343
  [Chain.Dogecoin]: true,
@@ -1345,7 +1346,7 @@ export const trezorWallet = createWallet({
1345
1346
  [Chain.Optimism]: true,
1346
1347
  [Chain.Polygon]: true,
1347
1348
  [Chain.XLayer]: true,
1348
- // DASH/ZEC: pending PSBT→TrezorConnect converter validation (V3 plan PR)
1349
+ // ZEC: pending PCZT/TrezorConnect validation
1349
1350
  },
1350
1351
  getExtendedPublicKey: getTrezorExtendedPublicKey,
1351
1352
  name: "connectTrezor",